Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirBroadcast extends PostProcessEvent
/**
* Voting round: the social-recovery guard; `mod` goes to voteMod.
* Otherwise refuses an `l1.sign` already `confirmed`, a network that is
* not Tron, Solana, a known EVM chain or a Bitcoin network, and a Bitcoin
* record without a txid and signed hex.
*
* @returns {Promise<boolean>}
* @memberof VarnirBroadcast
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
if (this.transactions.$entry === "mod") {
try {
return resolve(await this.voteMod());
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
try {
this.signedStream = this.getActivityStreams(
this.transactions.$o.signed
);
this.signedStreamData = this.signedStream.getState();
if (this.signedStreamData.confirmed) {
// confirmed so we don't need to be here at all
return reject("Transaction already broadcasted #CSVEDB");
}
// Fails closed (evm-registry block): a network that is not Tron,
// Solana or a known EVM chain has nothing to broadcast through.
const network = String(this.signedStreamData.network ?? "");
if (this.btcParams(network) !== null) {
// Bitcoin (btc block): a `btcNetworks` entry, and a signed record
// from the Bitcoin presigned path. A disabled entry still
// broadcasts what is already signed (security review M1).
this.requireBtcNetworkInFlight(network);
const btc = this.signedStreamData.btc;
if (!btc || typeof btc.txid !== "string" || !/^[0-9a-f]{64}$/.test(btc.txid) || typeof this.signedStreamData.signed !== "string" || !/^([0-9a-f]{2})+$/.test(this.signedStreamData.signed)) {
throw "Bitcoin: the signed record carries no transaction";
}
} else if (this.evmNonEvmCodes().indexOf(network.toLowerCase()) === -1) {
this.requireEvmNetwork(network);
}
// Now we could check broadcasted which now stores in volatile but I don't think it is needed
// receipt will do the same thing. Although we may have to always write the receipt given it is now determanistic?
// Due to this actually will be safer to check volatile broadcast
//this.volatile = await this.signedStream.getVolatile();
// if(this.signedStreamData.broadcasted || this.signedStreamData.confirmed || this.signedStreamData.receipt) {
// return reject("Transaction already broadcasted #CSVEDB");
// }
resolve(true);
} catch (e) {
this.ActiveLogger.error(
e,
`Rehandled Error - Varnir.Broadcast - ${this.umid}`
);
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
});
}/**
* Commit round (`mod`: commitMod), on every node: unless this node's
* volatile says `broadcasted`, sends the signed transaction for its
* network, writes the txid as `receipt` on the stream and the provider's
* response, `now` and (on success) `broadcasted` / `broadcastedAt` /
* `broadcastedUmid` to the volatile. Then emits `signature-broadcasted`,
* or `signature-broadcasted-fail` when the send failed. Any thrown error
* becomes "Runtime Commit Revert - <message>".
*
* @returns {Promise<any>}
* @memberof VarnirBroadcast
*/ public commit(possibleTerritoriality: boolean): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
// Unlike vote() above, this whole method previously had no top-level
// try/catch at all - any uncaught exception anywhere in here (a
// malformed network value, a library throwing, anything) surfaced
// to a caller only as the engine's own generic
// "(Unhandled Contract Error) {}", with nothing logged anywhere.
// Wrapping the whole thing mirrors vote()'s own pattern immediately
// above and actually surfaces what broke.
try {
if (this.transactions.$entry === "mod") {
return resolve(await this.commitMod());
}
// One branch name for every EVM chain, whichever table it came from.
const branch = this.btcParams(this.signedStreamData.network) !== null
? "bitcoin"
: this.evmNetworkData(this.signedStreamData.network)
? "evm"
: String(this.signedStreamData.network).toLowerCase();
// Usual http timeouts are 30s so lets extend
this.setTimeout(60000);
// For now verbose this method, later can combine
this.volatile = await this.signedStream.getVolatile();
if (!this.volatile.broadcasted) {
// Going to completly change this. Going to assume we should "just broadcast it"
// Then any response. First will check comms as we may have it anyway!
let txid = {} as any;
// Inverse as we may have bad nodes ahead of us
let ethersProvider;
switch (branch) {
case "bitcoin": {
const sent = await this.btcBroadcast();
this.receipt = sent.receipt;
txid = sent.txid;
break;
}
// Tron: each URL of tronRpc in order (the RPC proxy first when the
// owner set `tronNetworks`), keyless, each within its deadline. A
// throw, a timeout, or a reply that is not a Tron verdict
// (HTTP.send resolves {data: null} on a network error; the proxy's
// own errors are {error}; a gateway's may be anything) moves on.
// The first verdict ends the loop, success or chain refusal alike.
// No verdict from any URL is a failed broadcast.
//
// "trx-nile" is the ledger's own spelling (wallet-client.ts
// layer2NetworkCode); it was once misspelled "trx-niles" here,
// which left real signed transactions unbroadcast.
case "trx-shasta":
case "shasta":
case "trx-nile":
case "niles":
case "trx": {
txid.txid = this.signedStreamData.signed.txID;
const tronCode = branch === "trx" ? "trx" : branch.indexOf("shasta") !== -1 ? "shasta" : "niles";
let tronError: any = "No Tron endpoint answered";
this.receipt = null;
for (const url of this.tronRpc(tronCode)) {
try {
const result: any = await this.withDeadline(
() => HTTP.send(`${url}/wallet/broadcasttransaction`, "POST", [], this.signedStreamData.signed, false, 8),
TRON_SEND_TIMEOUT_MS
);
if (this.isTronVerdict(result.data)) {
this.receipt = {
...result.data as any,
transaction: this.signedStreamData.signed
};
break;
}
tronError = result.data === null || result.data === undefined ? `No reply from ${url}` : result.data;
} catch (e) {
tronError = e;
}
}
if (!this.receipt) {
this.receipt = {
error: tronError,
failToBroadcast: true,
};
}
break;
}
// Every EVM chain (evm-registry block): its RPCs in order, each
// pinned to the chain id, so an RPC serving another chain refuses
// ("underlying network changed") instead of broadcasting there. The
// four constant chains have one RPC each, the URL they always used.
case "evm": {
const evmChain = this.requireEvmNetwork(this.signedStreamData.network);
txid = ethers.utils.parseTransaction(this.signedStreamData.signed);
for (const url of evmChain.rpc) {
ethersProvider = this.evmProvider(url, evmChain.chainId);
try {
const provider = ethersProvider;
this.receipt = await this.withDeadline(
() => provider.sendTransaction(this.signedStreamData.signed),
EVM_RPC_TIMEOUT_MS
);
break;
} catch (e) {
this.receipt = {
error: e,
failToBroadcast: true,
};
}
}
break;
}
case "sol": {
//const connection = new Connection("https://api.solana.com", "confirmed");
//const connection = new Connection("https://solana-rpc.publicnode.com", "confirmed");
const connection = new Connection("https://api.mainnet-beta.solana.com/", "confirmed");
try {
// The receipt is just the txid which is just b58 of first signature
const signBuffer = Buffer.from(this.signedStreamData.signed, "hex");
txid = ethers.utils.base58.encode(signBuffer);
const tx = new VersionedTransaction(VersionedMessage.deserialize(Buffer.from(this.signedStreamData.payload, "hex")))
tx.addSignature(new PublicKey(this.signedStreamData.wallet), signBuffer);
this.receipt = await connection.sendRawTransaction(tx.serialize());
} catch (e) {
this.receipt = {
error: e,
failToBroadcast: true,
};
}
break;
}
case "soldev": {
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
try {
// The receipt is just the txid which is just b58 of first signature
const signBuffer = Buffer.from(this.signedStreamData.signed, "hex");
txid = ethers.utils.base58.encode(signBuffer);
const tx = new VersionedTransaction(VersionedMessage.deserialize(Buffer.from(this.signedStreamData.payload, "hex")))
tx.addSignature(new PublicKey(this.signedStreamData.wallet), signBuffer);
this.receipt = await connection.sendRawTransaction(tx.serialize());
} catch (e) {
this.receipt = {
error: e,
failToBroadcast: true,
};
}
break;
}
}
this.signedStreamData.receipt = txid;
// Track broadcast umids?
// if (this.signedStreamData.broadcastedUmid) {
// this.signedStreamData.broadcastedUmid.push(this.umid);
// } else {
// this.signedStreamData.broadcastedUmid = [this.umid];
// }
// Should receipt be an array? that may overcomplicate below
// Any ignorable errors
// Do we still need this?
switch (branch) {
case "trx-shasta":
case "shasta":
case "trx-nile":
case "niles":
if (this.receipt.code === "DUP_TRANSACTION_ERROR") {
// no longer resolve just make sure failedtobroadcast is set
this.receipt.failToBroadcast = false;
//return resolve(true);
}
break;
case "sol":
case "soldev":
if (this.receipt.failToBroadcast && this.receipt.error?.transactionMessage?.indexOf('This transaction has already been processed') !== -1) {
// It did broadcast
this.receipt = txid;
//this.receipt.failToBroadcast = false;
} else {
if(!this.receipt) {
this.receipt = txid;
}
// Cannot create property 'txid' on string '4bnFUu.....'
//this.receipt.txid = txid;
}
break;
case "evm":
// Is there an error in the receipt
if (this.receipt.error) {
this.ActiveLogger.info(
this.receipt,
`Unhandled Checker ${this.signedStreamData.umid} - Stage 2 (umid ${this.umid})`
);
if (
this.findNestedErrorBodyMatching(
this.receipt.error,
"already known"
)
) {
// We can continue as normal this isn't an error really seems to iterate 3-4 times
this.receipt.failToBroadcast = false;
} else {
// Next we can look for nonce expired if it is -1 should be the same
if (
this.findNestedErrorBodyMatching(
this.receipt.error,
`nonce too low: next nonce ${this.signedStreamData.nonce + 1
}, tx nonce ${this.signedStreamData.nonce}`
)
) {
this.receipt.failToBroadcast = false;
} else {
// Can't use .code SERVER_ERROR as that is true for all errors.
// However for the lack of body we should have the reason of 'missing response'
// If that is the case lets not mark it for failure as other nodes may have sent. Then let it
// fail after the timer elapses on confirmation
// reason: "missing response",
// code: "SERVER_ERROR",
// requestBody:
// serverError.code: "ECONNRESET",
if (this.receipt.error.reason === "missing response") {
this.ActiveLogger.info(
this.receipt,
`Unhandled Checker ${this.signedStreamData.umid} - Stage 2.5 (umid ${this.umid}) - MISSING REASON`
);
this.receipt.failToBroadcast = false;
} else {
// Does body contain the hash? If so most likely it was a valid broadcast!
if (
this.findNestedErrorBodyMatching(
this.receipt.error,
this.signedStreamData.receipt.hash
)
) {
// We can continue as normal this isn't an error really seems to iterate 3-4 times
this.receipt.failToBroadcast = false;
} else {
// Is this still needed? Doesn't do much?
// Now check for the transaction if it exists skip (and hopefully minigates should know by now!)
// if (
// ethersProvider &&
// this.receipt.error.transactionHash &&
// this.findNestedErrorBodyMatching(
// this.receipt.error,
// "nonce too low"
// ) &&
// (await ethersProvider.getTransaction(
// this.receipt.error.transactionHash
// ))
// ) {
// // getTransaction can return null but it does check memory pool and it did just send it!
// // Could mark failedToBroadcast as false here but doubt we will be here
// return resolve(true);
// }
if (
this.receipt.error.transactionHash &&
this.findNestedErrorBodyMatching(
this.receipt.error,
"nonce too low"
)
) {
this.ActiveLogger.info(
`Unhandled Checker ${this.signedStreamData.umid} - Stage 3 CATCH ALL (umid ${this.umid})`
);
this.receipt.failToBroadcast = false;
}
}
}
}
}
}
break;
}
this.eventData = {
metadata: (this.transactions as any).metadata || null,
signedStream: this.signedStream.getId(),
umid: this.signedStreamData.umid,
network: this.signedStreamData.network,
nonce: this.signedStreamData.nonce,
token: this.signedStreamData.token,
amount: this.signedStreamData.amount,
wallet: this.signedStreamData.wallet,
walletStream: this.signedStreamData.stream,
sender: this.signedStreamData.sender,
receipt: this.receipt,
};
this.volatile.receipt = this.receipt;
this.volatile.now = this.cDate; // consensus clock, not per-node new Date()
// Dangerous here, As may only failed due to duplicate!
if (!this.receipt.failToBroadcast) {
// Remove this when all updated
//this.signedStreamData.broadcasted = true;
this.volatile.broadcasted = true;
this.volatile.broadcastedAt = this.cDate;
this.volatile.broadcastedUmid = this.umid;
}
this.signedStream.setVolatile(this.volatile);
this.signedStream.setState(this.signedStreamData);
} else {
// May want to remove this. Although it isn't random so if it is here all should get here
if (!this.signedStreamData.receipt) {
// Now it is possible this could be empty with a rewrite but volatile says transaction done.
// So we should also reinject it here to prevent consensus problems
let txid = {} as any;
switch (branch) {
case "bitcoin": {
txid = {txid: this.signedStreamData.btc.txid};
break;
}
case "trx-shasta":
case "shasta":
case "trx-nile":
case "niles":
case "trx": {
txid.txid = this.signedStreamData.signed.txID;
break;
}
case "evm": {
txid = ethers.utils.parseTransaction(
this.signedStreamData.signed
);
break;
}
case "sol":
case "soldev": {
// Can't really calculate it, It *could* be the first signature maybe use that?
txid = this.transactions.$i.admin.txhash;
}
}
this.signedStreamData.receipt = txid;
this.signedStream.setState(this.signedStreamData);
}
// Track broadcast umids? (move to volatile?)
// if (this.signedStreamData.broadcastedUmid) {
// this.signedStreamData.broadcastedUmid.push(this.umid);
// } else {
// this.signedStreamData.broadcastedUmid = [this.umid];
// }
}
//this.signedStream.setVolatile(this.volatile);
//this.signedStream.setState(this.signedStreamData);
// Emit the broadcast event HERE, in commit(), which runs on EVERY committing
// node (proven live: all four nodes write a receipt) - NOT in postProcess(),
// which the engine runs on only one node. That is why the event, and so the
// confirm enqueue, reached only that node's minigate and left every other
// node's confirm-pending queue empty - a withdrawal broadcast by a node that
// then can't get ConfirmWithdraw committed stayed pending with no failover.
// Mirrors Varnir.ConfirmWithdraw, whose "confirmation" event (emitted in
// commit) already reaches all four minigates. eventData is normally set in
// the broadcast branch above; build it from committed state as a fallback so
// a node that took the already-broadcast branch still fires.
if (!this.eventData) {
this.eventData = {
metadata: (this.transactions as any).metadata || null,
signedStream: this.signedStream.getId(),
umid: this.signedStreamData.umid,
network: this.signedStreamData.network,
nonce: this.signedStreamData.nonce,
token: this.signedStreamData.token,
amount: this.signedStreamData.amount,
wallet: this.signedStreamData.wallet,
walletStream: this.signedStreamData.stream,
sender: this.signedStreamData.sender,
receipt: this.signedStreamData.receipt || (this.receipt ?? null),
};
}
if (this.receipt && this.receipt.failToBroadcast) {
this.event.emit("signature-broadcasted-fail", this.eventData);
} else {
this.event.emit("signature-broadcasted", this.eventData);
}
resolve(true);
} catch (e) {
this.ActiveLogger.error(
e,
`Rehandled Error - Varnir.Broadcast commit() - ${this.umid}`
);
return reject("Runtime Commit Revert - " + (e instanceof Error ? e.message : String(e)));
}
});
} 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;
}/**
* A provider pinned to `chainId`: ethers checks eth_chainId before sending
* and refuses another chain ("underlying network changed"). Not
* StaticJsonRpcProvider: given a network it trusts it and never asks the
* RPC, so a URL serving another chain would get the transaction. Each
* request is capped at the per-URL timeout; withDeadline caps the attempt.
*/ private evmProvider(url: string, chainId: number): any {
return new ethers.providers.JsonRpcProvider({url, timeout: EVM_RPC_TIMEOUT_MS}, {chainId, name: `evm-${chainId}`});
}/** A Tron broadcast verdict: `result: true`, or one of Tron's own response codes. */
private isTronVerdict(data: any): boolean {
if (!data || typeof data !== "object" || Array.isArray(data)) {
return false;
}
return data.result === true || (typeof data.code === "string" && TRON_VERDICT_CODES.indexOf(data.code) !== -1);
}/** * The Tron URLs for `code`, tried in order: the owner-set * `tronNetworks[code].rpc` when stored, else the keyless public endpoints. */
private tronRpc(code: "shasta" | "niles" | "trx"): string[] {
const wrapper: any = this.getContractData();
const stored = wrapper && wrapper.data ? wrapper.data.tronNetworks : undefined;
this.assertTronNetworks(stored);
if (stored && Object.keys(stored).indexOf(code) !== -1) {
return stored[code].rpc.slice();
}
const constants: {[code: string]: string[]} = {
shasta: ["https://api.shasta.trongrid.io"],
niles: ["https://nile.trongrid.io"],
trx: ["https://api.trongrid.io", "https://tron-rpc.publicnode.com"],
};
return constants[code].slice();
}/**
* The `mod` validator for `tronNetworks`: absent, or an object keyed by
* shasta / niles / trx whose values are exactly `{rpc: string[]}`.
*/ private assertTronNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "tronNetworks must be an object keyed by Tron network code";
}
for (const code of Object.keys(value)) {
if (["shasta", "niles", "trx"].indexOf(code) === -1) {
throw `tronNetworks: ${code} is not a Tron network`;
}
const entry = value[code];
if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).length !== 1 || Object.keys(entry)[0] !== "rpc") {
throw `tronNetworks.${code} must be exactly {rpc}`;
}
this.assertRpcUrls(`tronNetworks.${code}.rpc`, entry.rpc);
}
}/** * 1 to 4 plain https URLs carrying no API key. Contract data is public: a * keyed provider URL (Alchemy /v2/<key>, Infura /v3/<key>, QuickNode * /<token>/) must never land in it. The same rules as the evm-registry * block's `rpc` check, which stays verbatim there (canonical copy). */
private assertRpcUrls(label: string, rpc: unknown): void {
if (!Array.isArray(rpc) || rpc.length < 1 || rpc.length > 4) {
throw `${label} 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 `${label}: ${url} is not a plain https URL`;
}
const urlPath = url.slice(8).indexOf("/") === -1 ? "" : url.slice(8 + url.slice(8).indexOf("/"));
if (/[A-Za-z0-9_-]{24,}/.test(urlPath)) {
throw `${label}: ${url} looks like it carries an API key`;
}
}
}/** The `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/** * 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: any, identity: string): boolean {
return contract.getAuthorities().some((v: any) => v.public === identity);
}/** * Owner-only `mod`: writes this contract's `evmNetworks` (the evm-registry * block's chain table), `btcNetworks` (the btc block's) and `tronNetworks` * (the Tron send URLs). Each whole map * is validated first; one bad field refuses the write. */
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);
this.assertTronNetworks(this.transactions.$i.owner.tronNetworks);
return true;
}/** `mod` commit: stores `evmNetworks`, `btcNetworks` and `tronNetworks` (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.tronNetworks = this.transactions.$i.owner.tronNetworks ?? cd.tronNetworks ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}/** 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)`;
}
}
}/** * Broadcast a signed Bitcoin transaction (spec §7): POST the raw hex to * each keyless Esplora URL in `btcNetworks[code].broadcast`, then ask that * same server for the transaction's status. HTTP.send only returns JSON * bodies, and Esplora answers a broadcast in plain text, so the status * read is what proves the transaction reached a mempool (or a block). * Resending is always safe: the txid is fixed by the signed bytes. Why a * server refused is not classified here; the gateway does that through * its own provider (testmempoolaccept, sendrawtransaction). */
private async btcBroadcast(): Promise<{receipt: any; txid: any}/** 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};
}/** Whether `match` appears in `error.body` or in the body of any nested `error.error`. */
private findNestedErrorBodyMatching(error: any, match: string): boolean {
// Does the current error body contain the match?
if (error.body && error.body?.indexOf(match) !== -1) {
return true;
}
// Does the nested error contain the match?
if (error.error) {
return this.findNestedErrorBodyMatching(error.error, match);
}
return false;
}