Cash Assembly: Support for native cash assembly evaluations and primitive method resolution

This commit is contained in:
Kuldeep
2026-08-06 10:40:02 +00:00
parent 44b9ceee79
commit e76ff01192
13 changed files with 2317 additions and 741 deletions
+40
View File
@@ -0,0 +1,40 @@
import { bigIntToVmNumber, utf8ToBin } from '@bitauth/libauth';
import { CashAssemblyNumberNotSafeIntegerError, CashAssemblyUnsupportedValueTypeError } from './errors.ts';
/**
* Converts a value into bytes representation.
*
* @param {unknown} value - Value to encode, should be one of: Uint8Array, bigint, boolean, string, or a safe integer number.
* @param {string} valueIdentifier - Identifier used in error messages.
* @returns {Uint8Array} Bytes representation of the value.
* @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number is not a safe integer.
* @throws {@link CashAssemblyUnsupportedValueTypeError} When the value type cannot be resolved.
*/
export const convertValueToBytes = (value: unknown, valueIdentifier: string): Uint8Array => {
if (value instanceof Uint8Array) {
return value;
}
if (typeof value === 'bigint') {
return bigIntToVmNumber(value);
}
if (typeof value === 'boolean') {
// The BCH VM treats an empty byte array as false and any nonempty byte array as true.
return new Uint8Array(value ? [ 1 ] : []);
}
if (typeof value === 'string') {
return utf8ToBin(value);
}
if (typeof value === 'number') {
if (Number.isSafeInteger(value) === true) {
return bigIntToVmNumber(BigInt(value));
}
throw new CashAssemblyNumberNotSafeIntegerError(valueIdentifier, value);
}
throw new CashAssemblyUnsupportedValueTypeError(valueIdentifier, typeof value);
};
+61
View File
@@ -0,0 +1,61 @@
/**
* Detects whether a string is a pure CashAssembly expression.
*
* CashAssembly expressions look like `$(<variable>)` or `$(<a> <b>)`. This pattern checks
* that the entire string is one such expression and nothing else. It will not match if
* there is other text surrounding the expression.
*
* For example:
* `$(<fee>)` matches (a full expression)
* `OP_DUP $(<fee>)` does not match (extra text before it)
* `$()` does not match (empty expression)
*/
export const CASHASSEMBLY_EXPRESSION_PATTERN = /^\$\([^)]+\)$/;
/**
* Finds all CashAssembly evaluations embedded in a larger string.
*
* An evaluation looks like `$(...)`, for example `$(<fee>)` or `$(<a> <b>)`. This pattern
* locates every occurrence in the input and returns them all (global flag `g`).
* Empty evaluations `$()` are intentionally excluded because they reference no variables.
*
* For example, scanning `"OP_DUP <$(<pubkeyHash>)> OP_HASH160 $(<fee>)"` would return
* `['$(<pubkeyHash>)', '$(<fee>)']`.
*/
export const CASHASSEMBLY_EVALUATION_PATTERN = /\$\([^)]+\)/g;
/**
* Extracts variable names from angle-bracket references inside a CashAssembly evaluation.
*
* Inside an evaluation like `$(<pubkeyHash> <fee>)`, variables are referenced as `<name>`.
* This pattern captures the name between the brackets. The global flag `g` allows iterating
* over every variable reference in a single evaluation string.
*
* For example, running this against `$(<pubkeyHash> <fee>)` would return the variable names
* `["pubkeyHash", "fee"]`.
*/
export const CASHASSEMBLY_VARIABLE_PATTERN = /<([^>]+)>/g;
/**
* Identifies CashAssembly literal tokens that appear inside angle-bracket push statements.
*
* Inside an evaluation, not everything between `<` and `>` is a variable name. Literals are
* also valid push contents: numeric literals (e.g. `<0>`, `<32>`), hex literals (`<0x02>`),
* binary literals (`<0b1010>`), and string literals (`<"minting">`, `<'hello'>`). This pattern
* matches any captured token that starts with a digit or a quote character.
*/
export const CASHASSEMBLY_LITERAL_TOKEN_PATTERN = /^[0-9"']/;
/**
* Matches a single dot variable method reference inside an angle-bracket identifier.
*
* Used to detect primitive method references such as `expiry.toIso8601`.
*
* For example:
* `expiry.toIso8601` matches (base `expiry`, method `toIso8601`)
* `requestedSatoshis` does not match (no method)
* `key.schnorr_signature.all_outputs` does not match (more than one dot)
* `key.public_key` matches the pattern shape but it is only resolved
* when `hint` maps to a primitive
*/
export const CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN = /^([^.]+)\.([^.]+)$/;
+85
View File
@@ -0,0 +1,85 @@
/* eslint-disable max-classes-per-file */
/**
* Error thrown when a required variable is missing.
*/
export class CashAssemblyRequiredVariableMissingError extends Error {
constructor(variableNames?: string[]) {
const defaultMessage = 'Missing required variable';
if (variableNames !== undefined && variableNames.length > 0) {
super(`${defaultMessage}: variableNames [${variableNames.join(', ')}]`);
} else {
super(defaultMessage);
}
}
}
/**
* Error thrown when cash assembly compilation fails.
*/
export class CashAssemblyCompilationFailedError extends Error {
constructor(message?: string) {
const defaultMessage = 'Cash assembly compilation failed';
super(message ? `${defaultMessage}: ${message}` : defaultMessage);
}
}
/**
* Error thrown when a variable's runtime type does not match the type required for compilation.
*/
export class CashAssemblyVariableTypeMismatchError extends Error {
constructor(variableKey: string, expectedType: string, actualType: string) {
const defaultMessage = 'Variable type mismatch';
super(`${defaultMessage}: variableKey "${variableKey}", expected ${expectedType}, got ${actualType}`);
}
}
/**
* Error thrown when a supported primitive hint does not expose the requested method.
*/
export class CashAssemblyPrimitiveMethodMissingError extends Error {
constructor(identifier: string, methodName: string, hint: string) {
const defaultMessage = 'CashAssembly primitive method does not exist';
super(`${defaultMessage}: identifier "${identifier}", methodName "${methodName}", hint "${hint}"`);
}
}
/**
* Error thrown when a value cannot be resolved as bytes.
*/
export class CashAssemblyUnsupportedValueTypeError extends Error {
constructor(identifier: string, returnedType: string) {
const defaultMessage = 'CashAssembly value type is unsupported for byte resolution';
super(`${defaultMessage}: identifier "${identifier}", returnedType "${returnedType}"`);
}
}
/**
* Error thrown when a number cannot be safely encoded as a CashAssembly VM number.
*/
export class CashAssemblyNumberNotSafeIntegerError extends Error {
constructor(identifier: string, value: number) {
const defaultMessage = 'CashAssembly number is not a safe integer';
super(`${defaultMessage}: identifier "${identifier}", got ${String(value)}`);
}
}
/**
* Error thrown when a supported primitive is selected but its value is missing when provided in the variables map.
*/
export class CashAssemblyPrimitiveVariableMissingError extends Error {
constructor(identifier: string, variableName: string) {
const defaultMessage = 'CashAssembly primitive variable is missing from the variables map';
super(`${defaultMessage}: identifier "${identifier}", variableName "${variableName}"`);
}
}
/**
* Error thrown when compiled evaluation bytes cannot be decoded as a VM number.
*/
export class CashAssemblyVmNumberDecodeError extends Error {
constructor(reason: string) {
const defaultMessage = 'CashAssembly evaluation could not be decoded as a VM number';
super(`${defaultMessage}: ${reason}`);
}
}
+353
View File
@@ -0,0 +1,353 @@
/**
* Utilities for parsing, extracting, and compiling CashAssembly expressions.
*
* CashAssembly is the scripting language used by Bitauth templates to describe Bitcoin Cash
* locking and unlocking scripts.
*
* ## Syntax (CashAssembly)
*
* `<expression>` is a push statement. Compiles the contents and pushes the result onto the VM stack.
* `<someKey.public_key>` pushes the 33 byte compressed public key. `<1>` pushes the integer 1.
*
* `$(<expression>)` is an evaluation. Runs the inner script in the VM and inserts the top stack
* item as VM bytecode.
* `$(<someKey.public_key> OP_HASH160)` inserts the HASH160 of the public key.
*
* `<$(<expression>)>` is a push of an evaluation result. It evaluates first then pushes.
* For a P2PKH locking script example see
* `OP_DUP OP_HASH160 <$(<someKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG`.
*
* `variableId.operation` is a variable with a compiler resolved operation. `someKey.public_key`
* produces the public key bytes. `someKey.schnorr_signature.all_outputs` produces a Schnorr
* signature.
*
* Opcodes (`OP_DUP`, `OP_HASH160`, and similar) are inserted as their bytecode equivalent directly.
*
* ## Name resolution priority (CashAssembly)
*
* When the compiler encounters an identifier it resolves it in this order.
* 1. Opcode always wins. Naming a variable or script `OP_ADD` will not shadow it.
* 2. Variable shadows scripts of the same name.
* 3. Script is the script's bytecode.
*
* ## Resolution Order (CashAssembly + Primitive Method Resolution)
*
* Supported `<base.method>` pushes are resolved to bytes before CashAssembly compiles.
* Inside CashAssembly the order is Opcode then Variable then Script.
*/
import type { CompilerBch } from '@bitauth/libauth';
import { binToHex, binToUtf8, createCompilerBch, vmNumberToBigInt } from '@bitauth/libauth';
import type { XOInvitationVariableValue, XOTemplate } from '@xo-cash/types';
import {
CashAssemblyCompilationFailedError,
CashAssemblyVariableTypeMismatchError,
CashAssemblyRequiredVariableMissingError,
CashAssemblyVmNumberDecodeError,
} from './errors.ts';
import {
CASHASSEMBLY_EVALUATION_PATTERN,
CASHASSEMBLY_EXPRESSION_PATTERN,
CASHASSEMBLY_LITERAL_TOKEN_PATTERN,
CASHASSEMBLY_VARIABLE_PATTERN,
} from './defaults.ts';
import { convertValueToBytes } from './bytes.ts';
import { resolvePrimitiveMethodBytes } from './primitive-evaluations.ts';
/**
* Supported decode modes for compiled CashAssembly evaluation bytes.
*/
export type CompiledCashAssemblyDecodeMode = 'utf8' | 'hex' | 'boolean' | 'bigint' | 'uint8array';
/**
* Parameters for compiling CashAssembly string.
*/
export type CompileCashAssemblyStringParameters = {
/**
* Text that may embed CashAssembly evaluations such as `$(<fee>)` or `$(<expiry.toIso8601>)`.
*/
cashAssemblyText: string;
/**
* Used for both primitive method evaluations and normal CashAssembly compilation.
*/
variables: Record<string, XOInvitationVariableValue | Uint8Array>;
/**
* The mode to decode compiled evaluation bytes into a string.
*/
evaluationDecodeMode?: CompiledCashAssemblyDecodeMode;
/**
* Optional template variable definitions. When provided, each `<name.method>` push whose `hint`
* maps to a supported primitive class is resolved to bytes before CashAssembly compilation.
*/
templateVariables?: XOTemplate['variables'];
};
/**
* Checks if the expression is a CashAssembly expression.
*
* @param {unknown} expression - The expression to check.
* @returns {boolean} True if the expression is a CashAssembly expression, false otherwise.
*/
export const isCashAssemblyExpression = (expression: unknown): boolean => {
return typeof expression === 'string' && CASHASSEMBLY_EXPRESSION_PATTERN.test(expression);
};
/**
* Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.
*
* @param {string} text - The input string to scan for CashAssembly evaluations.
* @returns {string[]} An array of evaluation strings found in the input.
*
* @example
* extractCashAssemblyEvaluations("OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)");
* // returns ['$(<foo>)', '$(<bar>)']
*/
export const extractCashAssemblyEvaluations = (text: string): string[] => {
return text.match(CASHASSEMBLY_EVALUATION_PATTERN) ?? [];
};
/**
* Returns the segment of `identifier` before the first `.`.
*
* When there is no `.`, returns `identifier` unchanged.
* Multi segment identifiers such as `foo.bar.baz` resolve to `foo`.
*
* @param {string} identifier - Identifier that may contain a dot.
* @returns {string} The base name before the first `.`.
*/
const resolveIdentifierBaseName = (identifier: string): string => {
const firstDotIndex = identifier.indexOf('.');
if (firstDotIndex === -1) {
return identifier;
}
return identifier.slice(0, firstDotIndex);
};
/**
* Extracts unique variable identifiers enclosed in angle brackets from each evaluation string.
*
* CashAssembly literal tokens such as hex bytes, numbers, and quoted strings are excluded via
* {@link CASHASSEMBLY_LITERAL_TOKEN_PATTERN}. For example, `<0x02>` and `<"minting">` are not returned.
*
* @param {string[]} evaluations - An array of evaluation strings from which to extract variable names.
* @returns {string[]} An array of variable names.
*/
export const extractVariablesFromEvaluations = (evaluations: string[]): string[] => {
const uniqueVariables = new Set<string>();
for (const evaluation of evaluations) {
for (const [ , extractedIdentifier ] of evaluation.matchAll(CASHASSEMBLY_VARIABLE_PATTERN)) {
if (CASHASSEMBLY_LITERAL_TOKEN_PATTERN.test(extractedIdentifier)) {
continue;
}
uniqueVariables.add(extractedIdentifier);
}
}
return [ ...uniqueVariables ];
};
/**
* Decodes compiled CashAssembly evaluation bytes into a string representation.
*
* 'evaluationDecodeMode' determines how the evaluation bytes are interpreted and presented.
* Use `bigint` for numeric values like satoshis, `utf8` for text labels, `hex` for binary data
* such as hashes, and `boolean` to represent boolean values.
*
* @param {Uint8Array} compiledResult - The compiled evaluation bytecode.
* @param {CompiledCashAssemblyDecodeMode} [evaluationDecodeMode='utf8'] - The decode mode used to convert
* bytes to text.
* @returns {string} The decoded value as a string suitable for inline replacement.
* @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and the bytes are not a VM number.
*/
export const decodeCompiledCashAssemblyEvaluation = (
compiledResult: Uint8Array,
evaluationDecodeMode: CompiledCashAssemblyDecodeMode = 'utf8',
): string => {
// Converts the byte array to a string.
if (evaluationDecodeMode === 'uint8array') {
return String(compiledResult);
}
// Converts the byte array to a boolean string, converting the evaluation result into a true or a false.
if (evaluationDecodeMode === 'boolean') {
return compiledResult.length === 0 ? 'false' : 'true';
}
// Converts the byte array to a hex string.
if (evaluationDecodeMode === 'hex') {
return binToHex(compiledResult);
}
// Converts the byte array to a bigint string.
if (evaluationDecodeMode === 'bigint') {
const vmNumberResult = vmNumberToBigInt(compiledResult);
if (typeof vmNumberResult === 'bigint') {
return vmNumberResult.toString();
}
throw new CashAssemblyVmNumberDecodeError(vmNumberResult);
}
// Converts the byte array to a utf8 string.
return binToUtf8(compiledResult);
};
/**
* Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.
*
* @param {CompilerBch} compiler - The libauth compiler from {@link compileCashAssemblyEvaluations}.
* @param {string} evaluation - The specific evaluation string to compile.
* @param {Record<string, Uint8Array>} variables - A record mapping variable names to their values.
* @returns {Uint8Array} The compiled bytecode.
* @throws {@link CashAssemblyRequiredVariableMissingError} If a required variable is not present.
* @throws {@link CashAssemblyVariableTypeMismatchError} If a variable value is not a Uint8Array.
* @throws {@link CashAssemblyCompilationFailedError} If libauth compilation fails.
*/
export const generateCashAssemblyBytecode = (compiler: CompilerBch, evaluation: string, variables: Record<string, Uint8Array>): Uint8Array => {
const variableNames = extractVariablesFromEvaluations([ evaluation ]);
// Validate that all required variables are provided
const missingVariables = variableNames.filter((name: string) => !Object.hasOwn(variables, name));
if (missingVariables.length > 0) {
throw new CashAssemblyRequiredVariableMissingError(missingVariables);
}
// Construct the bytecode object using the keys in variableNames, mapping to the values in variables
const bytecode: Record<string, Uint8Array> = {};
for (const variableName of variableNames) {
const value = variables[variableName];
// By the time execution reaches this point, the value should be a Uint8Array.
if (!(value instanceof Uint8Array)) {
throw new CashAssemblyVariableTypeMismatchError(variableName, 'Uint8Array', typeof value);
}
bytecode[variableName] = value;
}
const compiledBytecode = compiler.generateBytecode({
data: { bytecode },
scriptId: evaluation,
});
if (!compiledBytecode.success) {
// Collapse libauth's full errors list into one string because
// CashAssemblyCompilationFailedError only carries a single message.
let compilationFailureMessage = 'unknown compilation failure';
if ('errors' in compiledBytecode && compiledBytecode.errors.length > 0) {
compilationFailureMessage = compiledBytecode.errors.map((compilationError) => compilationError.error).join('; ');
}
throw new CashAssemblyCompilationFailedError(compilationFailureMessage);
}
return compiledBytecode.bytecode;
};
/**
* Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.
*
* @param {string[]} evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)']).
* @returns {CompilerBch} A Libauth compiler instance for use with these evaluations.
*/
export const compileCashAssemblyEvaluations = (evaluations: string[]): CompilerBch => {
// Create a scripts object where each key is the evaluation and the value is also the evaluation
const scripts: Record<string, string> = {};
for (const evaluation of evaluations) {
scripts[evaluation] = evaluation;
}
// Get the variable names from the evaluations.
const variableNames = extractVariablesFromEvaluations(evaluations);
// Register each base name once. Dotted pushes share one WalletData entry under the base name.
const variables: Record<string, { type: 'WalletData' }> = {};
for (const variableName of variableNames) {
variables[resolveIdentifierBaseName(variableName)] = { type: 'WalletData' as const };
}
// Create the libauth compiler.
const compiler = createCompilerBch({
scripts,
variables,
});
return compiler;
};
/**
* Compiles all CashAssembly evaluations in a text string and replaces each evaluation
* with a decoded string representation.
*
* @param {CompileCashAssemblyStringParameters} parameters - Parameters for compiling the CashAssembly string.
* @param {string} parameters.cashAssemblyText - The string with CashAssembly evaluations.
* @param {Record<string, XOInvitationVariableValue | Uint8Array>} parameters.variables - Object mapping
* variable names to values for compilation.
* @param {CompiledCashAssemblyDecodeMode} [parameters.evaluationDecodeMode='utf8'] - The decode mode used
* after each evaluation is compiled. See {@link decodeCompiledCashAssemblyEvaluation}.
* @param {XOTemplate['variables']} [parameters.templateVariables] - Optional template variable definitions
* used to resolve supported `<name.method>` pushes via each variable's `hint`.
* @returns {string} Compiled text with all evaluations replaced by decoded string values.
* @throws {@link CashAssemblyRequiredVariableMissingError} When a required variable is not present in the variables map.
* @throws {@link CashAssemblyPrimitiveMethodMissingError} When a supported primitive hint has an unknown method.
* @throws {@link CashAssemblyPrimitiveVariableMissingError} When a supported primitive method is missing its runtime value.
* @throws {@link CashAssemblyUnsupportedValueTypeError} When a primitive method return type cannot be embedded as bytes.
* @throws {@link CashAssemblyNumberNotSafeIntegerError} When a number variable is not a safe integer.
* @throws {@link CashAssemblyVmNumberDecodeError} When `evaluationDecodeMode` is `bigint` and an evaluation is not a VM number.
*/
export const compileCashAssemblyString = (parameters: CompileCashAssemblyStringParameters): string => {
const { cashAssemblyText, variables, evaluationDecodeMode = 'utf8', templateVariables } = parameters;
return cashAssemblyText.replace(CASHASSEMBLY_EVALUATION_PATTERN, (evaluation) => {
// Extract variable identifiers required by the current evaluation.
const variableNames = extractVariablesFromEvaluations([ evaluation ]);
const primitiveMethodBytes = resolvePrimitiveMethodBytes({
identifiers: variableNames,
templateVariables,
variables,
});
// Prefer resolved method bytes. Fall back to converting the raw variable value.
const missingVariables = variableNames.filter((variableName) => {
if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {
return false;
}
return Object.hasOwn(variables, variableName) === false;
});
if (missingVariables.length > 0) {
throw new CashAssemblyRequiredVariableMissingError(missingVariables);
}
// Convert each variable to its bytes before compilation.
const variableBytes: Record<string, Uint8Array> = {};
for (const variableName of variableNames) {
if (Object.hasOwn(primitiveMethodBytes, variableName) === true) {
variableBytes[variableName] = primitiveMethodBytes[variableName];
continue;
}
variableBytes[variableName] = convertValueToBytes(variables[variableName], variableName);
}
// Compile the evaluation in isolation.
const compiler = compileCashAssemblyEvaluations([ evaluation ]);
// Generate the bytes for the evaluation.
const compilationResult: Uint8Array = generateCashAssemblyBytecode(compiler, evaluation, variableBytes);
// Decode the bytes into a string as per the decode mode.
return decodeCompiledCashAssemblyEvaluation(compilationResult, evaluationDecodeMode);
});
};
+5
View File
@@ -0,0 +1,5 @@
export * from './evaluations.ts';
export * from './primitive-evaluations.ts';
export * from './bytes.ts';
export * from './defaults.ts';
export * from './errors.ts';
@@ -0,0 +1,216 @@
import {
FungibleTokenAmount,
NFTCommitment,
PublicKey,
Satoshis,
SchnorrSignature,
TemplateIdentifier,
Timestamp,
TokenCategory,
TransactionHash,
} from '@xo-cash/primitives';
import { XOTemplatePrimitiveTypes } from '@xo-cash/types';
import type { XOTemplate, XOTemplatePrimitiveType } from '@xo-cash/types';
import { CashAssemblyPrimitiveMethodMissingError, CashAssemblyPrimitiveVariableMissingError } from './errors.ts';
import { CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN } from './defaults.ts';
import { convertValueToBytes } from './bytes.ts';
/**
* Template hint values mapped to a primitive class for resolving primitive method evaluations.
* Keys are values from XOTemplatePrimitiveTypes.
*/
const PRIMITIVE_BY_TEMPLATE_HINT = {
[XOTemplatePrimitiveTypes.FUNGIBLE_TOKEN_AMOUNT]: FungibleTokenAmount,
[XOTemplatePrimitiveTypes.NFT_COMMITMENT]: NFTCommitment,
[XOTemplatePrimitiveTypes.PUBLIC_KEY]: PublicKey,
[XOTemplatePrimitiveTypes.SATOSHIS]: Satoshis,
[XOTemplatePrimitiveTypes.SCHNORR_SIGNATURE]: SchnorrSignature,
[XOTemplatePrimitiveTypes.TEMPLATE_IDENTIFIER]: TemplateIdentifier,
[XOTemplatePrimitiveTypes.TIMESTAMP]: Timestamp,
[XOTemplatePrimitiveTypes.TOKEN_CATEGORY]: TokenCategory,
[XOTemplatePrimitiveTypes.TRANSACTION_HASH]: TransactionHash,
} as const;
type SupportedPrimitiveHint = keyof typeof PRIMITIVE_BY_TEMPLATE_HINT;
/**
* Inputs needed to call a primitive method for a `name.method` push.
*/
type CallPrimitiveMethodParameters = {
/**
* Full push identifier from the evaluation, for example `amount.toSatoshis`.
*/
identifier: string;
/**
* Method name to call on the constructed primitive, for example `toIso8601`.
*/
methodName: string;
/**
* Value for the variable.
*/
value: unknown;
/**
* Supported template hint that selects the primitive class.
*/
hint: SupportedPrimitiveHint;
};
/**
* Inputs needed to resolve primitive method pushes from extracted CashAssembly identifiers.
*/
export type ResolvePrimitiveMethodBytesParameters = {
/**
* Variable identifiers from {@link extractVariablesFromEvaluations}, for example
* `['amount.toSatoshis', 'fee.toSatoshis']`.
*/
identifiers: string[];
/**
* Variable names and values object.
*/
variables: Record<string, unknown>;
/**
* Template variable definitions. When omitted, no primitive methods are resolved.
* The `hint` on each entry selects the primitive class.
*/
templateVariables?: XOTemplate['variables'];
};
/**
* Returns true when `hint` maps to a supported primitive class in `PRIMITIVE_BY_TEMPLATE_HINT`.
*
* @param {XOTemplatePrimitiveType | undefined} hint - Template variable hint.
* @returns {boolean} True when the hint selects a supported primitive class.
*/
const isSupportedPrimitiveHint = (hint: XOTemplatePrimitiveType | undefined): hint is SupportedPrimitiveHint => {
return hint !== undefined && Object.hasOwn(PRIMITIVE_BY_TEMPLATE_HINT, hint) === true;
};
/**
* Returns true when `methodName` is an own function on the primitive class for `hint`.
*
* @param {SupportedPrimitiveHint} hint - Supported template hint.
* @param {string} methodName - Method name from the evaluation text, for example `toSatoshis`.
* @returns {boolean} True when that class exposes the named method.
*/
const canResolvePrimitiveMethod = (hint: SupportedPrimitiveHint, methodName: string): boolean => {
const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];
// Check own properties only so inherited Object.prototype names are rejected without needing a value.
if (Object.hasOwn(PrimitiveClass.prototype, methodName) === false) {
return false;
}
return typeof Reflect.get(PrimitiveClass.prototype, methodName) === 'function';
};
/**
* Constructs a primitive from a raw value and calls one instance method on it.
*
* Call only after `canResolvePrimitiveMethod` is true for the same hint and method.
*
* @param {CallPrimitiveMethodParameters} parameters - Identifier, method, value, and supported hint.
* @returns {unknown} Method return value, later encoded as CashAssembly push bytes.
* @throws {@link CashAssemblyPrimitiveMethodMissingError} When the prototype member is not a function.
* @throws When the primitive constructor rejects the raw value (validation errors from `@xo-cash/primitives`).
*/
const callPrimitiveMethod = (parameters: CallPrimitiveMethodParameters): unknown => {
const { identifier, methodName, value, hint } = parameters;
const PrimitiveClass = PRIMITIVE_BY_TEMPLATE_HINT[hint];
// Constructing runs each primitive's own input validation (range checks, hex length, etc).
// `as never` satisfies TypeScript across constructors that accept different input shapes.
const primitiveInstance = new PrimitiveClass(value as never);
// Same prototype member canResolvePrimitiveMethod already verified as an own function.
const primitiveMethod = Reflect.get(PrimitiveClass.prototype, methodName);
if (typeof primitiveMethod !== 'function') {
throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);
}
return primitiveMethod.call(primitiveInstance);
};
/**
* Resolves supported `base.method` identifiers to CashAssembly variable bytes.
*
* Each single dot identifier whose `hint` maps to a supported primitive is resolved and stored under
* the full identifier (`base.method`). Unsupported or multi dot identifiers are left for CashAssembly.
*
* When `templateVariables` is omitted, returns an empty map.
*
* @param {ResolvePrimitiveMethodBytesParameters} parameters - Identifiers, values, and optional template metadata.
* @returns {Record<string, Uint8Array>} Resolved method identifiers mapped to bytes for CashAssembly pushes.
* @throws {@link CashAssemblyPrimitiveMethodMissingError} When the hint is a supported primitive but the method is missing.
* @throws {@link CashAssemblyPrimitiveVariableMissingError} When the runtime value is missing from the variables map.
* @throws {@link CashAssemblyUnsupportedValueTypeError} When the method return type cannot be embedded.
* @throws {@link CashAssemblyNumberNotSafeIntegerError} When a method return value is a number that is not a safe integer.
*/
export const resolvePrimitiveMethodBytes = (parameters: ResolvePrimitiveMethodBytesParameters): Record<string, Uint8Array> => {
const { identifiers, templateVariables, variables } = parameters;
// Without template metadata there is no hint to select a primitive class.
if (templateVariables === undefined) {
return {};
}
const resolvedBytes: Record<string, Uint8Array> = {};
for (const identifier of identifiers) {
// The same identifier can appear more than once. Resolve it only once.
if (Object.hasOwn(resolvedBytes, identifier) === true) {
continue;
}
// Find the primitive method reference in the identifier.
const methodReferenceMatch = identifier.match(CASHASSEMBLY_VARIABLE_METHOD_REFERENCE_PATTERN);
if (methodReferenceMatch === null) {
continue;
}
const [ , baseName, methodName ] = methodReferenceMatch;
// Unknown identifiers and CashAssembly native operations such as someKey.schnorr_signature.all_outputs
// must be left for CashAssembly rather than treated as primitive failures.
if (Object.hasOwn(templateVariables, baseName) === false) {
continue;
}
const hint = templateVariables[baseName].hint;
if (isSupportedPrimitiveHint(hint) === false) {
continue;
}
// Supported hint with an unknown method should be thrown as an error.
if (canResolvePrimitiveMethod(hint, methodName) === false) {
throw new CashAssemblyPrimitiveMethodMissingError(identifier, methodName, hint);
}
// If the method is known but the runtime value is missing, throw an error.
if (Object.hasOwn(variables, baseName) === false) {
throw new CashAssemblyPrimitiveVariableMissingError(identifier, baseName);
}
const methodResult = callPrimitiveMethod({
identifier,
methodName,
value: variables[baseName],
hint,
});
// Store the result under identifier.
resolvedBytes[identifier] = convertValueToBytes(methodResult, identifier);
}
return resolvedBytes;
};