@xo-cash/engine 0.0.1 → 0.1.0-next.17298219321

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["parseTemplate","generateTemplateIdentifier"],"sources":["../source/errors.ts","../source/defaults.ts","../source/utils/libauth-utils.ts","../source/utils/cashassembly.ts","../source/utils/store-utils.ts","../source/monitor/blockchain.ts","../source/invitation/commit.ts","../source/invitation/builder.ts","../source/utils/template.ts","../source/invitation/merger.ts","../source/invitation/queries.ts","../source/invitation/validation.ts","../source/engine.ts"],"sourcesContent":["/* eslint-disable max-classes-per-file */\n\n// Template-related errors\n\n/**\n * Error thrown when an action is not found in the template.\n */\nexport class TemplateActionNotFoundError extends Error {\n constructor(actionIdentifier: string) {\n super(`Template action not found, actionIdentifier \"${actionIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when an output is not found in the template.\n */\nexport class TemplateOutputNotFoundError extends Error {\n constructor(outputIdentifier: string) {\n super(`Template output not found, outputIdentifier \"${outputIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when a template is not found.\n */\nexport class TemplateNotFoundError extends Error {\n constructor(templateIdentifier: string) {\n super(`Template not found, templateIdentifier \"${templateIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when a locking script is not found in the template.\n */\nexport class TemplateLockingScriptNotFoundError extends Error {\n constructor(lockingScriptIdentifier: string) {\n super(`Template locking script not found, lockingScriptIdentifier \"${lockingScriptIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when a locking script type is not found in the template.\n */\nexport class TemplateLockingScriptTypeNotFoundError extends Error {\n constructor(lockingScriptIdentifier: string) {\n super(`Template locking script type not found, lockingScriptIdentifier \"${lockingScriptIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when an unlocking script is not found in the template.\n */\nexport class UnlockingScriptNotFoundError extends Error {\n constructor(unlockingScriptIdentifier?: string) {\n const defaultMessage = 'Unlocking script not found in template';\n super(unlockingScriptIdentifier ? `${defaultMessage}: unlockingScriptIdentifier \"${unlockingScriptIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a script is not found in the template.\n */\nexport class ScriptNotFoundError extends Error {\n constructor(scriptIdentifier?: string) {\n const defaultMessage = 'Script not found in template';\n super(scriptIdentifier ? `${defaultMessage}: scriptIdentifier \"${scriptIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a starting action is not found in the template.\n */\nexport class StartingActionNotFoundError extends Error {\n constructor(templateIdentifier?: string) {\n const defaultMessage = 'Starting action not found in template';\n super(templateIdentifier ? `${defaultMessage}: templateIdentifier \"${templateIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a transaction is not found in the template.\n */\nexport class TemplateTransactionNotFoundError extends Error {\n constructor(transactionIdentifier: string) {\n super(`Template transaction not found, transactionIdentifier \"${transactionIdentifier}\"`);\n }\n}\n\n// Invitation-related errors\n\n/**\n * Error thrown when a commit entity identifier is not found.\n */\nexport class CommitEntityIdentifierNotFoundError extends Error {\n constructor(commitIdentifier?: string) {\n const defaultMessage = 'Commit entity identifier not found';\n super(commitIdentifier ? `${defaultMessage}: commitIdentifier \"${commitIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a commit is not signed.\n */\nexport class CommitNotSignedError extends Error {\n constructor(commitIdentifier?: string) {\n const defaultMessage = 'Commit not signed';\n super(commitIdentifier ? `${defaultMessage}: commitIdentifier \"${commitIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a commit is not found in the invitation.\n */\nexport class CommitNotFoundInInvitationError extends Error {\n constructor(commitIdentifier?: string) {\n const defaultMessage = 'Commit not found in invitation';\n super(commitIdentifier ? `${defaultMessage}: commitIdentifier \"${commitIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when one or more entity identifiers are invalid.\n */\nexport class InvalidEntityIdentifierError extends Error {\n constructor(entityIdentifiers?: string[]) {\n const defaultMessage = 'One or more entity identifiers are invalid';\n if (entityIdentifiers && entityIdentifiers.length > 0) {\n super(`${defaultMessage}: entityIdentifiers [${entityIdentifiers.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when one or more provided requirements were not expected by the template.\n */\nexport class InvalidRequirementsError extends Error {\n constructor(requirementIdentifiers?: string[]) {\n const defaultMessage = 'One or more provided requirements were not expected by the template';\n if (requirementIdentifiers && requirementIdentifiers.length > 0) {\n super(`${defaultMessage}: requirementIdentifiers [${requirementIdentifiers.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when one or more commit signatures are invalid.\n */\nexport class InvalidCommitSignaturesError extends Error {\n constructor(commitIdentifiers?: string[]) {\n const defaultMessage = 'One or more commit signatures are invalid';\n if (commitIdentifiers && commitIdentifiers.length > 0) {\n super(`${defaultMessage}: commitIdentifiers [${commitIdentifiers.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when an invitation is not found in the store.\n */\nexport class InvitationNotFoundInStoreError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invitation not found in store';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an invitation has already been accepted.\n */\nexport class InvitationAlreadyAcceptedError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invitation already accepted';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an invitation was created in the future.\n */\nexport class InvitationCreatedInFutureError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invitation created in the future';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an invitation has expired.\n */\nexport class InvitationExpiredError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invitation expired';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an invitation has not been accepted.\n */\nexport class InvitationNotAcceptedError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invitation not accepted';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an invitation is invalid.\n */\nexport class InvalidInvitationError extends Error {\n constructor(invitationIdentifier?: string) {\n const defaultMessage = 'Invalid invitation';\n super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier \"${invitationIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a merged commit is not found.\n */\nexport class MergedCommitNotFoundError extends Error {\n constructor() {\n const defaultMessage = 'Merged commit not found';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when the script hash data record for a given script hash is not found in the store.\n */\nexport class ScriptHashDataNotFoundError extends Error {\n constructor(scriptHash?: string) {\n const defaultMessage = 'Script hash data not found in store';\n super(scriptHash ? `${defaultMessage}: scriptHash \"${scriptHash}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when the root commit for an entity cannot be found in the invitation.\n */\nexport class RootCommitNotFoundError extends Error {\n constructor(entityIdentifier?: string) {\n const defaultMessage = 'Root commit not found in invitation';\n super(entityIdentifier ? `${defaultMessage}: entityIdentifier \"${entityIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a parent commit is not found.\n */\nexport class ParentCommitNotFoundError extends Error {\n constructor(parentCommitIdentifier: string, commitIdentifier: string) {\n super(`Parent commit not found: ${parentCommitIdentifier} (referenced by commit ${commitIdentifier})`);\n }\n}\n\n/**\n * Error thrown when duplicate transactionIndex values are found.\n */\nexport class DuplicateTransactionIndexError extends Error {\n constructor(itemType: 'input' | 'output', duplicateIndices: number[]) {\n const uniqueDuplicates = [ ...new Set(duplicateIndices) ];\n super(`Duplicate ${itemType} transactionIndex values found: ${uniqueDuplicates.join(', ')}`);\n }\n}\n\n/**\n * Error thrown when a circular merge reference is detected.\n */\nexport class CircularMergeReferenceError extends Error {\n constructor(itemType: 'input' | 'output', mergeKey: string, commitIdentifier: string) {\n super(`Circular merge reference detected for ${itemType}: ${mergeKey} (in commit ${commitIdentifier})`);\n }\n}\n\n/**\n * Error thrown when a mergesWith commit is not found.\n */\nexport class MergesWithCommitNotFoundError extends Error {\n constructor(mergesWithCommitIdentifier: string, currentCommitIdentifier: string) {\n super(`Merges with commit not found: ${mergesWithCommitIdentifier} (referenced by commit ${currentCommitIdentifier})`);\n }\n}\n\n/**\n * Error thrown when an item at a specific index is not found in a commit.\n */\nexport class ItemNotFoundInCommitError extends Error {\n constructor(itemType: 'input' | 'output', index: number, commitIdentifier: string) {\n const capitalizedType = itemType.charAt(0).toUpperCase() + itemType.slice(1);\n super(`${capitalizedType} at index ${index} not found in commit ${commitIdentifier}`);\n }\n}\n\n/**\n * Error thrown when locking bytecode is not found for an output.\n */\nexport class LockingBytecodeNotFoundForOutputError extends Error {\n constructor(outputIdentifier: string, transactionIndex?: number) {\n const indexInfo = ` (transactionIndex: ${transactionIndex ?? 'undefined'})`;\n super(`Locking bytecode not found for output: ${outputIdentifier}${indexInfo}`);\n }\n}\n\n/**\n * Error thrown when transaction version is defined multiple times in commits.\n */\nexport class DuplicateTransactionVersionError extends Error {\n constructor(commitIdentifiers: string[]) {\n super(`Transaction version is defined in multiple commits: ${commitIdentifiers.join(', ')}`);\n }\n}\n\n/**\n * Error thrown when transaction locktime is defined multiple times in commits.\n */\nexport class DuplicateTransactionLocktimeError extends Error {\n constructor(commitIdentifiers: string[]) {\n super(`Transaction locktime is defined in multiple commits: ${commitIdentifiers.join(', ')}`);\n }\n}\n\n/**\n * Error thrown when the provided template's identifier does not match the invitation's template identifier.\n */\nexport class InvitationTemplateMismatchError extends Error {\n constructor(expectedTemplateIdentifier: string, receivedTemplateIdentifier: string) {\n super(`Invitation template mismatch in validation, expected templateIdentifier \"${expectedTemplateIdentifier}\", got \"${receivedTemplateIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when an unspent output is not found.\n */\nexport class UnspentOutputNotFoundError extends Error {\n constructor(outpointIdentifier?: string) {\n const defaultMessage = 'Unspent output not found';\n super(outpointIdentifier ? `${defaultMessage}: outpointIdentifier \"${outpointIdentifier}\"` : defaultMessage);\n }\n}\n\n// Role-related errors\n\n/**\n * Error thrown when a role is invalid.\n */\nexport class InvalidRoleError extends Error {\n constructor(roleIdentifier?: string) {\n const defaultMessage = 'Invalid role';\n super(roleIdentifier ? `${defaultMessage}: roleIdentifier \"${roleIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when there are multiple roles for the starting action.\n */\nexport class MultipleRolesForStartingActionError extends Error {\n constructor(actionIdentifier?: string) {\n const defaultMessage = 'Multiple roles for starting action';\n super(actionIdentifier ? `${defaultMessage}: actionIdentifier \"${actionIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when no role is specified and multiple roles are available to be accepted.\n */\nexport class NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError extends Error {\n constructor() {\n const defaultMessage = 'No role specified and multiple roles available to be accepted';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when a role has already been accepted by another entity.\n */\nexport class RoleAlreadyAcceptedByAnotherEntityError extends Error {\n constructor(roleIdentifier?: string) {\n const defaultMessage = 'Role already accepted by another entity';\n super(roleIdentifier ? `${defaultMessage}: roleIdentifier \"${roleIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a role cannot start an action.\n */\nexport class RoleCannotStartActionError extends Error {\n constructor(roleIdentifier?: string, actionIdentifier?: string) {\n const defaultMessage = 'Role cannot start action';\n if (roleIdentifier && actionIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\", actionIdentifier \"${actionIdentifier}\"`);\n } else if (roleIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\"`);\n } else if (actionIdentifier) {\n super(`${defaultMessage}: actionIdentifier \"${actionIdentifier}\"`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when a role is not available to be accepted.\n */\nexport class RoleNotAvailableToBeAcceptedError extends Error {\n constructor(roleIdentifier?: string) {\n const defaultMessage = 'Role not available to be accepted';\n super(roleIdentifier ? `${defaultMessage}: roleIdentifier \"${roleIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a role is not defined for an action.\n */\nexport class RoleNotDefinedForActionError extends Error {\n constructor(roleIdentifier?: string, actionIdentifier?: string) {\n const defaultMessage = 'Role not defined for action';\n if (roleIdentifier && actionIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\", actionIdentifier \"${actionIdentifier}\"`);\n } else if (roleIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\"`);\n } else if (actionIdentifier) {\n super(`${defaultMessage}: actionIdentifier \"${actionIdentifier}\"`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when a role is not found.\n */\nexport class TemplateLockingScriptRoleNotFoundError extends Error {\n constructor(lockingScriptIdentifier: string, roleIdentifier: string) {\n super(`Template locking script role not found, lockingScriptIdentifier \"${lockingScriptIdentifier}\", roleIdentifier \"${roleIdentifier}\"`);\n }\n}\n\n// Variable and validation errors\n\n/**\n * Error thrown when a data type is invalid.\n */\nexport class InvalidDataTypeError extends Error {\n constructor() {\n const defaultMessage = 'Invalid data type';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when a variable type is invalid.\n */\nexport class InvalidVariableTypeError extends Error {\n constructor(variableKey: string, expectedType: string, actualType: string) {\n const defaultMessage = 'Invalid variable type';\n super(`${defaultMessage}: variableKey \"${variableKey}\", expected ${expectedType}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a required variable is missing.\n */\nexport class MissingRequiredVariableError extends Error {\n constructor(variableNames?: string[]) {\n const defaultMessage = 'Missing required variable';\n if (variableNames && variableNames.length > 0) {\n super(`${defaultMessage}: variableNames [${variableNames.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when an unknown variable is provided.\n */\nexport class UnknownVariableError extends Error {\n constructor(variableKey?: string) {\n const defaultMessage = 'Unknown variable provided';\n super(variableKey ? `${defaultMessage}: variableKey \"${variableKey}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a variable is required but not provided.\n */\nexport class VariableRequiredError extends Error {\n constructor(variableKey?: string) {\n const defaultMessage = 'Variable required';\n super(variableKey ? `${defaultMessage}: variableKey \"${variableKey}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a number variable value is not a valid integer for CashAssembly compilation.\n */\nexport class CashAssemblyVariableNotIntegerError extends Error {\n constructor(variableName: string, value: number) {\n super(`CashAssembly variable value is not a valid integer: variableName \"${variableName}\", got ${value}`);\n }\n}\n\n/**\n * Error thrown when variable validation fails.\n */\nexport class VariableValidationFailedError extends Error {\n constructor(variableNames?: string[]) {\n const defaultMessage = 'Variable validation failed';\n if (variableNames && variableNames.length > 0) {\n super(`${defaultMessage}: variableNames [${variableNames.join(', ')}]`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n// Transaction and compilation errors\n\n/**\n * Error thrown when an action is invalid for an invitation.\n */\nexport class InvalidActionError extends Error {\n constructor(actionIdentifier?: string) {\n const defaultMessage = 'Invalid action for invitation';\n super(actionIdentifier ? `${defaultMessage}: actionIdentifier \"${actionIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when cash assembly compilation fails.\n */\nexport class CashAssemblyCompilationFailedError extends Error {\n constructor(message?: string) {\n const defaultMessage = 'Cash assembly compilation failed';\n super(message ? `${defaultMessage}: ${message}` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when locking bytecode generation fails.\n */\nexport class LockingBytecodeGenerationFailedError extends Error {\n constructor() {\n const defaultMessage = 'Failed to generate locking bytecode';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when locking data is not found.\n */\nexport class LockingDataNotFoundError extends Error {\n constructor() {\n const defaultMessage = 'Locking data not found';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when transaction generation fails.\n */\nexport class TransactionGenerationFailedError extends Error {\n constructor() {\n const defaultMessage = 'Failed to generate transaction';\n super(defaultMessage);\n }\n}\n\n// General validation errors\n\n/**\n * Error thrown when the created by identifier is already set.\n */\nexport class CreatedByIdentifierAlreadySetError extends Error {\n constructor() {\n const defaultMessage = 'Created by identifier already set';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when the created by identifier signature is already set.\n */\nexport class CreatedByIdentifierSignatureAlreadySetError extends Error {\n constructor() {\n const defaultMessage = 'Created by identifier signature already set';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when data is not found in the template.\n */\nexport class DataNotFoundError extends Error {\n constructor() {\n const defaultMessage = 'Data not found in template';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when input is invalid.\n */\nexport class InvalidInputError extends Error {\n constructor() {\n const defaultMessage = 'Invalid input';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when required data is missing.\n */\nexport class MissingRequiredDataError extends Error {\n constructor() {\n const defaultMessage = 'Missing required data';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when a required field is missing.\n */\nexport class MissingRequiredFieldError extends Error {\n constructor(fieldName?: string) {\n const defaultMessage = 'Missing required field';\n super(fieldName ? `${defaultMessage}: fieldName \"${fieldName}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a required role for an entity is missing.\n */\nexport class MissingRequiredRoleForEntityError extends Error {\n constructor(roleIdentifier?: string, entityIdentifier?: string) {\n const defaultMessage = 'Missing required role for entity';\n if (roleIdentifier && entityIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\", entityIdentifier \"${entityIdentifier}\"`);\n } else if (roleIdentifier) {\n super(`${defaultMessage}: roleIdentifier \"${roleIdentifier}\"`);\n } else if (entityIdentifier) {\n super(`${defaultMessage}: entityIdentifier \"${entityIdentifier}\"`);\n } else {\n super(defaultMessage);\n }\n }\n}\n\n/**\n * Error thrown when a required signature by an entity is missing.\n */\nexport class MissingRequiredSignatureByEntityError extends Error {\n constructor(entityIdentifier?: string) {\n const defaultMessage = 'Missing required signature by entity';\n super(entityIdentifier ? `${defaultMessage}: entityIdentifier \"${entityIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when resource reservation fails.\n */\nexport class ReserveResourcesFailedError extends Error {\n constructor() {\n const defaultMessage = 'Failed to reserve resources';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when signature verification fails.\n */\nexport class SignatureVerificationFailedError extends Error {\n constructor() {\n const defaultMessage = 'Signature verification failed';\n super(defaultMessage);\n }\n}\n\n/**\n * Error thrown when a variable definition is invalid.\n */\nexport class InvalidVariableDefinitionError extends Error {\n constructor(variableIdentifier: string) {\n const defaultMessage = 'Invalid variable definition: must be an object';\n super(`${defaultMessage}: variableIdentifier \"${variableIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when an output does not have a locking script.\n */\nexport class TemplateLockingScriptInOutputNotFoundError extends Error {\n constructor(outputIdentifier: string) {\n const defaultMessage = 'Template locking script in output not found';\n super(`${defaultMessage}, outputIdentifier \"${outputIdentifier}\"`);\n }\n}\n\n/**\n * Error thrown when a locking script has an invalid type.\n */\nexport class InvalidLockingScriptTypeError extends Error {\n constructor(outputIdentifier: string, expectedType: string, actualType: string) {\n const defaultMessage = 'Locking script has invalid locking type';\n super(`${defaultMessage}: outputIdentifier \"${outputIdentifier}\", expected ${expectedType}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a locking type is invalid.\n */\nexport class InvalidLockingTypeError extends Error {\n constructor(outputIdentifier: string, validTypes: string[], actualType: string | undefined) {\n const defaultMessage = 'Invalid locking type';\n super(`${defaultMessage}: outputIdentifier \"${outputIdentifier}\", expected one of ${validTypes.join(', ')}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a derivative index has an invalid type.\n */\nexport class InvalidDerivativeIndexTypeError extends Error {\n constructor(expectedType: string, actualType: string) {\n const defaultMessage = 'Invalid derivativeIndex type';\n super(`${defaultMessage}: expected ${expectedType}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when a template output valueSatoshis has an invalid type for CashAssembly expression.\n */\nexport class InvalidTemplateOutputSatoshisTypeError extends Error {\n constructor(actualType: string) {\n const defaultMessage = 'Template output valueSatoshis must be a string for CashAssembly expression';\n super(`${defaultMessage}, got ${actualType}`);\n }\n}\n\n/**\n * Error thrown when an electrum client is not found.\n */\nexport class ElectrumClientNotFoundError extends Error {\n constructor() {\n const defaultMessage = 'No electrum client found';\n super(defaultMessage);\n }\n}\n","import { StorageType } from '@xo-cash/state';\n\n/**\n * When an entity opts to participate in an invitation, it reserves resources (e.g., UTXOs)\n * that would otherwise be available to other invitations. To prevent resources from remaining\n * locked indefinitely, each reservation requires an expiration time, after which the resources\n * can be released.\n *\n * By default, the expiration time is set to 1 hour.\n */\nexport const DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS = 60 * 60 * 1000;\n\n/**\n * The default storage backend is IndexedDB.\n */\nexport const DEFAULT_STORAGE_TYPE = StorageType.INDEXEDDB;\n\n/**\n * The default sequence number is 0, which disables relative locktime on the input.\n */\nexport const DEFAULT_SEQUENCE_NUMBER = 0;\n\n/**\n * The default locktime is 0, which means the transaction is valid in any block and has no absolute locktime constraint.\n */\nexport const DEFAULT_LOCKTIME = 0;\n\n/**\n * The default transaction version is 2.\n */\nexport const DEFAULT_VERSION = 2;\n\n/**\n * An empty unlocking bytecode used as a placeholder for inputs (unlockingBytecode) within an invitation.\n * This placeholder is used when the entities responsible for signing those inputs\n * have not yet provided their signatures for the resulting transaction.\n *\n * Using a placeholder unlocking bytecode enables the engine to construct transaction structures for the\n * libauth compiler when working on template actions, even before all participant signatures are available.\n * This is especially helpful when invitation commits are merged, as it allows the transaction to be built and it's\n * parts can be validated before all unlocking scripts have been provided.\n */\nexport const PLACEHOLDER_UNLOCKING_BYTECODE = new Uint8Array(0);\n\n/**\n * The default electrum application identifier.\n */\nexport const DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER = 'xo';\n\n/**\n * Detects whether a string is a pure CashAssembly expression.\n *\n * CashAssembly expressions look like `$(<variable>)` or `$(<a> <b>)`. This pattern checks\n * that the entire string is one such expression and nothing else. It will not match if\n * there is other text surrounding the expression.\n *\n * For example:\n * `$(<fee>)` matches (a full expression)\n * `OP_DUP $(<fee>)` does not match (extra text before it)\n * `$()` does not match (empty expression)\n */\nexport const CASHASSEMBLY_EXPRESSION_PATTERN = /^\\$\\([^)]+\\)$/;\n\n/**\n * Finds all CashAssembly evaluations embedded in a larger string.\n *\n * An evaluation looks like `$(...)`, for example `$(<fee>)` or `$(<a> <b>)`. This pattern\n * locates every occurrence in the input and returns them all (global flag `g`).\n * Empty evaluations `$()` are intentionally excluded because they reference no variables.\n *\n * For example, scanning `\"OP_DUP <$(<pubkeyHash>)> OP_HASH160 $(<fee>)\"` would return\n * `['$(<pubkeyHash>)', '$(<fee>)']`.\n */\nexport const CASHASSEMBLY_EVALUATION_PATTERN = /\\$\\([^)]+\\)/g;\n\n/**\n * Extracts variable names from angle-bracket references inside a CashAssembly evaluation.\n *\n * Inside an evaluation like `$(<pubkeyHash> <fee>)`, variables are referenced as `<name>`.\n * This pattern captures the name between the brackets. The global flag `g` allows iterating\n * over every variable reference in a single evaluation string.\n *\n * For example, running this against `$(<pubkeyHash> <fee>)` would return the variable names\n * `[\"pubkeyHash\", \"fee\"]`.\n */\nexport const CASHASSEMBLY_VARIABLE_PATTERN = /<([^>]+)>/g;\n\n/**\n * Identifies CashAssembly literal tokens that appear inside angle-bracket push statements.\n *\n * Inside an evaluation, not everything between `<` and `>` is a variable name. Literals are\n * also valid push contents: numeric literals (e.g. `<0>`, `<32>`), hex literals (`<0x02>`),\n * binary literals (`<0b1010>`), and string literals (`<\"minting\">`, `<'hello'>`). This pattern\n * matches any captured token that starts with a digit or a quote character.\n */\nexport const CASHASSEMBLY_LITERAL_TOKEN_PATTERN = /^[0-9\"']/;\n","import { createCompilerBch } from '@bitauth/libauth';\nimport {\n CashAssemblyCompilationFailedError,\n MissingRequiredVariableError,\n InvalidVariableTypeError,\n InvalidVariableDefinitionError,\n InvalidLockingScriptTypeError,\n InvalidLockingTypeError,\n UnlockingScriptNotFoundError,\n TemplateLockingScriptInOutputNotFoundError,\n} from '../errors.ts';\nimport { extractVariablesFromEvaluations } from './cashassembly.ts';\nimport type { Template } from './template.ts';\nimport type { CompilerBch, CompilerConfiguration, WalletTemplateVariable } from '@bitauth/libauth';\nimport type { UnspentOutputData } from '@xo-cash/state';\nimport type { XOTemplate, XOTemplateVariable, XOTemplateLockingType } from '@xo-cash/types';\n\n/**\n * Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.\n * Returns libauth result or error string.\n *\n * @param compiler - The libauth compiler.\n * @param evaluation - The specific evaluation string to compile.\n * @param variables - A record mapping variable names to their values.\n * @returns Bytecode result object on success, otherwise an error string.\n */\nexport const generateCashAssemblyBytecode = (compiler: CompilerBch, evaluation: string, variables: Record<string, unknown>): Uint8Array => {\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n // Validate that all required variables are provided\n const missingVariables = variableNames.filter((name: string) => !Object.hasOwn(variables, name));\n if (missingVariables.length > 0) {\n throw new MissingRequiredVariableError(missingVariables);\n }\n\n // Construct the bytecode object using the keys in variableNames, mapping to the values in variables\n const bytecode: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n const value = variables[variableName];\n if (!(value instanceof Uint8Array)) {\n throw new InvalidVariableTypeError(variableName, 'Uint8Array', typeof value);\n }\n\n bytecode[variableName] = value;\n }\n\n const compiledBytecode = compiler.generateBytecode({\n data: { bytecode },\n scriptId: evaluation,\n });\n\n if (!compiledBytecode.success) {\n const errorMessage = 'errors' in compiledBytecode ? JSON.stringify(compiledBytecode.errors) : JSON.stringify(compiledBytecode);\n throw new CashAssemblyCompilationFailedError(errorMessage);\n }\n\n return compiledBytecode.bytecode;\n};\n\n/**\n * Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.\n *\n * @param evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)'])\n * @returns A Libauth compiler instance for use with these evaluations.\n */\nexport const compileCashAssemblyEvaluations = (evaluations: string[]): CompilerBch => {\n // Create a scripts object where each key is the evaluation and the value is also the evaluation\n const scripts: Record<string, string> = {};\n for (const evaluation of evaluations) {\n scripts[evaluation] = evaluation;\n }\n\n // Get the variable names from the evaluations.\n const variableNames = extractVariablesFromEvaluations(evaluations);\n\n // Create a map of variable names to variable definitions.\n const variables = Object.fromEntries(variableNames.map((variableName: string) => [ variableName, { type: 'WalletData' as const }]));\n\n // Create the libauth compiler.\n const compiler = createCompilerBch({\n scripts,\n variables,\n });\n\n return compiler;\n};\n\n/**\n * Creates a map of variable identifiers to role identifiers for the libauth compiler configuration.\n *\n * @param template - The template used to gather the variable identifiers.\n * @param role - The role identifier to assign to the variables.\n * @returns {Record<string, string>} A map of variable identifiers to role identifiers.\n */\nexport const entityOwnershipForLibauthCompiler = (template: XOTemplate, role: string): Record<string, string> => {\n // Create a map of variable identifiers to role identifiers.\n const entityOwnershipMap: Record<string, string> = {};\n\n // Get the variable identifiers from the template.\n const variableIdentifiers = template.variables ? Object.keys(template.variables) : [];\n\n for (const variableIdentifier of variableIdentifiers) {\n entityOwnershipMap[variableIdentifier] = role;\n }\n\n return entityOwnershipMap;\n};\n\n/**\n * Creates a map of script identifiers to script definitions for the libauth compiler configuration.\n *\n * @param template - The template used to gather the scripts.\n * @returns {CompilerConfiguration['scripts']} A map of script identifiers to script definitions.\n */\nexport const scriptsForLibauthCompiler = (template: XOTemplate): CompilerConfiguration['scripts'] => {\n // Create a map of script identifiers to script definitions.\n const scriptsMap: CompilerConfiguration['scripts'] = {};\n\n // Get the script entries from the template.\n const scriptEntries = template.scripts ? Object.entries(template.scripts) : [];\n\n for (const [ scriptId, scriptDefinition ] of scriptEntries) {\n scriptsMap[scriptId] = scriptDefinition;\n }\n\n return scriptsMap;\n};\n\n/**\n * Converts template variables into libauth variables with types.\n *\n * @param template - The template to assign types to the variables.\n * @returns CompilerConfiguration['variables']\n */\nexport const assignTypeToVariablesForLibauthCompiler = (template: XOTemplate): CompilerConfiguration['variables'] => {\n // Initialize the variables with types.\n const variablesWithTypes: CompilerConfiguration['variables'] = {};\n\n // Get the variable entries from the template.\n const variableEntries: [string, XOTemplateVariable][] = template.variables ? Object.entries(template.variables) : [];\n\n // Iterate over the variable entries and assign types to the variables.\n for (const [ variableIdentifier, variableDefinition ] of variableEntries) {\n // Validate variable definition structure\n if (!variableDefinition || typeof variableDefinition !== 'object') {\n throw new InvalidVariableDefinitionError(variableIdentifier);\n }\n\n // Determine the type based on the hint\n let variableType: 'Key' | 'AddressData' | 'WalletData';\n if ('hint' in variableDefinition) {\n if (variableDefinition.hint === 'private_key') {\n variableType = 'Key';\n } else if (variableDefinition.hint === 'script') {\n variableType = 'AddressData';\n } else {\n variableType = 'WalletData';\n }\n } else {\n variableType = 'WalletData';\n }\n\n // Create a typed variable definition with the type set.\n const typedVariableDefinition: WalletTemplateVariable = {\n ...variableDefinition,\n type: variableType,\n };\n variablesWithTypes[variableIdentifier] = typedVariableDefinition;\n }\n\n return variablesWithTypes;\n};\n\n/**\n * Maps supported XO template locking types to the corresponding libauth compiler locking script type.\n */\nconst XO_LOCKING_TYPE_TO_LIBAUTH_MAP: Record<XOTemplateLockingType, 'p2sh20' | 'p2sh32' | 'standard'> = {\n p2s: 'standard',\n p2pkh: 'standard',\n p2sh: 'p2sh32',\n};\n\n/**\n * Converts an XO template locking type to the corresponding libauth compiler locking script type.\n *\n * @param lockingType - The XO template locking type to convert.\n * @returns The corresponding libauth compiler locking script type string.\n */\nexport const convertXOLockingTypeToLibauth = (lockingType: XOTemplateLockingType): 'p2sh20' | 'p2sh32' | 'standard' => {\n return XO_LOCKING_TYPE_TO_LIBAUTH_MAP[lockingType];\n};\n\n/**\n * Creates the libauth compatible compiler data for a unspent output.\n *\n * @param template - The template used to generate the compiler data for.\n * @param unspentOutput - The unspent output to create the compiler data for.\n * @returns The compiler data for the unspent output.\n * @returns {Promise<{\n * compiler: CompilerBch;\n * script: string;\n * valueSatoshis: bigint;\n * }>} The compiler data for the unspent output.\n */\nexport const createLibauthCompilerDataFromUnspentOutput = async (\n template: Template,\n unspentOutput: UnspentOutputData,\n): Promise<{\n compiler: CompilerBch;\n script: string;\n valueSatoshis: bigint;\n}> => {\n // Get the output identifier from the unspent output.\n const { outputIdentifier } = unspentOutput;\n\n // Get the output from the template.\n const output = template.getOutputOrThrow(outputIdentifier);\n\n // Get the locking script for the output.\n const lockingScriptForOutput = template.getLockingScriptForOutputOrThrow(outputIdentifier);\n\n // Validate that locking script exists\n if (lockingScriptForOutput.lockingBytecode === undefined) {\n throw new TemplateLockingScriptInOutputNotFoundError(outputIdentifier);\n }\n\n const lockingScriptIdentifier = output.lockingScript;\n\n // TODO: fix it hardcoded 'owner' role\n let roleIdentifier = 'owner';\n try {\n template.getRoleOrThrow(lockingScriptIdentifier, roleIdentifier);\n } catch {\n // If 'owner' doesn't exist, get first role\n const [ firstRoleId ] = template.getFirstRoleOrThrow(lockingScriptIdentifier);\n roleIdentifier = firstRoleId;\n }\n\n // Gather up all the variables that are owned by the role in the template.\n // The entity ownership just maps those variables to the role.\n // TODO: For now all the variables are assigned to a selected role.\n const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), roleIdentifier);\n\n // Gather up all the scripts from the template.\n const scripts = scriptsForLibauthCompiler(template.getTemplate());\n\n // Gather up all the variables from the template and assign a type to them.\n // Key, HDKey, WalletData, AddressData, etc.\n const variables = assignTypeToVariablesForLibauthCompiler(template.getTemplate());\n\n // Create the unlocking scripts for libauth compiler configuration.\n if (!lockingScriptForOutput.unlockingBytecode) {\n throw new UnlockingScriptNotFoundError(outputIdentifier);\n }\n\n if (typeof lockingScriptForOutput.lockingBytecode !== 'string') {\n throw new InvalidLockingScriptTypeError(outputIdentifier, 'string', typeof lockingScriptForOutput.lockingBytecode);\n }\n\n const unlockingScripts: CompilerConfiguration['unlockingScripts'] = {\n [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode,\n };\n\n // Derive the accepted XO locking type identifiers directly from the conversion map keys to avoid duplication.\n const validXOLockingTypes = Object.keys(XO_LOCKING_TYPE_TO_LIBAUTH_MAP) as Array<XOTemplateLockingType>;\n const { lockingType } = lockingScriptForOutput;\n if (lockingType === undefined) {\n throw new InvalidLockingTypeError(outputIdentifier, validXOLockingTypes, lockingType);\n }\n\n // Type guard: check if lockingType is one of the valid XO locking types.\n if (lockingType !== 'p2s' && lockingType !== 'p2pkh' && lockingType !== 'p2sh') {\n throw new InvalidLockingTypeError(outputIdentifier, validXOLockingTypes, lockingType);\n }\n\n // Convert the XO locking type to the libauth compiler locking type and create the config entry.\n const lockingScriptTypes: CompilerConfiguration['lockingScriptTypes'] = { lock: convertXOLockingTypeToLibauth(lockingType) };\n\n // Create the libauth compiler configuration.\n const libauthCompilerConfig = {\n entityOwnership,\n scripts,\n variables,\n unlockingScripts,\n lockingScriptTypes,\n };\n\n // Create the libauth BCH compiler.\n const compiler = createCompilerBch(libauthCompilerConfig);\n\n // Get the unlocking script id from the locking script for the output.\n const unlockingScriptId = lockingScriptForOutput.unlockingBytecode;\n\n // Return the libauth compiler data\n return {\n compiler,\n script: unlockingScriptId,\n valueSatoshis: BigInt(unspentOutput.valueSatoshis),\n };\n};\n","/**\n * Utilities for parsing, extracting, and compiling CashAssembly expressions.\n *\n * CashAssembly is the scripting language used by Bitauth templates to describe Bitcoin Cash\n * locking and unlocking scripts.\n *\n * ## Syntax\n *\n * `<expression>` — a push statement. Compiles the contents and pushes the result onto the VM stack.\n * `<someKey.public_key>` pushes the 33-byte compressed public key. `<1>` pushes the integer 1.\n *\n * `$(<expression>)` — an evaluation. Runs the inner script in the VM and inserts the top stack\n * item as VM bytecode.\n * `$(<someKey.public_key> OP_HASH160)` inserts the HASH160 of the public key.\n *\n * `<$(<expression>)>` — a push of an evaluation result. Combines the two above: evaluates first,\n * then pushes. Example: P2PKH locking script:\n * `OP_DUP OP_HASH160 <$(<someKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG`.\n *\n * `variableId.operation` — a variable with a compiler-resolved operation. `someKey.public_key`\n * produces the public key bytes. `someKey.schnorr_signature.all_outputs` produces a Schnorr\n * signature.\n *\n * Opcodes (`OP_DUP`, `OP_HASH160`, etc.) are inserted as their bytecode equivalent directly.\n *\n * ## Name resolution priority\n *\n * When the compiler encounters an identifier it resolves it in this order:\n * 1. Opcode — always wins. Naming a variable or script `OP_ADD` will not shadow it.\n * 2. Variable — shadows scripts of the same name.\n * 3. Script — the script's bytecode.\n *\n * NOTE: In future development of the XO, there will be XO_CODE taking the highest priority.\n *\n * @see playground/examples/cashassembly-evaluations.js for runnable examples covering all syntax forms,\n * VM evaluation, and name resolution priority.\n */\nimport { bigIntToVmNumber, binToHex, binToUtf8, utf8ToBin, vmNumberToBigInt } from '@bitauth/libauth';\nimport type { XOInvitationVariableValue } from '@xo-cash/types';\nimport { CashAssemblyVariableNotIntegerError, VariableValidationFailedError } from '../errors.ts';\nimport {\n CASHASSEMBLY_EVALUATION_PATTERN,\n CASHASSEMBLY_EXPRESSION_PATTERN,\n CASHASSEMBLY_LITERAL_TOKEN_PATTERN,\n CASHASSEMBLY_VARIABLE_PATTERN,\n} from '../defaults.ts';\nimport { generateCashAssemblyBytecode, compileCashAssemblyEvaluations } from './libauth-utils.ts';\n\n/**\n * Supported decode modes for compiled CashAssembly evaluation bytes.\n */\nexport type CompiledCashAssemblyDecodeMode = 'utf8' | 'hex' | 'boolean' | 'bigint' | 'uint8array';\n\n/**\n * Parameters for compiling CashAssembly string.\n */\nexport type CompileCashAssemblyStringParameters = {\n cashAssemblyText: string;\n variables: Record<string, XOInvitationVariableValue | Uint8Array>;\n evaluationDecodeMode?: CompiledCashAssemblyDecodeMode;\n};\n\n/**\n * Checks if the expression is a CashAssembly expression.\n *\n * @param expression - The expression to check.\n * @returns True if the expression is a CashAssembly expression, false otherwise.\n */\nexport const isCashAssemblyExpression = (expression: unknown): boolean => {\n return typeof expression === 'string' && CASHASSEMBLY_EXPRESSION_PATTERN.test(expression);\n};\n\n/**\n * Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.\n *\n * @param text - The input string to scan for CashAssembly evaluations.\n * @returns An array of evaluation strings found in the input.\n *\n * @example\n * extractCashAssemblyEvaluations(\"OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)\");\n * // returns ['$(<foo>)', '$(<bar>)']\n */\nexport const extractCashAssemblyEvaluations = (text: string): string[] => {\n return text.match(CASHASSEMBLY_EVALUATION_PATTERN) ?? [];\n};\n\n/**\n * Extracts unique variable identifiers enclosed in angle brackets from each evaluation string.\n *\n * CashAssembly literal tokens such as hex bytes, numbers, and quoted strings are excluded.\n * For example, `<0x02>` and `<\"minting\">` are not returned.\n *\n * @param evaluations - An array of evaluation strings from which to extract variable names.\n * @returns An array of variable names\n */\nexport const extractVariablesFromEvaluations = (evaluations: string[]): string[] => {\n // Use a Set to ensure uniqueness.\n const uniqueVariables = new Set<string>();\n\n // Iterate over each evaluation and extract the variable names.\n for (const evaluation of evaluations) {\n // Iterate over each match and extract the variable name.\n for (const match of evaluation.matchAll(CASHASSEMBLY_VARIABLE_PATTERN)) {\n // Extract the variable name from the match.\n const extractedIdentifier = match[1];\n\n // Skip literal tokens.\n if (CASHASSEMBLY_LITERAL_TOKEN_PATTERN.test(extractedIdentifier)) {\n continue;\n }\n\n // Add the variable name to the set.\n uniqueVariables.add(extractedIdentifier);\n }\n }\n\n // Return the unique variable names.\n return [ ...uniqueVariables ];\n};\n\n/**\n * Converts a variable value to its byte representation.\n *\n * @param value - The variable value to convert.\n * @param variableName - The name of the variable, used in error messages.\n * @returns The byte representation of the value.\n * @throws {CashAssemblyVariableNotIntegerError} If a number value is not a valid integer.\n */\nconst convertVariableToBytes = (value: XOInvitationVariableValue | Uint8Array, variableName: string): Uint8Array => {\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (typeof value === 'bigint') {\n return bigIntToVmNumber(value);\n }\n\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw new CashAssemblyVariableNotIntegerError(variableName, value);\n }\n\n return bigIntToVmNumber(BigInt(value));\n }\n\n if (typeof value === 'boolean') {\n // The BCH VM treats an empty byte array as false and any non-empty byte array as true.\n return new Uint8Array(value ? [ 1 ] : []);\n }\n\n return utf8ToBin(value);\n};\n\n/**\n * Decodes compiled CashAssembly evaluation bytes into a string representation.\n *\n * 'evaluationDecodeMode' determines how the evaluation bytes are interpreted and presented.\n * Choose based on what the evaluation is expected to produce:\n * `bigint` for numeric values like satoshis, `utf8` for text labels, `hex` for binary data such\n * as hashes, and `boolean` to represent boolean values.\n *\n * @param compiledResult - The compiled evaluation bytecode.\n * @param evaluationDecodeMode - The decode mode used to convert bytes to text.\n * @returns The decoded value as a string suitable for inline replacement.\n */\nexport const decodeCompiledCashAssemblyEvaluation = (\n compiledResult: Uint8Array,\n evaluationDecodeMode: CompiledCashAssemblyDecodeMode = 'utf8',\n): string => {\n // Simply converts the byte array to a string.\n if (evaluationDecodeMode === 'uint8array') {\n return String(compiledResult);\n }\n\n // Converts the byte array to a boolean string, converting the evaluation result into a true or a false.\n // Suitable for UX where converting the evaluation to a readable true or false is desired.\n if (evaluationDecodeMode === 'boolean') {\n return compiledResult.length === 0 ? 'false' : 'true';\n }\n\n // Converts the byte array to a hex string.\n if (evaluationDecodeMode === 'hex') {\n return binToHex(compiledResult);\n }\n\n // Converts the byte array to a bigint string.\n if (evaluationDecodeMode === 'bigint') {\n const vmNumberResult = vmNumberToBigInt(compiledResult);\n if (typeof vmNumberResult === 'bigint') {\n return vmNumberResult.toString();\n }\n }\n\n // Converts the byte array to a utf8 string.\n return binToUtf8(compiledResult);\n};\n\n/**\n * Compiles all CashAssembly evaluations in a text string and replaces each evaluation\n * with a decoded string representation.\n *\n * @param cashAssemblyText - The string with CashAssembly evaluations.\n * @param variables - Object mapping variable names to values for compilation.\n * @param evaluationDecodeMode - The decode mode used after each evaluation is compiled.\n * @returns Compiled text with all evaluations replaced by decoded string values.\n * @throws VariableValidationFailedError when a required variable is not present in the variables map.\n */\nexport const compileCashAssemblyString = (parameters: CompileCashAssemblyStringParameters): string => {\n const { cashAssemblyText, variables, evaluationDecodeMode = 'utf8' } = parameters;\n\n let compiledText = cashAssemblyText;\n const evaluations = extractCashAssemblyEvaluations(cashAssemblyText);\n\n for (const evaluation of evaluations) {\n // Extract variable identifiers required by the current evaluation.\n const variableNames = extractVariablesFromEvaluations([ evaluation ]);\n\n // Validate that all required variables are provided.\n const missingVariables = variableNames.filter((variableName) => !Object.hasOwn(variables, variableName));\n if (missingVariables.length > 0) {\n throw new VariableValidationFailedError(missingVariables);\n }\n\n // Convert each variable to its bytes before compilation.\n const convertedVariables: Record<string, Uint8Array> = {};\n for (const variableName of variableNames) {\n convertedVariables[variableName] = convertVariableToBytes(variables[variableName], variableName);\n }\n\n // Compile the evaluation in isolation and replace it with the decoded string.\n const compiler = compileCashAssemblyEvaluations([ evaluation ]);\n\n // Generate the bytes for the evaluation.\n const compilationResult: Uint8Array = generateCashAssemblyBytecode(compiler, evaluation, convertedVariables);\n\n // Decode the bytes into a string as per the decode mode.\n const decodedResult = decodeCompiledCashAssemblyEvaluation(compilationResult, evaluationDecodeMode);\n\n // Replace the evaluation with the decoded string.\n compiledText = compiledText.replace(evaluation, decodedResult);\n }\n\n // Return the compiled text.\n return compiledText;\n};\n","import type { ScriptHashListUnspentResponse } from '@electrum-cash/protocol';\nimport type { State } from '@xo-cash/state';\nimport { UnspentOutputStatus } from '@xo-cash/state';\nimport { ScriptHashDataNotFoundError } from '../errors.ts';\n\n/**\n * Synchronizes the store of unspent outputs for a given script hash with the current state of the blockchain.\n *\n * This method performs the following:\n * 1. Retrieves the stored script hash data from the state.\n * 2. Fetches the current list of unspent outputs for the script hash from the state.\n * 3. Queries the blockchain for all unspent transaction outputs associated with the script hash.\n * 4. Adds any new unspent outputs found on the blockchain but missing from the state to the state.\n * 5. Removes any unspent outputs present in the state but no longer in the blockchain.\n *\n * @param state - The State instance to use for data operations.\n * @param scriptHash - The script hash for which to update the stored unspent outputs.\n * @param fetchUnspentOutputsCallback - Callback function to fetch unspent outputs from the blockchain.\n * @throws If the script hash is not found in the state.\n */\nexport const updateUnspentOutputsForScriptHashInStore = async (\n state: State,\n scriptHash: string,\n fetchUnspentOutputsCallback: (scriptHash: string) => Promise<ScriptHashListUnspentResponse>,\n): Promise<void> => {\n // Retrieve the locking bytecode data from store, throwing if not found.\n const scriptHashData = await state.getScriptHashData(scriptHash);\n\n if (scriptHashData === undefined) {\n throw new ScriptHashDataNotFoundError(scriptHash);\n }\n\n // Fetch all current unspent outputs from the store for this script hash.\n const unspentOutputsFromCache = await state.listUnspentOutputsData({ scriptHash });\n\n const unspentOutputsFromBlockchain = await fetchUnspentOutputsCallback(scriptHash);\n\n // Collect store outpoint keys for quick lookup.\n const cachedOutpointKeys = new Set<string>();\n for (const cachedOutput of unspentOutputsFromCache) {\n const key = `${cachedOutput.outpointTransactionHash}:${cachedOutput.outpointIndex}`;\n cachedOutpointKeys.add(key);\n }\n\n // Collect blockchain outpoint keys for quick lookup.\n const blockchainOutpointKeys = new Set<string>();\n for (const unspentOutput of unspentOutputsFromBlockchain) {\n const key = `${unspentOutput.tx_hash}:${unspentOutput.tx_pos}`;\n blockchainOutpointKeys.add(key);\n }\n\n // For each unspent output from the blockchain, add it to the store if not already present.\n for (const unspentOutput of unspentOutputsFromBlockchain) {\n const outpointKey = `${unspentOutput.tx_hash}:${unspentOutput.tx_pos}`;\n if (!cachedOutpointKeys.has(outpointKey)) {\n const unspentOutputData = {\n status: unspentOutput.height === 0 ? UnspentOutputStatus.PENDING : UnspentOutputStatus.CONFIRMED,\n reservedBy: undefined,\n scriptHash,\n selectable: true,\n privacy: false,\n templateIdentifier: scriptHashData.templateIdentifier,\n outputIdentifier: scriptHashData.outputIdentifier,\n outpointIndex: unspentOutput.tx_pos,\n outpointTransactionHash: unspentOutput.tx_hash,\n minedAtHeight: unspentOutput.height,\n valueSatoshis: unspentOutput.value,\n };\n\n await state.storeUnspentOutputData(unspentOutputData);\n }\n }\n\n // Remove any stored outputs that are no longer present in the blockchain.\n for (const cachedOutput of unspentOutputsFromCache) {\n const cachedKey = `${cachedOutput.outpointTransactionHash}:${cachedOutput.outpointIndex}`;\n if (!blockchainOutpointKeys.has(cachedKey)) {\n await state.deleteUnspentOutputData(cachedOutput.outpointTransactionHash, cachedOutput.outpointIndex);\n }\n }\n};\n","import { fetchScriptHashUnspentTransactionOutputs } from '@electrum-cash/protocol';\nimport { electrumClients, electrumEvents, stopElectrumNetwork } from '@electrum-cash/application';\nimport type {\n BlockReceived,\n BlockVerified,\n ChainStatus,\n OutputContested,\n OutputFinalized,\n OutputOrphaned,\n OutputReceived,\n OutputRejected,\n OutputSpent,\n OutputVerified,\n SystemFailure,\n TransactionContested,\n TransactionFinalized,\n TransactionOrphaned,\n TransactionReceived,\n TransactionRejected,\n TransactionVerified,\n AddressUpdate,\n ScriptHashUpdate,\n} from '@electrum-cash/application';\nimport type { State, UnspentOutputData } from '@xo-cash/state';\nimport { updateUnspentOutputsForScriptHashInStore } from '../utils/index.ts';\n\n/**\n * BlockchainMonitor class that provides blockchain monitoring operations.\n */\nexport class BlockchainMonitor {\n /**\n * The state instance for data persistence.\n */\n private state: State;\n\n /**\n * Flag indicating whether event listeners have been initialized.\n */\n private eventListenersInitialized: boolean = false;\n\n /**\n * Creates a new instance of BlockchainMonitor.\n *\n * @param {State} state - The State instance for data persistence.\n */\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Initializes event listeners for electrum application events.\n * Registers listeners for all available events from the electrum application,\n * including system, chain status, block, transaction, output, and address events.\n * This should be called after the electrum application is initialized.\n * Note: Event data is not stored, listeners are registered but remain empty.\n *\n * @returns {void}\n */\n initializeEventListeners(): void {\n if (this.eventListenersInitialized) {\n return;\n }\n\n electrumEvents.on('SystemFailure', (_error: SystemFailure) => {\n // TODO: Handle system failure properly at and should reflect this at root level to handle other resources.\n // TODO: Add logging for system failure.\n\n // Stop the blockchain monitor on system failure\n this.stop().catch(() => {});\n });\n\n electrumEvents.on('ChainStatus', (_status: ChainStatus) => {\n // TODO: Handle chain status\n });\n\n electrumEvents.on('BlockReceived', (_data: BlockReceived) => {\n // TODO: Handle block received\n });\n\n electrumEvents.on('BlockVerified', (_data: BlockVerified) => {\n // TODO: Handle block verified\n });\n\n // Transaction events\n electrumEvents.on('TransactionReceived', (_data: TransactionReceived) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('TransactionVerified', (_data: TransactionVerified) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('TransactionOrphaned', (_data: TransactionOrphaned) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('TransactionFinalized', (_data: TransactionFinalized) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('TransactionContested', (_data: TransactionContested) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('TransactionRejected', (_data: TransactionRejected) => {\n // Event listener registered but data is not stored\n });\n\n // Output events\n electrumEvents.on('OutputReceived', (_data: OutputReceived) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputContested', (_data: OutputContested) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputRejected', (_data: OutputRejected) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputVerified', (_data: OutputVerified) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputOrphaned', (_data: OutputOrphaned) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputFinalized', (_data: OutputFinalized) => {\n // Event listener registered but data is not stored\n });\n\n electrumEvents.on('OutputSpent', (_data: OutputSpent) => {\n // Event listener registered but data is not stored\n });\n\n // Address events\n electrumEvents.on('AddressUpdate', (_data: AddressUpdate) => {\n // Event listener registered but data is not stored\n });\n\n // Script hash events\n electrumEvents.on('ScriptHashUpdate', async (data: ScriptHashUpdate) => {\n await this.onScriptHashUpdate(data);\n });\n\n this.eventListenersInitialized = true;\n }\n\n /**\n * Stops the blockchain monitor and releases resources.\n * @returns {Promise<void>} Resolves when the blockchain monitor is stopped.\n */\n async stop(): Promise<void> {\n // Stop the electrum network\n await stopElectrumNetwork();\n\n // Reset the event listeners initialized flag\n this.eventListenersInitialized = false;\n }\n\n /**\n * Handles the creation of a new unspent output by storing it in the state.\n *\n * @param {UnspentOutputData} data - The unspent output data to store.\n * @returns {Promise<void>} Resolves when the unspent output data is stored.\n */\n async handleUnspentOutputCreated(data: UnspentOutputData): Promise<void> {\n await this.state.storeUnspentOutputData(data);\n }\n\n /**\n * Handles script hash update notifications from the electrum protocol.\n * When a script hash update is received, this method finds the scriptHash and updates the unspent outputs for it.\n *\n * @param {ScriptHashUpdate} data - The script hash update data.\n * @returns {Promise<void>} Resolves when the unspent outputs are updated.\n */\n async onScriptHashUpdate(data: ScriptHashUpdate): Promise<void> {\n const { scriptHash } = data;\n\n const scriptHashDataList = await this.state.listScriptHashData({ scriptHash });\n\n const [ firstElectrumClient ] = electrumClients.values();\n\n for (const scriptHashData of scriptHashDataList) {\n await updateUnspentOutputsForScriptHashInStore(this.state, scriptHashData.scriptHash, async () => {\n return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scriptHashData.scriptHash);\n });\n }\n }\n}\n","import { binToHex, generateRandomBytes } from '@bitauth/libauth';\nimport type { XOInvitation } from '@xo-cash/types';\n\n/**\n * Generates a random 16-byte commit identifier.\n *\n * @returns {string} The generated commit identifier as a hex string.\n */\nexport const generateCommitIdentifier = (): string => {\n return binToHex(generateRandomBytes(16));\n};\n\n/**\n * Finds the root commit identifier for a given entity in an invitation. The root commit is\n * the first commit the entity added to the invitation.\n *\n * @param {XOInvitation} invitation The invitation whose commits are searched.\n * @param {string} entityIdentifier The entity identifier to search for among the invitation commits.\n * @returns {string | undefined} The root commit identifier if the entity has a commit in the invitation, otherwise undefined.\n */\nexport const findRootCommitIdentifierInInvitation = (invitation: XOInvitation, entityIdentifier: string): string | undefined => {\n // Find the root commit identifier for the entity by iterating through the commits.\n for (const commit of invitation.commits) {\n if (commit.entityIdentifier === entityIdentifier) {\n return commit.commitIdentifier;\n }\n }\n\n // If the root commit identifier is not found, return undefined.\n return undefined;\n};\n","import { binToHex, generateRandomBytes } from '@bitauth/libauth';\nimport { DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS } from '../defaults.ts';\nimport type { XOInvitation, XOInvitationCommit, XOInvitationInput, XOInvitationOutput, XOInvitationVariable, XOTemplate } from '@xo-cash/types';\nimport {\n CommitEntityIdentifierNotFoundError,\n CommitNotSignedError,\n InvalidCommitSignaturesError,\n InvalidEntityIdentifierError,\n InvalidRequirementsError,\n InvitationExpiredError,\n ParentCommitNotFoundError,\n InvitationTemplateMismatchError,\n} from '../errors.ts';\nimport {\n generateTemplateIdentifier,\n hasInvitationExpired,\n Template,\n validateInvitationCommits,\n validateInvitationEntities,\n validateRoleRequirements,\n} from '../index.ts';\nimport type { InvitationCreationParameters } from '../interfaces.ts';\nimport { generateCommitIdentifier } from './commit.ts';\n\n/**\n * Builder for the XOInvitation\n */\nexport class InvitationBuilder {\n /**\n * The identifier of the current invitation.\n *\n * TODO: Add validations and type checks to the identifier e.g length.\n */\n public invitationIdentifier: string;\n\n /**\n * The identifier of the template for the invitation.\n *\n * TODO: Add validations and type checks to the identifier e.g it should be a 32 byte hex string, etc.\n */\n public templateIdentifier: string;\n\n /**\n * The identifier of the action for the invitation.\n */\n public actionIdentifier: string;\n\n /**\n * The timestamp when the invitation is created.\n *\n */\n private createdAtTimestamp: number;\n\n /**\n * The commits in the invitation.\n */\n private commits: XOInvitationCommit[];\n\n /**\n * Create a new InvitationBuilder.\n * @param invitation Context for invitation creation.\n */\n constructor(invitation: InvitationCreationParameters) {\n const { templateIdentifier, actionIdentifier } = invitation;\n\n // Assign the template identifier\n this.templateIdentifier = templateIdentifier;\n\n // Assign the action identifier\n this.actionIdentifier = actionIdentifier;\n\n // Initialize the commits array.\n this.commits = [];\n\n // TODO: Implement a better way to generate the invitation identifier.\n this.invitationIdentifier = binToHex(generateRandomBytes(16));\n\n // Assign the current timestamp when the invitation is created.\n this.createdAtTimestamp = Date.now();\n }\n\n /**\n * Create a builder from an existing invitation.\n * @param invitation An existing XOInvitation.\n */\n static fromInvitation(invitation: XOInvitation): InvitationBuilder {\n // Create a builder instance from an existing invitation\n const builder = new InvitationBuilder({\n templateIdentifier: invitation.templateIdentifier,\n actionIdentifier: invitation.actionIdentifier,\n });\n\n // Overwrite the invitation identifier.\n builder.invitationIdentifier = invitation.invitationIdentifier;\n\n // Overwrite the created at timestamp\n builder.createdAtTimestamp = invitation.createdAtTimestamp;\n\n // Overwrite the commits\n builder.commits = [ ...invitation.commits ];\n\n // Return the builder instance\n return builder;\n }\n\n /**\n * Build the XOInvitation object to be shared.\n * @returns The built XOInvitation.\n */\n build(): XOInvitation {\n return {\n invitationIdentifier: this.invitationIdentifier,\n templateIdentifier: this.templateIdentifier,\n actionIdentifier: this.actionIdentifier,\n createdAtTimestamp: this.createdAtTimestamp,\n commits: this.commits,\n };\n }\n\n /**\n * Fully validates a given XOInvitation.\n *\n * @param template - The template to validate against.\n * @throws {InvitationExpiredError} If the invitation has expired.\n * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.\n * @throws {InvalidRequirementsError} If the requirements are invalid.\n * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.\n */\n validate(template: XOTemplate): this {\n // Generate the template identifier from the template.\n const templateIdentifier = generateTemplateIdentifier(template);\n\n // If the template identifier does not match the invitation template identifier, throw an error.\n if (templateIdentifier !== this.templateIdentifier) {\n throw new InvitationTemplateMismatchError(this.templateIdentifier, templateIdentifier);\n }\n\n // Get the action from the template.\n const action = new Template(template).getActionOrThrow(this.actionIdentifier);\n\n // Build the invitation.\n const invitation = this.build();\n\n // Check if the invitation has expired.\n if (hasInvitationExpired(invitation)) {\n throw new InvitationExpiredError();\n }\n\n // Validate entity information (public keys)\n if (!validateInvitationEntities(invitation)) {\n throw new InvalidEntityIdentifierError();\n }\n\n // Validate that all provided requirements were expected\n if (!validateRoleRequirements(invitation, template, action)) {\n throw new InvalidRequirementsError();\n }\n\n // Validate commit signatures\n if (!validateInvitationCommits(invitation)) {\n throw new InvalidCommitSignaturesError();\n }\n\n // Return the builder instance\n return this;\n }\n\n /**\n * Add a commit to the invitation.\n * @param commit The commit to add.\n * @returns The builder instance.\n */\n addCommit(commit: XOInvitationCommit): this {\n if (!commit.signature) {\n throw new CommitNotSignedError(commit.commitIdentifier);\n }\n\n if (!commit.entityIdentifier) {\n throw new CommitEntityIdentifierNotFoundError(commit.commitIdentifier);\n }\n\n this.commits.push(commit);\n\n return this;\n }\n\n /**\n * Returns the commitIdentifier of the last commit in the invitation.\n * @returns The commitIdentifier as a string, or undefined if there are no commits.\n */\n getLastCommitIdentifier(): string | undefined {\n return this.commits[this.commits.length - 1]?.commitIdentifier;\n }\n\n /**\n * Returns the last InvitationCommit in the invitation.\n * @returns The last InvitationCommit object, or undefined if there are no commits.\n */\n getLastCommit(): XOInvitationCommit | undefined {\n return this.commits[this.commits.length - 1];\n }\n\n /**\n * Creates an unsigned commit without adding it to the invitation.\n * This allows for atomic commit creation with signature.\n *\n * @param params - Parameters for creating the commit\n * @param params.inputs - Optional array of inputs to add\n * @param params.outputs - Optional array of outputs to add\n * @param params.variables - Optional array of variables to add\n * @param params.transactionVersion - Optional transaction version\n * @param params.transactionLocktime - Optional transaction locktime\n * @param params.expiresAtTimestamp - Optional expiration timestamp (defaults to now + DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS)\n * @returns The unsigned commit (without signature)\n */\n createUnsignedCommit(params: {\n inputs?: XOInvitationInput[];\n outputs?: XOInvitationOutput[];\n variables?: XOInvitationVariable[];\n transactionVersion?: number;\n transactionLocktime?: number;\n expiresAtTimestamp?: number;\n }): Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'> {\n const { inputs, outputs, variables, transactionVersion, transactionLocktime, expiresAtTimestamp } = params;\n\n // Validate mergesWith references\n if (inputs) {\n this.validateMergesWithReferences(inputs);\n }\n\n if (outputs) {\n this.validateMergesWithReferences(outputs);\n }\n\n // Create commit using private helper method\n return this.createCommit({\n previousCommitIdentifier: this.getLastCommitIdentifier(),\n inputs,\n outputs,\n variables,\n transactionVersion,\n transactionLocktime,\n expiresAtTimestamp: expiresAtTimestamp ?? Date.now() + DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS,\n });\n }\n\n /**\n * Creates a new commit from the provided data.\n * This is a private helper method that initializes the commit building logic.\n */\n private createCommit(params: {\n previousCommitIdentifier: string | undefined;\n inputs?: XOInvitationInput[];\n outputs?: XOInvitationOutput[];\n variables?: XOInvitationVariable[];\n transactionVersion?: number;\n transactionLocktime?: number;\n expiresAtTimestamp: number;\n }): Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'> {\n // Check if variables are provided, if they are then assign them to the data.\n let variables: XOInvitationCommit['data']['variables'];\n if (params.variables !== undefined && params.variables.length > 0) {\n variables = params.variables;\n }\n\n // Check if inputs are provided, if they are then assign them to the data.\n let inputs: XOInvitationCommit['data']['inputs'];\n if (params.inputs !== undefined && params.inputs.length > 0) {\n inputs = params.inputs;\n }\n\n // Check if outputs are provided, if they are then assign them to the data.\n let outputs: XOInvitationCommit['data']['outputs'];\n if (params.outputs !== undefined && params.outputs.length > 0) {\n outputs = params.outputs;\n }\n\n const data: XOInvitationCommit['data'] = { variables, inputs, outputs };\n\n // Include transaction version and transaction locktime in data (must be in data for commitIdentifier computation)\n if (params.transactionVersion !== undefined) {\n data.transactionVersion = params.transactionVersion;\n }\n\n if (params.transactionLocktime !== undefined) {\n data.transactionLocktime = params.transactionLocktime;\n }\n\n // Generate a commit identifier.\n const commitIdentifier = generateCommitIdentifier();\n\n return {\n commitIdentifier,\n previousCommitIdentifier: params.previousCommitIdentifier,\n data,\n expiresAtTimestamp: params.expiresAtTimestamp,\n };\n }\n\n /**\n * Validates mergesWith references for inputs and outputs.\n * @private\n */\n private validateMergesWithReferences(items: Array<{ mergesWith?: { commitIdentifier: string } }>): void {\n for (const item of items) {\n if (item.mergesWith) {\n const parentCommit = this.commits.find((commit) => commit.commitIdentifier === item.mergesWith?.commitIdentifier);\n if (!parentCommit) {\n throw new ParentCommitNotFoundError(item.mergesWith.commitIdentifier, this.invitationIdentifier);\n }\n\n // TODO: Fetch the commit and the values provided here and ensure they are not overwriting OR providing conflicting information.\n }\n }\n }\n}\n","import type {\n XOTemplate,\n XOTemplateAction,\n XOTemplateTransaction,\n XOTemplateOutput,\n XOTemplateLockingScript,\n XOTemplateLockingScriptRole,\n XOTemplateActionIntent,\n} from '@xo-cash/types';\nimport {\n TemplateActionNotFoundError,\n TemplateTransactionNotFoundError,\n TemplateOutputNotFoundError,\n TemplateLockingScriptNotFoundError,\n TemplateLockingScriptInOutputNotFoundError,\n TemplateLockingScriptTypeNotFoundError,\n TemplateLockingScriptRoleNotFoundError,\n} from '../errors.ts';\n\n/**\n * Template class for accessing template data.\n */\nexport class Template {\n /**\n * The template object.\n */\n private readonly template: XOTemplate;\n\n /**\n * Creates a Template class from a template object.\n */\n constructor(template: XOTemplate) {\n this.template = template;\n }\n\n /**\n * Gets the underlying template object.\n */\n getTemplate(): XOTemplate {\n return this.template;\n }\n\n /**\n * Gets the starting actions for the template.\n * @returns {Array<XOTemplateActionIntent>} The list of starting actions.\n */\n getStartingActions(): Array<XOTemplateActionIntent> {\n return this.template.start ?? [];\n }\n\n /**\n * Retrieves an output definition by identifier.\n * @throws {TemplateOutputNotFoundError} If the output is not found.\n */\n getOutputOrThrow(outputIdentifier: string): XOTemplateOutput {\n const output = this.template.outputs[outputIdentifier];\n if (output === undefined) {\n throw new TemplateOutputNotFoundError(outputIdentifier);\n }\n\n if (!output.lockingScript) {\n throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);\n }\n\n return output;\n }\n\n /**\n * Retrieves the locking script identifier from an output.\n * @throws {TemplateOutputNotFoundError} If the output is not found.\n * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.\n */\n getLockingScriptIdentifierOrThrow(outputIdentifier: string): string {\n const output = this.getOutputOrThrow(outputIdentifier);\n if (output.lockingScript === undefined) {\n throw new TemplateLockingScriptInOutputNotFoundError(outputIdentifier);\n }\n\n return output.lockingScript;\n }\n\n /**\n * Retrieves a locking script definition by identifier.\n * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.\n */\n getLockingScriptOrThrow(lockingScriptIdentifier: string): XOTemplateLockingScript {\n const lockingScript = this.template.lockingScripts[lockingScriptIdentifier];\n if (lockingScript === undefined) {\n throw new TemplateLockingScriptNotFoundError(lockingScriptIdentifier);\n }\n\n if (lockingScript.lockingType === undefined) {\n throw new TemplateLockingScriptTypeNotFoundError(lockingScriptIdentifier);\n }\n\n return lockingScript;\n }\n\n /**\n * Retrieves the locking script for a given output.\n * @throws {TemplateOutputNotFoundError} If the output is not found.\n * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.\n * @throws {TemplateLockingScriptNotFoundError} If the locking script definition is not found.\n */\n getLockingScriptForOutputOrThrow(outputIdentifier: string): XOTemplateLockingScript {\n const lockingScriptIdentifier = this.getLockingScriptIdentifierOrThrow(outputIdentifier);\n\n return this.getLockingScriptOrThrow(lockingScriptIdentifier);\n }\n\n /**\n * Retrieves a role within a locking script.\n * @param lockingScriptIdentifier - The locking script identifier.\n * @param roleIdentifier - The role identifier.\n * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.\n * @throws {TemplateLockingScriptRoleNotFoundError} If the role is not found.\n */\n getRoleOrThrow(lockingScriptIdentifier: string, roleIdentifier: string): XOTemplateLockingScriptRole {\n const lockingScript = this.getLockingScriptOrThrow(lockingScriptIdentifier);\n const role = lockingScript.roles?.[roleIdentifier];\n if (role === undefined) {\n throw new TemplateLockingScriptRoleNotFoundError(lockingScriptIdentifier, roleIdentifier);\n }\n\n return role;\n }\n\n /**\n * Retrieves the first available role in a locking script, or throws if none exist.\n * @param lockingScriptIdentifier - The locking script identifier.\n * @returns A tuple of [roleIdentifier, role].\n * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.\n * @throws {TemplateLockingScriptRoleNotFoundError} If no roles exist.\n */\n getFirstRoleOrThrow(lockingScriptIdentifier: string): [string, XOTemplateLockingScriptRole] {\n const lockingScript = this.getLockingScriptOrThrow(lockingScriptIdentifier);\n const roles = lockingScript.roles ?? {};\n const roleKeys = Object.keys(roles);\n if (roleKeys.length === 0) {\n // TODO: This function is to be removed in future updates, refer to the issue https://gitlab.com/GeneralProtocols/xo/engine/-/work_items/39 for more details.\n throw new TemplateLockingScriptRoleNotFoundError(lockingScriptIdentifier, '');\n }\n\n return [ roleKeys[0], roles[roleKeys[0]] ];\n }\n\n /**\n * Retrieves secrets for a locking script.\n * If roleIdentifier is provided, returns secrets from the role's state.\n * Otherwise, returns secrets from the locking script itself.\n * @param lockingScriptIdentifier - The locking script identifier.\n * @param roleIdentifier - The role identifier (optional, if not provided uses locking script secrets).\n * @returns Array of secret identifiers.\n * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.\n * @throws {TemplateLockingScriptRoleNotFoundError} If roleIdentifier is provided but the role is not found.\n */\n getSecrets(lockingScriptIdentifier: string, roleIdentifier?: string): string[] {\n if (roleIdentifier !== undefined) {\n const role = this.getRoleOrThrow(lockingScriptIdentifier, roleIdentifier);\n\n return role.state?.secrets ?? [];\n }\n\n const lockingScript = this.getLockingScriptOrThrow(lockingScriptIdentifier);\n\n return lockingScript.state?.secrets ?? [];\n }\n\n /**\n * Retrieves an action definition by identifier.\n * @param actionIdentifier - The identifier of the action.\n * @throws {TemplateActionNotFoundError} If the action is not found.\n */\n getActionOrThrow(actionIdentifier: string): XOTemplateAction {\n const action = this.template.actions[actionIdentifier];\n if (action === undefined) {\n throw new TemplateActionNotFoundError(actionIdentifier);\n }\n\n return action;\n }\n\n /**\n * Retrieves a transaction definition by identifier.\n * @param transactionIdentifier - The identifier of the transaction.\n * @throws {TemplateTransactionNotFoundError} If the transaction is not found.\n */\n getTransactionOrThrow(transactionIdentifier: string): XOTemplateTransaction {\n const transaction = this.template.transactions?.[transactionIdentifier];\n if (transaction === undefined) {\n throw new TemplateTransactionNotFoundError(transactionIdentifier);\n }\n\n return transaction;\n }\n\n /**\n * Retrieves the transaction for a given action.\n * @param actionIdentifier - The identifier of the action.\n * @throws {TemplateActionNotFoundError} If the action is not found.\n * @throws {TemplateTransactionNotFoundError} If the action has no transaction defined or the transaction is not found.\n */\n getTransactionForActionOrThrow(actionIdentifier: string): XOTemplateTransaction {\n const action = this.getActionOrThrow(actionIdentifier);\n if (action.transaction === undefined) {\n throw new TemplateTransactionNotFoundError(actionIdentifier);\n }\n\n return this.getTransactionOrThrow(action.transaction);\n }\n}\n","/**\n * Note:\n * This file implements the merging of invitation commits using a chain model.\n *\n * Each commit has exactly one parent commit (or none for tip commits).\n *\n * The invitation always ensures that when a new commit is added and shared with the other parties\n * they can't change the information provided in the previous commits.\n *\n * Once the invitation is to be merged this is how it merges:\n *\n * - Gathers up all the variables, states, version, locktime, inputs and outputs from all the commits.\n * - It could be that there are duplicates of each identifier, to handle this the min/max from the template is\n * used to determine whether that should be allowed or not. (TODO: min/max logic not implemented yet)\n * - The mergesWith is used to merge the information with a previous commit. Any overwrite of that commit is strictly not allowed.\n * - The merger uses a visitor pattern to traverse the commits, each data point in the invitation is marked as visited and merged.\n * - After this process is done all the non marked data points are merged with the existing data.\n * - Finally for inputs and outputs are sorted based on the transactionIndex and full merged data is returned.\n */\n\nimport { hexToBin } from '@bitauth/libauth';\nimport { DEFAULT_VERSION, DEFAULT_LOCKTIME, DEFAULT_SEQUENCE_NUMBER, PLACEHOLDER_UNLOCKING_BYTECODE } from '../defaults.ts';\nimport type {\n XOInvitationCommit,\n XOInvitation,\n XOInvitationVariable,\n XOInvitationVariableValue,\n XOInvitationInput,\n XOInvitationOutput,\n XOTemplate,\n} from '@xo-cash/types';\nimport {\n CircularMergeReferenceError,\n DuplicateTransactionIndexError,\n DuplicateTransactionLocktimeError,\n DuplicateTransactionVersionError,\n ItemNotFoundInCommitError,\n LockingBytecodeNotFoundForOutputError,\n MergesWithCommitNotFoundError,\n ParentCommitNotFoundError,\n} from '../errors.ts';\nimport { compileCashAssemblyString, isCashAssemblyExpression } from '../utils/index.ts';\nimport { Template } from '../utils/template.ts';\n\n/**\n * The final resultant of merging invitation commits.\n */\nexport type MergedInvitation = {\n inputs: XOInvitationInput[];\n outputs: XOInvitationOutput[];\n variables: XOInvitationVariable[];\n transactionVersion: number;\n transactionLocktime: number;\n};\n\ntype InputWithCommitIdentifier = {\n input: XOInvitationInput;\n sourceCommitIdentifier: string;\n};\n\ntype OutputWithCommitIdentifier = {\n output: XOInvitationOutput;\n sourceCommitIdentifier: string;\n};\n\ntype MergeableItem<T> = T & {\n mergesWith?: {\n commitIdentifier: string;\n index: number;\n };\n transactionIndex?: number;\n};\n\ntype MergeContext<T> = {\n items: Array<{ item: MergeableItem<T>; sourceCommitIdentifier: string }>;\n commitsMap: Map<string, XOInvitationCommit>;\n getItemsFromCommit: (commit: XOInvitationCommit) => MergeableItem<T>[] | undefined;\n resolveItem: (item: MergeableItem<T>) => T;\n itemType: 'input' | 'output';\n};\n\n/**\n * Converts an array of XOInvitationVariable objects into an object,\n * where each key is the variable's identifier and the value is the variable's value.\n *\n * @param variables - Array of XOInvitationVariable objects to convert.\n * @returns An object mapping each variable identifier to its corresponding value.\n */\nexport const convertCommitVariablesIntoObject = (variables: XOInvitationVariable[]): Record<string, XOInvitationVariableValue> => {\n const variablesObject: Record<string, XOInvitationVariableValue> = {};\n for (const variable of variables) {\n variablesObject[variable.variableIdentifier] = variable.value;\n }\n\n return variablesObject;\n};\n\n/**\n * Validates that all commit references exist.\n */\nconst validateCommitReferences = (commits: XOInvitationCommit[], commitsMap: Map<string, XOInvitationCommit>): void => {\n for (const commit of commits) {\n if (commit.previousCommitIdentifier && !commitsMap.has(commit.previousCommitIdentifier)) {\n throw new ParentCommitNotFoundError(commit.previousCommitIdentifier, commit.commitIdentifier);\n }\n }\n};\n\n/**\n * Merges simple data types (variables, transactionVersion, transactionLocktime).\n */\nconst mergeSimpleData = (commits: XOInvitationCommit[]): {\n variables: XOInvitationVariable[];\n transactionVersion: number | undefined;\n transactionLocktime: number | undefined;\n} => {\n const variables: XOInvitationVariable[] = [];\n const versionCommitIdentifiers: string[] = [];\n const locktimeCommitIdentifiers: string[] = [];\n\n let transactionVersion: number | undefined;\n let transactionLocktime: number | undefined;\n\n for (const commit of commits) {\n if (commit.data.variables) {\n variables.push(...commit.data.variables);\n }\n\n if (commit.data.transactionVersion !== undefined) {\n versionCommitIdentifiers.push(commit.commitIdentifier);\n if (transactionVersion === undefined) {\n transactionVersion = commit.data.transactionVersion;\n }\n }\n\n if (commit.data.transactionLocktime !== undefined) {\n locktimeCommitIdentifiers.push(commit.commitIdentifier);\n if (transactionLocktime === undefined) {\n transactionLocktime = commit.data.transactionLocktime;\n }\n }\n }\n\n if (versionCommitIdentifiers.length > 1) {\n throw new DuplicateTransactionVersionError(versionCommitIdentifiers);\n }\n\n if (locktimeCommitIdentifiers.length > 1) {\n throw new DuplicateTransactionLocktimeError(locktimeCommitIdentifiers);\n }\n\n return { variables, transactionVersion, transactionLocktime };\n};\n\n/**\n * Validates that there are no duplicate transactionIndex values.\n */\nconst validateTransactionIndices = <T extends { transactionIndex?: number }>(items: T[], itemType: 'input' | 'output'): void => {\n const indices = items.map((item) => item.transactionIndex).filter((idx): idx is number => idx !== undefined);\n\n const duplicates = indices.filter((idx, i) => indices.indexOf(idx) !== i);\n if (duplicates.length > 0) {\n throw new DuplicateTransactionIndexError(itemType, duplicates);\n }\n};\n\n/**\n * Generic function to merge items (inputs or outputs) with mergesWith references.\n */\nconst mergeItemsWithMergesWith = <T extends { transactionIndex?: number }>(context: MergeContext<T>): T[] => {\n const { items, commitsMap, getItemsFromCommit, resolveItem, itemType } = context;\n\n // Set to keep track of visited commits (commits that have been merged with)\n const visitedCommits = new Set<string>();\n\n /**\n * Resolves mergesWith references for an item recursively with cycle detection.\n */\n const resolveItemMerges = (item: MergeableItem<T>, currentCommitIdentifier: string, visitedPath: Set<string> = new Set()): MergeableItem<T> => {\n const mergedItem: MergeableItem<T> = { ...item };\n\n if (item.mergesWith) {\n // Create a unique key for cycle detection\n const mergeKey = `${item.mergesWith.commitIdentifier}:${item.mergesWith.index}`;\n if (visitedPath.has(mergeKey)) {\n throw new CircularMergeReferenceError(itemType, mergeKey, currentCommitIdentifier);\n }\n\n visitedPath.add(mergeKey);\n\n const mergesWithCommit = commitsMap.get(item.mergesWith.commitIdentifier);\n\n if (!mergesWithCommit) {\n throw new MergesWithCommitNotFoundError(item.mergesWith.commitIdentifier, currentCommitIdentifier);\n }\n\n const parentItems = getItemsFromCommit(mergesWithCommit);\n if (parentItems) {\n const parentItem = parentItems[item.mergesWith.index];\n if (!parentItem) {\n throw new ItemNotFoundInCommitError(itemType, item.mergesWith.index, item.mergesWith.commitIdentifier);\n }\n\n visitedCommits.add(item.mergesWith.commitIdentifier);\n\n // Recursively resolve parent item\n const resolvedParent = resolveItemMerges(parentItem, item.mergesWith.commitIdentifier, visitedPath);\n\n // Merge parent properties into current item\n Object.assign(mergedItem, resolvedParent);\n }\n }\n\n // Remove mergesWith reference after resolution\n if (mergedItem.mergesWith) {\n delete mergedItem.mergesWith;\n }\n\n return mergedItem;\n };\n\n const resolvedItems: T[] = [];\n\n // Process items that merge with other commits\n for (const { item, sourceCommitIdentifier } of items) {\n if (item.mergesWith) {\n const mergedItem = resolveItemMerges(item, sourceCommitIdentifier);\n const resolvedItem = resolveItem(mergedItem);\n resolvedItems.push(resolvedItem);\n }\n }\n\n // Process standalone items (but skip ones from commits that were merged with)\n for (const { item, sourceCommitIdentifier } of items) {\n if (!item.mergesWith && !visitedCommits.has(sourceCommitIdentifier)) {\n const mergedItem = resolveItemMerges(item, sourceCommitIdentifier);\n const resolvedItem = resolveItem(mergedItem);\n resolvedItems.push(resolvedItem);\n }\n }\n\n // Validate transaction indices\n validateTransactionIndices(resolvedItems, itemType);\n\n // Sort by transactionIndex (undefined values go to the end)\n resolvedItems.sort((a, b) => {\n const indexA = a.transactionIndex ?? Number.MAX_SAFE_INTEGER;\n const indexB = b.transactionIndex ?? Number.MAX_SAFE_INTEGER;\n\n return indexA - indexB;\n });\n\n return resolvedItems;\n};\n\n/**\n * Applies input-specific properties and defaults.\n */\nconst applyInputProperties = (input: XOInvitationInput): XOInvitationInput => {\n const processedInput: XOInvitationInput = { ...input };\n\n // Apply current input's properties (overriding parent)\n if (input.outpointIndex !== undefined) {\n processedInput.outpointIndex = input.outpointIndex;\n }\n\n if (input.outpointTransactionHash !== undefined) {\n processedInput.outpointTransactionHash =\n typeof input.outpointTransactionHash === 'string' ? hexToBin(input.outpointTransactionHash) : input.outpointTransactionHash;\n }\n\n if (input.sequenceNumber !== undefined) {\n processedInput.sequenceNumber = input.sequenceNumber;\n }\n\n if (input.unlockingBytecode !== undefined && input.unlockingBytecode !== PLACEHOLDER_UNLOCKING_BYTECODE) {\n processedInput.unlockingBytecode = typeof input.unlockingBytecode === 'string' ? hexToBin(input.unlockingBytecode) : input.unlockingBytecode;\n }\n\n // Apply defaults\n if (processedInput.sequenceNumber === undefined) {\n processedInput.sequenceNumber = DEFAULT_SEQUENCE_NUMBER;\n }\n\n if (processedInput.unlockingBytecode === undefined) {\n processedInput.unlockingBytecode = PLACEHOLDER_UNLOCKING_BYTECODE;\n }\n\n return processedInput;\n};\n\n/**\n * Merges inputs from all commits, resolving mergesWith references.\n * Also sorts all the inputs by transactionIndex.\n */\nconst mergeInputs = (commits: XOInvitationCommit[], commitsMap: Map<string, XOInvitationCommit>): XOInvitationInput[] => {\n // Collect all inputs with their source commit\n const allInputs: InputWithCommitIdentifier[] = [];\n\n for (const commit of commits) {\n if (commit.data.inputs) {\n for (const input of commit.data.inputs) {\n allInputs.push({\n input,\n sourceCommitIdentifier: commit.commitIdentifier,\n });\n }\n }\n }\n\n return mergeItemsWithMergesWith<XOInvitationInput>({\n items: allInputs.map(({ input, sourceCommitIdentifier }) => ({\n item: input,\n sourceCommitIdentifier,\n })),\n commitsMap,\n getItemsFromCommit: (commit) => commit.data.inputs,\n resolveItem: (item) => applyInputProperties(item),\n itemType: 'input',\n });\n};\n\n/**\n * Resolves output from template if identifier is present.\n */\nconst resolveOutputFromTemplate = (output: XOInvitationOutput, variables: XOInvitationVariable[], templateInstance: Template): XOInvitationOutput => {\n const resolvedOutput: XOInvitationOutput = { ...output };\n\n if (!output.outputIdentifier) {\n // Apply current output's properties even if no identifier\n if (output.valueSatoshis !== undefined) {\n resolvedOutput.valueSatoshis = BigInt(output.valueSatoshis);\n }\n\n if (output.lockingBytecode !== undefined) {\n resolvedOutput.lockingBytecode = typeof output.lockingBytecode === 'string' ? hexToBin(output.lockingBytecode) : output.lockingBytecode;\n }\n\n return resolvedOutput;\n }\n\n const templateOutput = templateInstance.getOutputOrThrow(output.outputIdentifier);\n\n // Resolve valueSatoshis from template if not provided\n if (resolvedOutput.valueSatoshis === undefined) {\n if (templateOutput.valueSatoshis && isCashAssemblyExpression(templateOutput.valueSatoshis)) {\n // If the execution flow reaches here then it means that the valueSatoshis is a pure cashassembly evaluation string.\n\n // Convert the variables into an object.\n const variablesObject = convertCommitVariablesIntoObject(variables);\n\n const compiledResult = compileCashAssemblyString({\n // Type assertion is safe here as `isCashAssemblyExpression` performs a type check\n cashAssemblyText: templateOutput.valueSatoshis as string,\n variables: variablesObject,\n // The evaluation will result in a bigint value and then be replaced with the cashassembly string.\n evaluationDecodeMode: 'bigint',\n });\n\n resolvedOutput.valueSatoshis = BigInt(compiledResult);\n }\n }\n\n // Resolve lockingBytecode from template if not provided\n if (resolvedOutput.lockingBytecode === undefined) {\n if (templateOutput.lockingScript && isCashAssemblyExpression(templateOutput.lockingScript)) {\n // If the execution flow reaches here then it means that the lockingScript is a pure cashassembly evaluation string.\n\n // Convert the variables into an object.\n const variablesObject = convertCommitVariablesIntoObject(variables);\n\n const compiledResult = compileCashAssemblyString({\n cashAssemblyText: templateOutput.lockingScript,\n variables: variablesObject,\n // The value is evaluated into a hex string\n evaluationDecodeMode: 'hex',\n });\n\n // hexToBin is needed here to convert the compiled hex string into a bytes array.\n resolvedOutput.lockingBytecode = hexToBin(compiledResult);\n }\n }\n\n if (!resolvedOutput.lockingBytecode) {\n throw new LockingBytecodeNotFoundForOutputError(output.outputIdentifier ?? 'unknown', output.transactionIndex);\n }\n\n // Ensure lockingBytecode is binary\n if (typeof resolvedOutput.lockingBytecode === 'string') {\n resolvedOutput.lockingBytecode = hexToBin(resolvedOutput.lockingBytecode);\n }\n\n // Apply current output's properties (overriding parent/template)\n if (output.valueSatoshis !== undefined) {\n resolvedOutput.valueSatoshis = BigInt(output.valueSatoshis);\n }\n\n if (output.lockingBytecode !== undefined) {\n resolvedOutput.lockingBytecode = typeof output.lockingBytecode === 'string' ? hexToBin(output.lockingBytecode) : output.lockingBytecode;\n }\n\n // Remove identifier after resolution\n // It is only needed to look up template data and must not appear in the final output.\n delete resolvedOutput.outputIdentifier;\n\n return resolvedOutput;\n};\n\n/**\n * Applies output-specific properties and resolves from template.\n */\nconst applyOutputProperties = (output: XOInvitationOutput, variables: XOInvitationVariable[], templateInstance: Template): XOInvitationOutput => {\n return resolveOutputFromTemplate(output, variables, templateInstance);\n};\n\n/**\n * Merges outputs from all commits, resolving mergesWith references and template identifiers.\n * Final list is sorted by transactionIndex.\n */\nconst mergeOutputs = (\n commits: XOInvitationCommit[],\n commitsMap: Map<string, XOInvitationCommit>,\n template: XOTemplate,\n variables: XOInvitationVariable[],\n): XOInvitationOutput[] => {\n const templateInstance = new Template(template);\n\n // Collect all outputs with their source commit\n const allOutputs: OutputWithCommitIdentifier[] = [];\n\n for (const commit of commits) {\n if (commit.data.outputs) {\n for (const output of commit.data.outputs) {\n allOutputs.push({\n output,\n sourceCommitIdentifier: commit.commitIdentifier,\n });\n }\n }\n }\n\n return mergeItemsWithMergesWith<XOInvitationOutput>({\n items: allOutputs.map(({ output, sourceCommitIdentifier }) => ({\n item: output,\n sourceCommitIdentifier,\n })),\n commitsMap,\n getItemsFromCommit: (commit) => commit.data.outputs,\n resolveItem: (item) => applyOutputProperties(item, variables, templateInstance),\n itemType: 'output',\n });\n};\n\n/**\n * Merges invitation commits and transforms it into MergedInvitation structure.\n *\n * @param invitation - The invitation containing commits to merge.\n * @param template - The template used for resolving output identifiers.\n * @returns MergedInvitation structure, or null if no commits exist.\n * @throws {Error} If merge conflicts or missing references are detected.\n */\nexport const mergeInvitationCommits = (invitation: XOInvitation, template: XOTemplate): MergedInvitation | null => {\n const { commits } = invitation;\n\n // If there are not commits, then return null.\n if (!commits?.length) return null;\n\n // Creating a map of all the commits by their identifier\n const commitsMap = new Map<string, XOInvitationCommit>();\n for (const commit of commits) {\n commitsMap.set(commit.commitIdentifier, commit);\n }\n\n // Before merging, validate that all previousCommitIdentifier references exist\n validateCommitReferences(commits, commitsMap);\n\n // Merge variables, state, version, and locktime\n // TODO: Implement duplicate variable handling logic based on min/max from template.\n // Different variables with the same identifier should be handled according to template rules.\n const { variables, transactionVersion, transactionLocktime } = mergeSimpleData(commits);\n\n const inputs = mergeInputs(commits, commitsMap);\n const outputs = mergeOutputs(commits, commitsMap, template, variables);\n\n return {\n inputs,\n outputs,\n variables,\n transactionVersion: transactionVersion ?? DEFAULT_VERSION,\n transactionLocktime: transactionLocktime ?? DEFAULT_LOCKTIME,\n };\n};\n","import type {\n XOInvitation,\n XOTemplate,\n XOTemplateAction,\n XOInvitationRequirements,\n XOInvitationRoleRequirement,\n XOInvitationVariable,\n XOInvitationInput,\n XOInvitationOutput,\n} from '@xo-cash/types';\nimport { Template } from '../utils/template.ts';\n\n/**\n * Field names that represent requirement types in an invitation.\n * These are the top-level fields that can contain requirement identifiers.\n */\nconst INVITATION_REQUIREMENT_FIELD_NAMES = [ 'variables', 'inputs', 'outputs' ] as const;\n\n/**\n * Checks if a role requirement has any items of the specified types.\n * @param roleRequirement - The role requirement object to check for any populated requirement fields.\n * @returns `true` if the role has any requirements (variables, inputs, or outputs), `false` otherwise.\n */\nconst hasRoleRequirements = (roleRequirement: XOInvitationRoleRequirement): boolean => {\n return INVITATION_REQUIREMENT_FIELD_NAMES.some((requirementFieldName) => {\n const requirementIdentifiers = roleRequirement[requirementFieldName];\n\n return requirementIdentifiers && requirementIdentifiers.length > 0;\n });\n};\n\n/**\n * Filters role requirements to only include those with actual populated requirements.\n * Removes any roles that have no variables, inputs, or outputs defined.\n * @param roleRequirements - Record mapping role identifiers to their requirement objects.\n * @returns Filtered record containing only roles that have at least one requirement field populated.\n */\nconst filterRolesWithRequirements = (roleRequirements: Record<string, XOInvitationRoleRequirement>): Record<string, XOInvitationRoleRequirement> => {\n const filteredRoleRequirements: Record<string, XOInvitationRoleRequirement> = {};\n for (const [ roleIdentifier, roleRequirement ] of Object.entries(roleRequirements)) {\n if (hasRoleRequirements(roleRequirement)) {\n filteredRoleRequirements[roleIdentifier] = roleRequirement;\n }\n }\n\n return filteredRoleRequirements;\n};\n\n/**\n * Finds requirement identifiers that are required but not yet populated.\n * @param requiredIdentifiers - Array of requirement identifiers that are expected/required.\n * @param populatedIdentifiers - Array of requirement identifiers that have already been provided.\n * @returns Array of identifiers that are required but missing from the populated list.\n */\nconst findMissingRequirementIdentifiers = (requiredIdentifiers: string[] = [], populatedIdentifiers: string[] = []): string[] => {\n return requiredIdentifiers.filter((identifier) => !populatedIdentifiers.includes(identifier));\n};\n\n/**\n * Processes and identifies missing requirements by comparing template requirements with populated requirements.\n * Analyzes both top-level requirements and role-specific requirements to determine what is still needed.\n * @param requirementsFromTemplate - Requirements expected from the template definition.\n * @param populatedRequirements - Requirements that have already been populated in the invitation.\n * @returns Object containing:\n * - `missingRequirements`: Top-level missing requirements (variables, inputs, outputs).\n * - `missingRoleRequirements`: Record of role-specific missing requirements keyed by role identifier.\n */\nconst processMissingRequirements = (\n requirementsFromTemplate: XOInvitationRequirements,\n populatedRequirements: XOInvitationRequirements,\n): {\n missingRequirements: XOInvitationRequirements;\n missingRoleRequirements: Record<string, XOInvitationRoleRequirement>;\n} => {\n // Initialize the missing requirements and roles objects.\n const missingRequirements: XOInvitationRequirements = {};\n\n // Initialize the missing roles object.\n const missingRoleRequirements: Record<string, XOInvitationRoleRequirement> = {};\n\n // Process top-level requirements\n INVITATION_REQUIREMENT_FIELD_NAMES.forEach((requirementFieldName) => {\n // Get the missing identifiers for the requirement field.\n const missingIdentifiers = findMissingRequirementIdentifiers(\n requirementsFromTemplate[requirementFieldName],\n populatedRequirements[requirementFieldName],\n );\n\n // If there are missing identifiers, add them to the missing requirements object.\n if (missingIdentifiers.length > 0) {\n missingRequirements[requirementFieldName] = missingIdentifiers;\n }\n });\n\n // Process role-level requirements\n for (const [ roleIdentifier, roleRequirement ] of Object.entries(requirementsFromTemplate.roles ?? {})) {\n // Get the populated role requirement from the populated requirements.\n const populatedRoleRequirement = populatedRequirements.roles?.[roleIdentifier];\n\n // Process each requirement type.\n INVITATION_REQUIREMENT_FIELD_NAMES.forEach((requirementFieldName) => {\n // Get the missing identifiers for the requirement field.\n const missingIdentifiers = findMissingRequirementIdentifiers(\n roleRequirement[requirementFieldName],\n populatedRoleRequirement?.[requirementFieldName],\n );\n\n // If there are missing identifiers, add them to the missing roles object.\n if (missingIdentifiers.length > 0) {\n if (!missingRoleRequirements[roleIdentifier]) missingRoleRequirements[roleIdentifier] = {};\n\n // Add the missing identifiers to the missing roles object.\n missingRoleRequirements[roleIdentifier][requirementFieldName] = missingIdentifiers;\n }\n });\n }\n\n return { missingRequirements, missingRoleRequirements };\n};\n\n/**\n * Extracts and lists all requirements from the template and action for an invitation.\n * Analyzes the template action to determine what variables, inputs, outputs, and role-specific\n * requirements are needed to fulfill the action.\n *\n * @param template - The template.\n * @param action - The action that has requirements.\n * @returns {XOInvitationRequirements} An object containing all the requirements.\n */\nexport const listRequirementsFromTemplate = (template: XOTemplate, action: XOTemplateAction): XOInvitationRequirements => {\n // Initialize the general requirements object.\n const generalRequirements: XOInvitationRequirements = {};\n\n // Initialize the specific role requirements object.\n const roleRequirements: Record<string, XOInvitationRoleRequirement> = {};\n\n // This is expected to have requirements only specific to the roles.\n if (action.roles) {\n for (const [ roleIdentifier, roleDefinition ] of Object.entries(action.roles)) {\n // If the role definition has requirements, add them to the role requirements object.\n if (roleDefinition.requirements) {\n // Add the role identifier to the role requirements object.\n if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};\n\n // Add the variables to the role requirements object.\n if (roleDefinition.requirements.variables) {\n roleRequirements[roleIdentifier].variables = roleDefinition.requirements.variables;\n }\n }\n }\n }\n\n // Cover role specific requirements in the action.\n if (action.requirements?.participants) {\n for (const roleSlot of action.requirements.participants) {\n const roleIdentifier = roleSlot.role;\n\n // TODO: Add support for min max slots.\n\n // If the role requirements object does not have an entry for the role identifier, create one.\n if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};\n\n // Variables for a role in an action are declared on the action's roles definition.\n const roleVariables = action.roles?.[roleIdentifier]?.requirements?.variables;\n if (roleVariables) {\n roleRequirements[roleIdentifier].variables = roleVariables;\n }\n }\n }\n\n // Covering the transaction requirements for inputs, outputs and other expected information.\n if (action.transaction) {\n // Get the transaction definition from the template.\n const transactionDefinition = new Template(template).getTransactionOrThrow(action.transaction);\n\n // Process the transaction roles.\n if (transactionDefinition.roles) {\n // Process each transaction role.\n for (const [ roleIdentifier, transactionRoleRequirement ] of Object.entries(transactionDefinition.roles)) {\n // If the role requirements object does not have an entry for the role identifier, create one.\n if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};\n\n // Add the inputs to the role requirements object, extracting just the identifier string from each entry.\n if (transactionRoleRequirement.inputs) {\n const transactionInputRequirementIdentifiers = [];\n for (const transactionInputRequirement of transactionRoleRequirement.inputs) {\n transactionInputRequirementIdentifiers.push(transactionInputRequirement.input);\n }\n\n roleRequirements[roleIdentifier].inputs = transactionInputRequirementIdentifiers;\n }\n\n // Add the outputs to the role requirements object, extracting just the identifier string from each entry.\n if (transactionRoleRequirement.outputs) {\n const transactionOutputRequirementIdentifiers = [];\n for (const transactionOutputRequirement of transactionRoleRequirement.outputs) {\n transactionOutputRequirementIdentifiers.push(transactionOutputRequirement.output);\n }\n\n roleRequirements[roleIdentifier].outputs = transactionOutputRequirementIdentifiers;\n }\n }\n }\n\n // Add the inputs to the general requirements object, extracting just the identifier string from each entry.\n if (transactionDefinition.inputs && transactionDefinition.inputs.length > 0) {\n generalRequirements.inputs = transactionDefinition.inputs.map((transactionInput) => transactionInput.input);\n }\n\n // Add the outputs to the general requirements object, extracting just the identifier string from each entry.\n if (transactionDefinition.outputs && transactionDefinition.outputs.length > 0) {\n generalRequirements.outputs = transactionDefinition.outputs.map((transactionOutput) => transactionOutput.output);\n }\n }\n\n // Filter out roles that have no actual requirements\n const roleRequirementsWithItems = filterRolesWithRequirements(roleRequirements);\n\n // Initialize the final requirements object.\n const finalRequirements: XOInvitationRequirements = {};\n\n // Process each requirement type.\n for (const requirementFieldName of INVITATION_REQUIREMENT_FIELD_NAMES) {\n // Get the requirement identifiers from the general requirements object.\n const requirementIdentifiers = generalRequirements[requirementFieldName];\n\n // If the requirement identifiers are not empty, add them to the final requirements object.\n if (requirementIdentifiers !== undefined && requirementIdentifiers.length > 0) {\n finalRequirements[requirementFieldName] = requirementIdentifiers;\n }\n }\n\n // If there are any roles with actual requirements, add them to the final requirements object.\n if (Object.keys(roleRequirementsWithItems).length > 0) {\n finalRequirements.roles = roleRequirementsWithItems;\n }\n\n // Return the final requirements object.\n return finalRequirements;\n};\n\n/**\n * Counts the number of distinct entities that have filled a specific role in the invitation.\n * An entity is considered to have filled a role if any of its commits contain data\n * (variables, inputs, or outputs) associated with that role identifier.\n *\n * TODO: Determine how an Authorized Entity will get into the invitation process.\n *\n * @param invitation - The invitation to examine.\n * @param roleIdentifier - The role identifier to count filled slots for.\n * @returns The number of unique entities that have contributed data for the specified role.\n */\nconst countFilledSlotsForRole = (invitation: XOInvitation, roleIdentifier: string): number => {\n const entityIdentifiers = new Set<string>();\n\n for (const commit of invitation.commits ?? []) {\n const { variables, inputs, outputs } = commit.data;\n\n // Check if any item in this commit is associated with the target role.\n let hasRoleData = false;\n for (const list of [ variables ?? [], inputs ?? [], outputs ?? [] ]) {\n for (const item of list) {\n if (item.roleIdentifier === roleIdentifier) {\n hasRoleData = true;\n break;\n }\n }\n\n if (hasRoleData) {\n break;\n }\n }\n\n if (hasRoleData) {\n entityIdentifiers.add(commit.entityIdentifier);\n }\n }\n\n return entityIdentifiers.size;\n};\n\n/**\n * Adds variable identifiers from invitation variables to the appropriate requirement collections.\n * Variables are added to either top-level requirements or role-specific requirements based on\n * whether they have a role identifier. This can be customized independently as variable handling evolves.\n *\n * @param variables - Array of invitation variables to extract identifiers from.\n * @param generalRequirements - Requirements object to add top-level variable identifiers to.\n * @param roleRequirements - Record of role requirements to add role-specific variable identifiers to.\n * @returns Updated requirements objects.\n */\nconst addVariableIdentifiers = (\n variables: XOInvitationVariable[],\n generalRequirements: XOInvitationRequirements,\n roleRequirements: Record<string, XOInvitationRoleRequirement>,\n): {\n generalRequirements: XOInvitationRequirements;\n roleRequirements: Record<string, XOInvitationRoleRequirement>;\n} => {\n const updatedGeneralRequirements = { ...generalRequirements };\n const updatedRoleRequirements = { ...roleRequirements };\n\n for (const variable of variables) {\n if (!variable.variableIdentifier) continue;\n\n if (variable.roleIdentifier) {\n if (!updatedRoleRequirements[variable.roleIdentifier]) {\n updatedRoleRequirements[variable.roleIdentifier] = {};\n }\n\n const roleRequirement = updatedRoleRequirements[variable.roleIdentifier];\n if (!roleRequirement.variables) {\n roleRequirement.variables = [];\n }\n\n roleRequirement.variables.push(variable.variableIdentifier);\n } else {\n if (!updatedGeneralRequirements.variables) {\n updatedGeneralRequirements.variables = [];\n }\n\n updatedGeneralRequirements.variables.push(variable.variableIdentifier);\n }\n }\n\n return {\n generalRequirements: updatedGeneralRequirements,\n roleRequirements: updatedRoleRequirements,\n };\n};\n\n/**\n * Adds input identifiers from invitation inputs to the appropriate requirement collections.\n * Inputs are added to either top-level requirements or role-specific requirements based on\n * whether they have a role identifier.\n *\n * @param inputs - Array of invitation inputs to extract identifiers from.\n * @param generalRequirements - Requirements object to add top-level input identifiers to.\n * @param roleRequirements - Record of role requirements to add role-specific input identifiers to.\n * @returns Updated requirements objects.\n */\nconst addInputIdentifiers = (\n inputs: XOInvitationInput[],\n generalRequirements: XOInvitationRequirements,\n roleRequirements: Record<string, XOInvitationRoleRequirement>,\n): {\n generalRequirements: XOInvitationRequirements;\n roleRequirements: Record<string, XOInvitationRoleRequirement>;\n} => {\n const updatedGeneralRequirements = { ...generalRequirements };\n const updatedRoleRequirements = { ...roleRequirements };\n\n for (const input of inputs) {\n if (!input.inputIdentifier) continue;\n\n if (input.roleIdentifier) {\n if (!updatedRoleRequirements[input.roleIdentifier]) {\n updatedRoleRequirements[input.roleIdentifier] = {};\n }\n\n const roleRequirement = updatedRoleRequirements[input.roleIdentifier];\n if (!roleRequirement.inputs) {\n roleRequirement.inputs = [];\n }\n\n roleRequirement.inputs.push(input.inputIdentifier);\n } else {\n if (!updatedGeneralRequirements.inputs) {\n updatedGeneralRequirements.inputs = [];\n }\n\n updatedGeneralRequirements.inputs.push(input.inputIdentifier);\n }\n }\n\n return {\n generalRequirements: updatedGeneralRequirements,\n roleRequirements: updatedRoleRequirements,\n };\n};\n\n/**\n * Adds output identifiers from invitation outputs to the appropriate requirement collections.\n * Outputs are added to either top-level requirements or role-specific requirements based on\n * whether they have a role identifier. This can be customized independently as output handling evolves.\n *\n * @param outputs - Array of invitation outputs to extract identifiers from.\n * @param generalRequirements - Requirements object to add top-level output identifiers to.\n * @param roleRequirements - Record of role requirements to add role-specific output identifiers to.\n * @returns Updated requirements objects.\n */\nconst addOutputIdentifiers = (\n outputs: XOInvitationOutput[],\n generalRequirements: XOInvitationRequirements,\n roleRequirements: Record<string, XOInvitationRoleRequirement>,\n): {\n generalRequirements: XOInvitationRequirements;\n roleRequirements: Record<string, XOInvitationRoleRequirement>;\n} => {\n const updatedGeneralRequirements = { ...generalRequirements };\n const updatedRoleRequirements = { ...roleRequirements };\n\n for (const output of outputs) {\n if (!output.outputIdentifier) continue;\n\n if (output.roleIdentifier) {\n if (!updatedRoleRequirements[output.roleIdentifier]) {\n updatedRoleRequirements[output.roleIdentifier] = {};\n }\n\n const roleRequirement = updatedRoleRequirements[output.roleIdentifier];\n if (!roleRequirement.outputs) {\n roleRequirement.outputs = [];\n }\n\n roleRequirement.outputs.push(output.outputIdentifier);\n } else {\n if (!updatedGeneralRequirements.outputs) {\n updatedGeneralRequirements.outputs = [];\n }\n\n updatedGeneralRequirements.outputs.push(output.outputIdentifier);\n }\n }\n\n return {\n generalRequirements: updatedGeneralRequirements,\n roleRequirements: updatedRoleRequirements,\n };\n};\n\n/**\n * Lists all requirements that have been populated in the invitation by examining all commits.\n * Extracts variable, input, and output identifiers from all commits in the invitation and\n * organizes them into top-level and role-specific requirements.\n *\n * @param invitation - The invitation object to analyze for populated requirements.\n * @returns An object containing all populated requirements found in the invitation's commits,\n * including top-level requirements and role-specific requirements. Only includes roles\n * that have at least one requirement populated.\n */\nexport const listPopulatedRequirementsInInvitation = (invitation: XOInvitation): XOInvitationRequirements => {\n let generalRequirements: XOInvitationRequirements = {};\n let roleRequirements: Record<string, XOInvitationRoleRequirement> = {};\n\n for (const commit of invitation.commits ?? []) {\n const { variables, inputs, outputs } = commit.data;\n\n if (variables) {\n const result = addVariableIdentifiers(variables, generalRequirements, roleRequirements);\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n\n if (inputs) {\n const result = addInputIdentifiers(inputs, generalRequirements, roleRequirements);\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n\n if (outputs) {\n const result = addOutputIdentifiers(outputs, generalRequirements, roleRequirements);\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n }\n\n return {\n ...generalRequirements,\n ...(Object.keys(roleRequirements).length > 0 && { roles: roleRequirements }),\n };\n};\n\n/**\n * Lists all missing requirements for the invitation that have not yet been supplied.\n * Compares the requirements expected from the template with what has been populated in the invitation\n * to determine what is still needed.\n *\n * Logic: `missing_requirements = requirements_from_template - populated_requirements_in_invitation`\n *\n * @param invitation - The invitation object to check for missing requirements.\n * @param template - The template defining what requirements are expected.\n * @param action - The template action being analyzed to determine required requirements.\n * @returns An object containing all missing requirements, including top-level missing requirements\n * and role-specific missing requirements. Only includes roles that have at least one missing requirement.\n */\nexport const listMissingRequirements = (invitation: XOInvitation, template: XOTemplate, action: XOTemplateAction): XOInvitationRequirements => {\n const requiredRequirementsFromTemplate: XOInvitationRequirements = listRequirementsFromTemplate(template, action);\n const populatedRequirementsInInvitation: XOInvitationRequirements = listPopulatedRequirementsInInvitation(invitation);\n\n const { missingRequirements, missingRoleRequirements } = processMissingRequirements(\n requiredRequirementsFromTemplate,\n populatedRequirementsInInvitation,\n );\n\n // Filter out roles that have no actual missing requirements (empty objects)\n const roleRequirementsWithMissingItems = filterRolesWithRequirements(missingRoleRequirements);\n\n const finalMissingRequirements: XOInvitationRequirements = { ...missingRequirements };\n\n // Only include roles if there are any roles with missing requirements\n if (Object.keys(roleRequirementsWithMissingItems).length > 0) {\n finalMissingRequirements.roles = roleRequirementsWithMissingItems;\n }\n\n return finalMissingRequirements;\n};\n\n/**\n * Lists role identifiers for roles that still have capacity for additional participants.\n * A role is considered available if the number of distinct entities that have filled it\n * is less than the role's maximum slot count. If max is undefined, the role has unlimited capacity.\n *\n * @param invitation - The invitation object to check for available roles.\n * @param template - The template defining the invitation structure and requirements.\n * @param action - The template action being analyzed to determine which roles are expected.\n * @returns Array of role identifier strings representing roles that can still accept participants.\n * Returns an empty array if no roles are defined in the action.\n */\nexport const listAvailableRolesForInvitation = (invitation: XOInvitation, action: XOTemplateAction): string[] => {\n const actionRoleSpecs = action.requirements?.participants ?? [];\n if (actionRoleSpecs.length === 0) return [];\n\n const availableRoleIdentifiers: string[] = [];\n\n for (const roleSpec of actionRoleSpecs) {\n const roleIdentifier = roleSpec.role;\n const filledSlots = countFilledSlotsForRole(invitation, roleIdentifier);\n const maxSlots = roleSpec.slots?.max;\n\n // A role is available if it hasn't reached its maximum capacity (undefined max = unlimited).\n if (maxSlots === undefined || filledSlots < maxSlots) {\n availableRoleIdentifiers.push(roleIdentifier);\n }\n }\n\n return availableRoleIdentifiers;\n};\n","import type { XOInvitation, XOTemplate, XOTemplateAction } from '@xo-cash/types';\nimport { buildInvitationCommitSigningPayload, verifySchnorrSignature } from '@xo-cash/crypto';\nimport { PublicKey } from '@xo-cash/primitives';\nimport { listPopulatedRequirementsInInvitation, listRequirementsFromTemplate } from './queries.ts';\n\n/**\n * Validates that the invitation has not expired for any of the commits.\n *\n * @param invitation - The XOInvitation object containing creation and expiration timestamps.\n * @returns True if the invitation is expired, false if it is valid.\n */\nexport const hasInvitationExpired = (invitation: XOInvitation): boolean => {\n const { commits } = invitation;\n const now = Date.now();\n\n return commits.some((commit) => commit.expiresAtTimestamp < now);\n};\n\n/**\n * Validates that all entity identifiers in the invitation are valid public keys.\n * Extracts unique entity identifiers from all commits.\n *\n * @param invitation - The invitation to validate.\n * @returns True if all entities are valid, false otherwise.\n */\nexport const validateInvitationEntities = (invitation: XOInvitation): boolean => {\n const entityIdentifiers = new Set(invitation.commits.map((commit) => commit.entityIdentifier));\n\n for (const entityIdentifier of entityIdentifiers) {\n try {\n new PublicKey(entityIdentifier);\n } catch {\n return false;\n }\n }\n\n // TODO: Return identifiers\n return true;\n};\n\n/**\n * Validates that all provided requirements in the invitation were expected by the template.\n *\n * @param invitation - The invitation to validate.\n * @param template - The template to validate against.\n * @param action - The action to validate against.\n * @returns True if all requirements are expected, false otherwise.\n */\nexport const validateRoleRequirements = (invitation: XOInvitation, template: XOTemplate, action: XOTemplateAction): boolean => {\n const expectedRequirementsByTemplate = listRequirementsFromTemplate(template, action);\n const populatedRequirementsByInvitation = listPopulatedRequirementsInInvitation(invitation);\n\n // Check top-level requirements\n const requirementTypes = [ 'variables', 'inputs', 'outputs' ] as const;\n for (const type of requirementTypes) {\n const populated = populatedRequirementsByInvitation[type] ?? [];\n const expected = expectedRequirementsByTemplate[type] ?? [];\n\n // Check if any provided requirement was not expected\n for (const populatedIdentifier of populated) {\n const isExpected = expected.some((expectedIdentifier) => expectedIdentifier === populatedIdentifier);\n if (!isExpected) {\n return false;\n }\n }\n }\n\n // Check role-level requirements\n if (populatedRequirementsByInvitation.roles) {\n for (const [ roleIdentifier, populatedRole ] of Object.entries(populatedRequirementsByInvitation.roles)) {\n const expectedRole = expectedRequirementsByTemplate.roles?.[roleIdentifier];\n\n // If role has populated requirements but wasn't expected, it's invalid\n if (!expectedRole) {\n return false;\n }\n\n for (const type of requirementTypes) {\n const populated = populatedRole[type] ?? [];\n const expected = expectedRole[type] ?? [];\n\n // Check if any provided requirement was not expected\n for (const populatedIdentifier of populated) {\n const isExpected = expected.some((expectedIdentifier) => expectedIdentifier === populatedIdentifier);\n if (!isExpected) {\n return false;\n }\n }\n }\n }\n }\n\n return true;\n};\n\n/**\n * Validates commit signatures.\n * Signature signs: stringify(data) + templateIdentifier + actionIdentifier + invitationIdentifier + commitIdentifier + previousCommitIdentifier\n *\n * @param invitation - The invitation containing commits to validate.\n * @returns True if all commit signatures are valid, false otherwise.\n */\nexport const validateInvitationCommits = (invitation: XOInvitation): boolean => {\n const { templateIdentifier, actionIdentifier, invitationIdentifier, commits } = invitation;\n\n for (const commit of commits) {\n const entityPublicKey = commit.entityIdentifier;\n\n const commitSigningPayload = buildInvitationCommitSigningPayload({\n data: commit.data,\n templateIdentifier,\n actionIdentifier,\n invitationIdentifier,\n commitIdentifier: commit.commitIdentifier,\n previousCommitIdentifier: commit.previousCommitIdentifier,\n });\n\n // Verify the signature\n const isValid = verifySchnorrSignature(commit.signature, entityPublicKey, commitSigningPayload);\n\n if (!isValid) {\n return false;\n }\n }\n\n return true;\n};\n","import { binToHex, createCompilerBch, encodeTransaction, generateTransaction, hashTransaction, hexToBin, sha256, utf8ToBin } from '@bitauth/libauth';\nimport type { CompilerConfiguration } from '@bitauth/libauth';\nimport { Crypto, convertMnemonicToSeedBytes, type PrivateKeyRecordForLibauthCompiler } from '@xo-cash/crypto';\nimport type { TransactionHash } from '@electrum-cash/protocol';\nimport { State, createStorageAdapter } from '@xo-cash/state';\nimport type { ScriptHashData, StoredInvitation, UnspentOutputData } from '@xo-cash/state';\nimport type {\n XOInvitation,\n XOInvitationCommit,\n XOInvitationInput,\n XOInvitationRequirements,\n XOTemplate,\n XOTemplateActionIntent,\n XOTemplateLockingScript,\n} from '@xo-cash/types';\nimport { generateTemplateIdentifier, parseTemplate, scriptToScriptHash } from '@xo-cash/utils';\nimport type { ChainStatus } from '@electrum-cash/application';\nimport { electrumClients, getChainStatus, initializeElectrumApplication, broadcastTransaction } from '@electrum-cash/application';\nimport { fetchScriptHashUnspentTransactionOutputs, subscribeToScriptHashUpdates } from '@electrum-cash/protocol';\nimport { electrumServers } from '@electrum-cash/servers';\nimport { BlockchainMonitor } from './monitor/blockchain.ts';\nimport {\n CommitNotFoundInInvitationError,\n InvalidInputError,\n LockingBytecodeGenerationFailedError,\n LockingDataNotFoundError,\n TemplateLockingScriptTypeNotFoundError,\n MergedCommitNotFoundError,\n TemplateNotFoundError,\n TransactionGenerationFailedError,\n TemplateTransactionNotFoundError,\n UnspentOutputNotFoundError,\n InvalidDerivativeIndexTypeError,\n ElectrumClientNotFoundError,\n InvitationNotFoundInStoreError,\n RootCommitNotFoundError,\n ScriptHashDataNotFoundError,\n} from './errors.ts';\nimport { DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, DEFAULT_STORAGE_TYPE } from './defaults.ts';\nimport type {\n AcceptInvitationParameters,\n ExecuteActionParameters,\n AppendInvitationParameters,\n GetSpendableResourcesParameters,\n InvitationCreationParameters,\n XOEngineOptions,\n} from './interfaces.ts';\nimport {\n findRootCommitIdentifierInInvitation,\n InvitationBuilder,\n listAvailableRolesForInvitation,\n listMissingRequirements,\n listRequirementsFromTemplate,\n mergeInvitationCommits,\n} from './invitation/index.ts';\nimport { Template } from './utils/template.ts';\nimport {\n assignTypeToVariablesForLibauthCompiler,\n entityOwnershipForLibauthCompiler,\n createLibauthCompilerDataFromUnspentOutput,\n scriptsForLibauthCompiler,\n updateUnspentOutputsForScriptHashInStore,\n convertXOLockingTypeToLibauth,\n} from './utils/index.ts';\n\n/**\n * XO Engine class: Acts like an orchestrator for the XO system.\n */\nexport class Engine {\n /**\n * The crypto instance.\n */\n private crypto: Crypto;\n\n /**\n * The state instance.\n */\n private state: State;\n\n /**\n * The blockchain monitor instance.\n */\n private blockchainMonitor: BlockchainMonitor;\n\n // TODO: The default identifiers exist as the strategy on how to create the change and default\n // unlocking conditions are unclear. This is likely to change in the future.\n\n /**\n * The default template identifier.\n */\n private defaultTemplateIdentifier: string;\n\n /**\n * The default role identifier.\n */\n private defaultRoleIdentifier: string;\n\n /**\n * The default output identifier.\n */\n private defaultOutputIdentifier: string;\n\n /**\n * Constructs a new instance of XO Engine.\n * @private\n * @param {string} mnemonic - The BIP39 mnemonic to be used for this instance of the engine.\n * @param {State} state - State instance.\n * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.\n */\n private constructor(mnemonic: string, state: State, blockchainMonitor: BlockchainMonitor) {\n // Set the crypto instance, the crypto instance requires seed bytes to be passed in the constructor.\n // `convertMnemonicToSeedBytes` performs full BIP39 validation before deriving the seed that is later used to derive the purpose HD node.\n // - Enforces the minimum word count\n // - Validates that all words are in the BIP39 word list\n // - Validates the checksum for the mnemonic\n this.crypto = new Crypto(convertMnemonicToSeedBytes(mnemonic));\n\n // Set the state instance\n this.state = state;\n\n // Set the blockchain monitor instance\n this.blockchainMonitor = blockchainMonitor;\n }\n\n /**\n * Initializes and creates a new XO Engine instance.\n * Configures the state, initializes the sync server and monitor for app and blockchain events\n *\n * @param {string} mnemonic - BIP39 mnemonic to be used for this instance of the engine.\n * @param {XOEngineOptions} options - Database configuration options.\n * @returns {Promise<Engine>} An initialized Engine instance.\n */\n static async create(mnemonic: string, options: XOEngineOptions): Promise<Engine> {\n // Initialize the electrum application\n await initializeElectrumApplication(options.electrumApplicationIdentifier ?? DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, {\n electrumServers,\n ...options,\n });\n\n // Generate the account hash from the mnemonic.\n const accountHash = binToHex(sha256.hash(utf8ToBin(mnemonic)));\n\n // Create storage adapter\n const storageAdapter = await createStorageAdapter({\n storageType: options.storageType ?? DEFAULT_STORAGE_TYPE,\n databasePath: options.databasePath,\n databaseFilename: options.databaseFilename,\n accountHash,\n });\n\n // Initialize the state instance\n const stateInstance = new State(storageAdapter);\n\n // Initialize the blockchain monitor, event listeners for electrum application events\n const blockchainMonitor = new BlockchainMonitor(stateInstance);\n blockchainMonitor.initializeEventListeners();\n\n // Initialize the engine instance\n const engineInstance = new Engine(mnemonic, stateInstance, blockchainMonitor);\n\n // Initialize the state sync server.\n await engineInstance.initializeStateSync();\n\n // Return the engine instance\n return engineInstance;\n }\n\n /**\n * Stops the engine instance and cleans up resources.\n * @returns {Promise<void>} Resolves when the engine is stopped.\n */\n async stop(): Promise<void> {\n // Stop the blockchain monitor\n await this.blockchainMonitor.stop();\n\n // TODO: Implement this.\n // Close the state, storage instance and all the resources.\n // await this.state.close();\n }\n\n // ============================================================================\n // Blockchain Operations\n // ============================================================================\n\n /**\n * Retrieves the current chain status from the electrum application.\n * @returns {Promise<ChainStatus>} The current chain status.\n */\n async getChainStatus(): Promise<ChainStatus> {\n return getChainStatus();\n }\n\n // ============================================================================\n // Template Management\n // ============================================================================\n\n /**\n * Retrieves a template by its identifier from the state.\n * @param {string} templateIdentifier - Template identifier.\n * @returns {Promise<XOTemplate | undefined>} The template object.\n */\n async getTemplate(templateIdentifier: string): Promise<XOTemplate | undefined> {\n // Get the template from the state.\n return this.state.getTemplate(templateIdentifier);\n }\n\n /**\n * Imports a template into the Engine after sanitization and validation.\n * @param {string | XOTemplate} untrustedJsonOrObject - JSON or object containing the untrusted template to import.\n * @returns {Promise<void>} Resolves when the template is imported.\n * @throws {TemplateImportFailedError} If the template is invalid.\n */\n async importTemplate(untrustedJsonOrObject: string | XOTemplate): Promise<{ template: XOTemplate; templateIdentifier: string }> {\n // Sanitize the template, convert the JSON into usable objects.\n // Also validates it against the schema and looks for unknown properties.\n const template = parseTemplate(untrustedJsonOrObject);\n\n // Store the template in the state.\n await this.state.storeTemplate(template);\n\n // Return the template and template identifier\n return {\n template,\n templateIdentifier: generateTemplateIdentifier(template),\n };\n }\n\n /**\n * Lists all the imported templates.\n * @returns {Promise<XOTemplate[]>} The list of imported templates.\n */\n async listImportedTemplates(): Promise<XOTemplate[]> {\n return this.state.listTemplates();\n }\n\n /**\n * Lists the starting actions available in a specified template.\n * @param {string} templateIdentifier - Template identifier.\n * @returns {Promise<Array<XOTemplateActionIntent>>} The list of starting actions.\n */\n async listStartingActions(templateIdentifier: string): Promise<Array<XOTemplateActionIntent>> {\n // Get the template from the state.\n const template = await this.getTemplateOrThrow(templateIdentifier);\n\n return new Template(template).getStartingActions();\n }\n\n /**\n * Update the unspent outputs for all of a templates lockingBytecodes.\n *\n * TODO: Make this an private/internal method.\n *\n * @param {string} templateIdentifier - Template identifier.\n * @returns {Promise<void>} Resolves when the unspent outputs are updated.\n */\n async updateUnspentOutputsForTemplate(templateIdentifier: string): Promise<void> {\n const scriptHashDataList = await this.listScriptHashesForTemplate(templateIdentifier);\n for (const scriptHashData of scriptHashDataList) {\n await this.updateUnspentOutputsForScriptHashInStore(scriptHashData.scriptHash);\n }\n }\n\n /**\n * Subscribe to the script hashes for a template.\n *\n * TODO: Make this a private/internal method. We may change how/where this is defined in the future.\n * We'd like to ensure events are propagated to the sync server with an ACK and that the states match between remote and local.\n *\n * @param {string} templateIdentifier - Template identifier.\n * @returns {Promise<void>} Resolves when the script hashes are subscribed.\n */\n async subscribeToScriptHashForTemplate(templateIdentifier: string): Promise<void> {\n // Grab our electrum client\n const [ firstElectrumClient ] = electrumClients.values();\n\n // If we don't have an electrum client, return.\n // TODO: Move this functionality to electrum package\n if (firstElectrumClient === undefined) {\n return;\n }\n\n // Grab the script hashes for the template\n const scriptHashDataList = await this.listScriptHashesForTemplate(templateIdentifier);\n\n // Subscribe to the script hashes\n for (const scriptHashData of scriptHashDataList) {\n await subscribeToScriptHashUpdates(firstElectrumClient, scriptHashData.scriptHash);\n }\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * TENTATIVE METHOD: DEFAULT LOCKING STRATEGY UNKNOWN\n *\n * Sets the default locking parameters (template, output, and role identifiers) for the engine.\n * TODO: The default identifiers exist as the strategy on how to create the change and default\n * unlocking conditions are unclear. This is likely to change in the future.\n *\n * @param {string} templateIdentifier - The identifier of the template to use as default.\n * @param {string} outputIdentifier - The identifier of the output within the specified template.\n * @param {string} roleIdentifier - The identifier of the role to use as default for this output.\n * @returns {Promise<void>} Resolves when the default parameters have been successfully set.\n * @throws {Error} If the template or output cannot be found.\n */\n async setDefaultLockingParameters(templateIdentifier: string, outputIdentifier: string, roleIdentifier: string): Promise<void> {\n this.defaultTemplateIdentifier = templateIdentifier;\n this.defaultOutputIdentifier = outputIdentifier;\n this.defaultRoleIdentifier = roleIdentifier;\n }\n\n // ============================================================================\n // State Sync\n // ============================================================================\n\n /**\n * TODO: Implement this.\n *\n * State sync should always be working, any hiccups in the sync process should be resolved\n * Unable to do so should halt all operations unless no remote servers are provided.\n *\n * Initializes the state sync process.\n * @returns {Promise<void>} Resolves when the state sync is initialized.\n */\n async initializeStateSync(): Promise<void> {\n // Sync with the local storage state and remote server(s) state.\n // TODO: Implement this.\n // this.state.initializeStateSync();\n\n // Fetch all the scriptHashes for all the templates\n const scriptHashDataList = await this.listScriptHashes();\n\n // Go through each scriptHash and update the unspent outputs for it.\n for (const scriptHashData of scriptHashDataList) {\n await this.updateUnspentOutputsForScriptHashInStore(scriptHashData.scriptHash);\n }\n }\n\n // ============================================================================\n // Invitation Operations\n // ============================================================================\n\n /**\n * Creates an invitation that can be shared with other entities, user, application, etc.\n * Invitation is the fundamental communication unit in XO, all the interactions done using the\n * xo template are done using invitations.\n *\n * @param {InvitationCreationParameters} params - The parameters for invitation creation.\n * @param {string} params.templateIdentifier - Identifier for the template to use.\n * @param {string} params.actionIdentifier - Identifier for the action to initiate.\n * @returns {Promise<XOInvitation>} A promise that resolves to the constructed invitation.\n * @throws {TemplateNotFoundError} If the template is not found.\n * @throws {TemplateActionNotFoundError} If the action is not found.\n *\n * TODO: Add all the throws that happen during the execution of the method.\n */\n async createInvitation(params: InvitationCreationParameters): Promise<XOInvitation> {\n // Get the template from the state.\n const templateFromStore = await this.getTemplateOrThrow(params.templateIdentifier);\n\n // If the action doesn't exist then this will throw\n new Template(templateFromStore).getActionOrThrow(params.actionIdentifier);\n\n // Create an invitation builder\n const invitationBuilder = new InvitationBuilder(params);\n\n const invitationCommit = invitationBuilder.createUnsignedCommit({});\n // Generate the root commit identifier for the invitation. This commit is the first commit of the invitation for this\n // entity and hence it's also the root commit identifier.\n // The invitation when stored will also store this identifier to re-create the identity(extended public key) of the entity.\n const rootCommitIdentifier = invitationCommit.commitIdentifier;\n\n // Create an unsigned invitation commit and sign it.\n const signedCommit = this.crypto.signInvitationCommitWithSchnorr({\n invitationCommit,\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the builder.\n invitationBuilder.addCommit(signedCommit);\n\n // Build the invitation, i.e. make an object\n const invitation = invitationBuilder.build();\n\n // TODO: Implement the following steps.\n // 1. Create an new event\n // 2. Push the event to the encryption server.\n // 3. Implement a strategy to trigger expiration of the invitation.\n // 4. Remove the invitation from the state after expiration\n // 5. Emit an event for the invitation expiration.\n // 6. Sync with the remote servers.\n\n // Store the invitation and entity identifier\n await this.state.storeInvitation(invitation.invitationIdentifier, {\n ...invitation,\n entityIdentifier: signedCommit.entityIdentifier,\n });\n\n return invitation;\n }\n\n /**\n * Accepts an invitation, an entity accepts an invitation and becomes part of the invitation.\n *\n * @param {XOInvitation} invitation - The invitation to be accepted.\n * @param {AcceptInvitationParameters} params - Optional parameters for accepting the invitation.\n * @returns {Promise<XOInvitation>} The updated XOInvitation instance.\n * @throws {TemplateNotFoundError} If the template is not found.\n * @throws {TemplateActionNotFoundError} If the action is not found.\n * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.\n * @throws {InvalidRequirementsError} If the requirements are invalid.\n * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.\n */\n async acceptInvitation(invitation: XOInvitation, params?: AcceptInvitationParameters): Promise<XOInvitation> {\n const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);\n // Note: In the future, it might be better to have a function that checks if the template doesn't exist and\n // has some mechanism to ask the user to import it temporarily, permanently or reject and then call the\n // function again.\n\n // TODO: add validation.\n\n // This throws if the action is not found.\n new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier);\n\n // Fetch the invitation from the store.\n const invitationFromStore = await this.state.getInvitation(invitation.invitationIdentifier);\n\n // If the invitation already exists in the store, return it.\n if (invitationFromStore !== undefined) {\n return invitationFromStore;\n }\n\n // Create an invitation builder from the existing invitation.\n const invitationBuilder = InvitationBuilder.fromInvitation(invitation);\n\n const invitationCommit = invitationBuilder.createUnsignedCommit({ ...params });\n\n // The entity is accepting the invitation, so this is the first commit in the invitation for this entity.\n // This means that the commit identifier generated will also be the root commit identifier for the entity.\n const rootCommitIdentifier = invitationCommit.commitIdentifier;\n\n // Create an unsigned commit and sign it.\n const signedCommit = this.crypto.signInvitationCommitWithSchnorr({\n invitationCommit,\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the invitation builder.\n invitationBuilder.addCommit(signedCommit);\n\n // Build the invitation, i.e. make it an object.\n const acceptedInvitation = invitationBuilder.build();\n\n // TODO: Work on the following steps.\n // 1. Create an new event\n // 2. Push the event to the encryption server.\n // 3. Implement a strategy to trigger expiration of the invitation.\n // 4. Remove the invitation from the store after expiration\n // 5. Emit an event for the invitation expiration.\n // 6. Sync with the remote servers.\n\n // Store the invitation and entity identifier.\n await this.state.storeInvitation(acceptedInvitation.invitationIdentifier, {\n ...acceptedInvitation,\n entityIdentifier: signedCommit.entityIdentifier,\n });\n\n return acceptedInvitation;\n }\n\n /**\n * Appends the invitation with the new information.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to append. The invitation must already exist in the store.\n * @param {AppendInvitationParameters} params - The parameters to append the invitation with.\n * @returns {Promise<XOInvitation>} The appended invitation.\n * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.\n */\n async appendInvitation(invitationIdentifier: string, params: AppendInvitationParameters): Promise<XOInvitation> {\n // Fetch the invitation from the store to confirm it exists.\n const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);\n\n return this.applyInvitationAppend(invitationFromStore, params);\n }\n\n /**\n * Signs the provided invitation once all the resources are reserved and the invitation is complete.\n * This method is used to sign own inputs and provide unlocking data for them, this appends the\n * invitation and adds new commit with unlocking data.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to sign. The invitation must already exist in the store.\n * @returns {Promise<XOInvitation>} Resolves when signing is complete.\n * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.\n *\n * TODO: Add all the throws that happen during the execution of the method.\n */\n async signInvitation(invitationIdentifier: string): Promise<XOInvitation> {\n // Fetch the invitation from the store to confirm it exists.\n const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);\n\n // Get the template from the store.\n const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);\n\n // Merge the invitation commits into a single commit.\n const mergedCommit = mergeInvitationCommits(invitationFromStore, template);\n\n // If no merged commit is generated then there is nothing to sign.\n if (mergedCommit === undefined) {\n throw new MergedCommitNotFoundError();\n }\n\n // TODO: Use compileInputTemplate and compileOutputTemplate from libauth and only sign the relevant and required parts.\n // TODO: This is incomplete work and won't work with other sighash schemes except for SIGHASH_ALL.\n\n // To sign the invitation and provide unlockingBytecode the engine must generate a transaction and sign.\n // Construct a transaction from the merged commit.\n const transactionResult = generateTransaction({\n version: mergedCommit.transactionVersion,\n locktime: mergedCommit.transactionLocktime,\n // @ts-expect-error Merged commit's input have more information than required by generateTransaction.\n inputs: mergedCommit.inputs,\n // @ts-expect-error Merged commit's output have more information than required by generateTransaction.\n outputs: mergedCommit.outputs,\n });\n\n // If the transaction generation fails then it means that the merged commit is invalid.\n // TODO: Improve error messaging, this can fail for multiple reasons.\n if (transactionResult.success === false) {\n throw new TransactionGenerationFailedError();\n }\n\n // Since the transaction is generated, now lookup all the reserved unspentoutputs for the invitation.\n const unspentOutputs = await this.state.listUnspentOutputsData({ reservedBy: invitationFromStore.invitationIdentifier });\n\n // Find all inputs in the transaction that belongs to the entity and provide the unlocking data for them.\n // TODO: Use the derived inputs from compileInputTemplate and collect the unlocking data for each input within this loop.\n // This will also remove the reliance of keeping the derived private key for the compiler in an object and use it later\n // when the transaction is signed using the compiler.\n for (const [ index, input ] of transactionResult.transaction.inputs.entries()) {\n // Find the unspent output that is reserved for the invitation.\n let unspentOutput: UnspentOutputData | undefined;\n for (const sourceOutput of unspentOutputs) {\n if (\n sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash)\n && sourceOutput.outpointIndex === input.outpointIndex\n && sourceOutput.reservedBy\n // TODO: Add strategy of unconfirmed outputs spending.\n // && sourceOutput.status === UnspentOutputStatus.CONFIRMED\n ) {\n unspentOutput = sourceOutput;\n break;\n }\n }\n\n // If the unspent output is not found, it means that the input does not belong to the entity.\n if (!unspentOutput) {\n continue;\n }\n\n // The selected unspent output has a locking bytecode, it stores unlocking conditions\n // that are used for generating the unlocking bytecode.\n const scriptHashData = await this.state.getScriptHashData(unspentOutput.scriptHash);\n\n // If the script hash data record is not found, throw an error.\n // This should never happen for inputs reserved through the engine.\n if (scriptHashData === undefined) {\n throw new ScriptHashDataNotFoundError(unspentOutput.scriptHash);\n }\n\n let compilerPrivateKeyRecord: PrivateKeyRecordForLibauthCompiler | undefined;\n\n if (scriptHashData.derivationSource !== undefined) {\n if (scriptHashData.derivationSource.lockingType === 'p2pkh') {\n // Each locking bytecode might have been generated by a different template (lockingscripts).\n // Get the template data from the state.\n const templateDataForInput = await this.state.getTemplate(scriptHashData.templateIdentifier);\n\n // This should never happen.\n if (templateDataForInput === undefined) {\n throw new TemplateNotFoundError(scriptHashData.templateIdentifier);\n }\n\n // Create a template object from the template data.\n const templateInstanceForInput = new Template(templateDataForInput);\n\n // TODO: Move the generation part and secrets to crypto module.\n\n // Get the locking script identifier for the output that can unlock the unspent output.\n const lockingScriptIdentifier = templateInstanceForInput.getLockingScriptIdentifierOrThrow(scriptHashData.outputIdentifier);\n\n // Get the secret identifiers for the locking script.\n const secretIdentifiers = templateInstanceForInput.getSecrets(lockingScriptIdentifier, scriptHashData.roleIdentifier);\n\n // Generate the unlocking data for the compiler.\n const { derivativeIndex } = scriptHashData.derivationSource;\n if (typeof derivativeIndex !== 'string') {\n throw new InvalidDerivativeIndexTypeError('string', typeof derivativeIndex);\n }\n\n compilerPrivateKeyRecord = this.crypto.derivePrivateKeyRecordForCompiler({\n compilerKeyIdentifiers: secretIdentifiers,\n templateIdentifier: scriptHashData.templateIdentifier,\n templateKeyDerivationIndex: Number(derivativeIndex),\n });\n }\n }\n\n // If the unlocking data is not found, throw an error.\n if (compilerPrivateKeyRecord === undefined) {\n throw new LockingDataNotFoundError();\n }\n\n // Generate the compiler data for the input.\n const compilerData = await createLibauthCompilerDataFromUnspentOutput(new Template(template), unspentOutput);\n // Update the input with the unlocking bytecode.\n // TODO: No proper defined type for the data yet. Needs fixing.\n transactionResult.transaction.inputs[index] = {\n ...input,\n unlockingBytecode: {\n ...compilerData,\n // @ts-expect-error TODO: No proper defined type for the data yet. Needs fixing.\n data: compilerPrivateKeyRecord,\n },\n };\n }\n\n // TODO: Once the inputs are already compiled above, there will be no need to call this function.\n // Aggregation of inputs and constructing the transaction will be sufficient.\n const signedTransaction = generateTransaction({\n version: transactionResult.transaction.version,\n locktime: transactionResult.transaction.locktime,\n inputs: transactionResult.transaction.inputs,\n outputs: transactionResult.transaction.outputs,\n });\n\n if (signedTransaction.success === false) {\n throw new TransactionGenerationFailedError();\n }\n\n // Now that we have signed the relevant parts in the transaction, we need to extend the invitation by\n // providing the unlocking data to each of the inputs.\n\n // Use a StoredInvitation variable to carry the entityIdentifier across loop iterations\n // without re-fetching from the store on each append.\n let currentStoredInvitation: StoredInvitation = invitationFromStore;\n\n // Find all inputs in the transaction that belongs to the entity and provide the unlocking data for them.\n // TODO: Instead of looping through again, it might make sense to prepare a list in the previous loop and use it here.\n for (const input of signedTransaction.transaction.inputs.values()) {\n // Find the unspent output that is reserved for the invitation.\n // TODO: This is not efficient and might need to be optimized once a list is formed in the previous loop.\n let unspentOutput: UnspentOutputData | undefined;\n for (const sourceOutput of unspentOutputs) {\n if (\n sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash)\n && sourceOutput.outpointIndex === input.outpointIndex\n // && sourceOutput.reserved === true\n // && sourceOutput.status === UnspentOutputStatus.CONFIRMED\n ) {\n unspentOutput = sourceOutput;\n break;\n }\n }\n\n // If the unspent output is not found, it means that the input does not belong to the entity.\n if (unspentOutput === undefined) {\n throw new UnspentOutputNotFoundError();\n }\n\n // Find the commit that has the same outpointTransactionHash and outpointIndex and use the commit's identifier\n // to point to the commit that will be extended.\n\n // This represents the commit that will be extended.\n let commitToExtend: XOInvitationCommit | undefined;\n\n // This represents the index of the input in the commit that will be extended.\n let indexToExtend: number | undefined;\n\n for (const commit of currentStoredInvitation.commits) {\n for (const [ index, commitInput ] of (commit.data.inputs ?? []).entries()) {\n if (\n commitInput.outpointTransactionHash\n && binToHex(commitInput.outpointTransactionHash) === binToHex(input.outpointTransactionHash)\n && Number(commitInput.outpointIndex) === Number(input.outpointIndex)\n ) {\n commitToExtend = commit;\n indexToExtend = index;\n }\n }\n }\n\n // If the commit to extend is not found or the index to extend is not found, throw an error.\n // This should never happen.\n if (commitToExtend === undefined || indexToExtend === undefined) {\n throw new CommitNotFoundInInvitationError();\n }\n\n // Apply the unlocking commit directly using the in-memory stored invitation to avoid\n // an unnecessary store round-trip on each loop iteration.\n const updatedInvitation = await this.applyInvitationAppend(currentStoredInvitation, {\n inputs: [\n {\n mergesWith: {\n commitIdentifier: commitToExtend.commitIdentifier,\n index: indexToExtend,\n },\n unlockingBytecode: input.unlockingBytecode,\n },\n ],\n });\n\n // Carry the entityIdentifier forward so the next iteration can still sign correctly.\n currentStoredInvitation = { ...updatedInvitation, entityIdentifier: invitationFromStore.entityIdentifier };\n }\n\n // Return the extended invitation.\n return currentStoredInvitation;\n }\n\n /**\n * Executes an action for a given invitation.\n * @param {string} invitationIdentifier - The identifier of the invitation whose action to execute.\n * The invitation must already exist in the store.\n * @param {ExecuteActionParameters} params - Parameters for executing the action.\n * @returns {Promise<TransactionHash>} Resolves with the transaction hash when the action is executed.\n * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.\n *\n * TODO: Add all the throws that happen during the execution of the method.\n */\n async executeAction(invitationIdentifier: string, params: ExecuteActionParameters): Promise<TransactionHash> {\n // Fetch the invitation from the store to confirm it exists.\n const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);\n\n // Get the template from the state.\n const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);\n\n // Merge invitation commits into transaction data\n const mergedCommit = mergeInvitationCommits(invitationFromStore, template);\n\n // If no merged commit is generated then there is nothing to sign.\n if (mergedCommit === undefined) {\n throw new MergedCommitNotFoundError();\n }\n\n // Get the action from the template.\n const action = new Template(template).getActionOrThrow(invitationFromStore.actionIdentifier);\n\n if (action.transaction === undefined) {\n throw new TemplateTransactionNotFoundError(invitationFromStore.actionIdentifier);\n }\n\n // To execute the action generate the transaction\n // TODO: Use compileInputTemplate and compileOutputTemplate from libauth and only sign the relevant and required parts.\n const resultTransaction = generateTransaction({\n version: mergedCommit.transactionVersion,\n locktime: mergedCommit.transactionLocktime,\n // @ts-expect-error merged commit's input have more information than required by generateTransaction.\n inputs: mergedCommit.inputs,\n // @ts-expect-error merged commit's output have more information than required by generateTransaction.\n outputs: mergedCommit.outputs,\n });\n\n // If the transaction generation fails then it means that the merged commit is invalid.\n if (!resultTransaction.success) {\n throw new TransactionGenerationFailedError();\n }\n\n // Encode the transaction\n const transactionHex = binToHex(encodeTransaction(resultTransaction.transaction));\n\n // Hash the transaction.\n const txHash = hashTransaction(hexToBin(transactionHex));\n\n // If the broadcastTransaction flag is set, broadcast the transaction to the blockchain.\n if (params.broadcastTransaction) {\n // TODO: Work on the following steps.\n // 1. Broadcast the transaction to the blockchain.\n // 2. Subscribe to the transaction hash for confirmations.\n // 3. Update the invitation status and add transaction details.\n // 4. Update the transaction status as well as the invitation status as per the transaction updates.\n // 5. Create an event and store it in the local storage.\n // 6. Push the event to the encryption server.\n const broadcastResult = await broadcastTransaction(transactionHex);\n\n return broadcastResult;\n }\n\n return txHash;\n }\n\n // ============================================================================\n // Invitation Queries\n // ============================================================================\n\n /**\n * Lists available roles for the given invitation.\n *\n * @param {XOInvitation} invitation - The invitation to examine.\n * @returns {Promise<string[]>} The list of roles that still require data.\n * @throws {TemplateNotFoundError} If the template is not found.\n * @throws {TemplateActionNotFoundError} If the action is not found.\n */\n async listAvailableRoles(invitation: XOInvitation): Promise<string[]> {\n // Get the template from the state.\n const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);\n\n // Get the action from the template.\n const action = new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier);\n\n // List the available roles for the invitation.\n return listAvailableRolesForInvitation(invitation, action);\n }\n\n /**\n * Lists requirements for the provided invitation.\n *\n * @param {XOInvitation} invitation - The invitation to analyze requirements for.\n * @returns {Promise<XOInvitationRequirements>} The requirements information.\n *\n */\n async listRequirements(invitation: XOInvitation): Promise<XOInvitationRequirements> {\n // Get the template from the state.\n const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);\n\n // Get the action from the template.\n const action = new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier);\n\n // List the requirements for the invitation.\n return listRequirementsFromTemplate(templateFromStore, action);\n }\n\n /**\n * Lists missing requirements for the provided invitation.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to analyze. The invitation must already exist in the store.\n * @returns {Promise<XOInvitationRequirements>} The missing requirements.\n * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.\n */\n async listMissingRequirements(invitationIdentifier: string): Promise<XOInvitationRequirements> {\n // Fetch the invitation from the store to confirm it exists.\n const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);\n\n // Get the template from the state.\n const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);\n\n // Get the action from the template.\n const action = new Template(template).getActionOrThrow(invitationFromStore.actionIdentifier);\n\n // List the missing requirements for the invitation.\n return listMissingRequirements(invitationFromStore, template, action);\n }\n\n // ============================================================================\n // Resource Management\n // ============================================================================\n\n /**\n * Lists all the unspent outputs.\n *\n * @returns {Promise<UnspentOutputData[]>} The list of unspent outputs.\n */\n async listUnspentOutputsData(): Promise<UnspentOutputData[]> {\n return this.state.listUnspentOutputsData();\n }\n\n /**\n * Finds suitable resources for an invitation.\n *\n * TODO: May become private. This may change in the future and become a more advanced coin selection method used directly by the engine.\n * The current behavior is that it finds \"spendable\" outputs, but we may adjust this to actually find \"suitable\" outputs.\n *\n * @param {XOInvitation} invitation - The invitation to find resources for.\n * @param {GetSpendableResourcesParameters} options - Parameters for finding suitable resources.\n * @returns {Promise<{ unspentOutputs: UnspentOutputData[] }>} The list of suitable resources.\n */\n async getSpendableResources(\n invitation: XOInvitation,\n options?: GetSpendableResourcesParameters,\n ): Promise<{\n unspentOutputs: UnspentOutputData[];\n }> {\n // TODO: Perform validations\n const { templateIdentifier } = invitation;\n\n // Get the template from the state.\n const templateData = await this.state.getTemplate(templateIdentifier);\n\n // If the template is not found, throw an error.\n if (templateData === undefined) {\n throw new TemplateNotFoundError(templateIdentifier);\n }\n\n // Resolve the source template and output identifiers from the options, falling back to the engine defaults.\n const sourceTemplateIdentifier = options?.templateIdentifier ?? this.defaultTemplateIdentifier;\n const sourceOutputIdentifier = options?.outputIdentifier ?? this.defaultOutputIdentifier;\n\n // Validate the resolved source template and output exist in the state before querying UTXOs.\n const rawSourceTemplate = await this.state.getTemplate(sourceTemplateIdentifier);\n if (rawSourceTemplate === undefined) {\n throw new TemplateNotFoundError(sourceTemplateIdentifier);\n }\n\n // Validate the resolved output identifier exists in the source template.\n new Template(rawSourceTemplate).getOutputOrThrow(sourceOutputIdentifier);\n\n // Gather the script hash data for the resolved source template.\n const scriptHashDataList = await this.state.listScriptHashData({ templateIdentifier: sourceTemplateIdentifier });\n\n // Create an array of unspent outputs to store out of the filtering process into.\n const unspentOutputs: Array<UnspentOutputData> = [];\n\n // Iterate over the lockingBytecodes and filter the outputs.\n for (const scriptHashData of scriptHashDataList) {\n // Get the list of unspent outputs for the script hash.\n const outputsByScriptHash = await this.state.listUnspentOutputsData({ scriptHash: scriptHashData.scriptHash });\n\n // Filter the unspent outputs.\n // TODO: Finalize on a strategy, e.g selection based on the the status of the output etc.\n const unspentOutputsByScriptHash: UnspentOutputData[] = [];\n for (const output of outputsByScriptHash) {\n // If this output is not reserved, add it to the list.\n if (output.reservedBy === undefined) {\n unspentOutputsByScriptHash.push(output);\n }\n }\n\n unspentOutputs.push(...unspentOutputsByScriptHash);\n }\n\n // Return the unspent outputs\n return { unspentOutputs };\n }\n\n // ============================================================================\n // Script Hash Operations\n // ============================================================================\n\n /**\n * Retrieves a list of script hash data stored for a given template identifier.\n *\n * @param {string} templateIdentifier - The identifier of the template.\n * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.\n */\n async listScriptHashesForTemplate(templateIdentifier: string): Promise<ScriptHashData[]> {\n return this.state.listScriptHashData({ templateIdentifier });\n }\n\n /**\n * Gets all the script hashes from all the templates.\n *\n * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.\n */\n async listScriptHashes(): Promise<ScriptHashData[]> {\n // First, get all the templates\n const templates = await this.state.listTemplates();\n\n // Get the template identifiers\n const templateIdentifiers = templates.map((template) => generateTemplateIdentifier(template));\n\n // Then, call listScriptHashData for each template\n const scriptHashDataPromises = templateIdentifiers.map((templateIdentifier) => this.listScriptHashesForTemplate(templateIdentifier));\n\n // Wait for all the script hash data promises to resolve\n const scriptHashDataList = await Promise.all(scriptHashDataPromises);\n\n // Flatten the array of script hash data\n return scriptHashDataList.flat();\n }\n\n /**\n * Generates the locking bytecode for a specified template output and role.\n *\n * Role is important because in the template definition it can direct to a different secret or a locking script\n * for that to be discovered and used, it must know what role is provided. Also, it's important for libauth compiler\n * to know what role is being used to generate the locking bytecode.\n *\n * Currently, only \"standard\" type (e.g. P2PKH) locking scripts are supported.\n * In the future, this method will be extended to support more output script types based on template definitions.\n *\n * Future definition of primitives is going to define how other non-p2pkh locking scripts are validated,\n * for example, p2pkh is possible because the engine know what a private key and public key is more such primitives\n * will be defined and they will be helpful in generating and validating locking scripts of different types.\n *\n * Process overview:\n * - Fetch the template and output definition by their identifiers.\n * - Find the relevant locking script and roles.\n * - Select the specified role or fallback to the first available role.\n * - Build the entity ownership mapping, scripts, and variable definitions for Libauth.\n * - Set up unlocking scripts and locking script type for the compiler configuration.\n * - For \"standard\" lock scripts, generate entropy if required. (TODO: Improve entropy generation.)\n * - Compile the locking bytecode with the Libauth compiler.\n * - Subscribe to blockchain updates for the script hash and store the resulting bytecode.\n *\n * TODO: Support additional types of outputs/scripts tied to template specification.\n * TODO: If important to make this process faster, consider emitting an event and pushing process to the event loop.\n * TODO: Encrypt the new information, update the encrypted state servers.\n *\n * @param {string} templateIdentifier - Identifier of the template.\n * @param {string} outputIdentifier - Identifier of the output (from the template).\n * @param {string} roleIdentifier - Role identifier (corresponding to a role in the output's script).\n * @returns {Promise<string>} The generated locking bytecode as a hexadecimal string.\n * @throws {Error} If any required template, output, or configuration is not found, or if compilation fails.\n */\n async generateLockingBytecode(templateIdentifier: string, outputIdentifier: string, roleIdentifier?: string): Promise<string> {\n // Get the template data from the state.\n const templateFromStore = await this.getTemplateOrThrow(templateIdentifier);\n\n // Create a template class instance from the template data\n const template = new Template(templateFromStore);\n\n // Get the output from the template.\n const output = template.getOutputOrThrow(outputIdentifier);\n\n // Get the locking script from the output in template\n const lockingScriptForOutput = template.getLockingScriptForOutputOrThrow(outputIdentifier);\n\n // Get the role from the output in template. Or auto-select the first role if no role identifier is provided.\n const selectedRoleId = roleIdentifier ?? template.getFirstRoleOrThrow(output.lockingScript)[0];\n // Validate role exists if provided\n if (roleIdentifier) {\n template.getRoleOrThrow(output.lockingScript, roleIdentifier);\n }\n\n const finalRoleIdentifier = selectedRoleId;\n\n // Gather up all the variables that are owned by the role in the template.\n // The entity ownership just maps those variables to the role.\n // TODO: For now all the variables are assigned to a selected role.\n const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), finalRoleIdentifier);\n\n // Gather up all the scripts from the template.\n const scripts = scriptsForLibauthCompiler(template.getTemplate());\n\n // Gather up all the variables from the template and assign a type to them.\n // Key, HDKey, WalletData, AddressData, etc.\n const variables = assignTypeToVariablesForLibauthCompiler(template.getTemplate());\n\n // Gather up all the unlocking scripts from the template.\n // TODO: Has hardcoded value, finalize on the value.\n if (lockingScriptForOutput.unlockingBytecode === undefined || lockingScriptForOutput.lockingBytecode === undefined) {\n throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);\n }\n\n const unlockingScripts: CompilerConfiguration['unlockingScripts'] = {\n [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode,\n };\n\n const { lockingType } = lockingScriptForOutput;\n\n // hard coded lock type for p2pkh\n const lockingScriptTypes: CompilerConfiguration['lockingScriptTypes'] = { lock: convertXOLockingTypeToLibauth(lockingType) };\n\n // Create the compiler configuration\n const libauthCompilerConfig = {\n entityOwnership,\n scripts,\n variables,\n unlockingScripts,\n lockingScriptTypes,\n };\n const compiler = createCompilerBch(libauthCompilerConfig);\n\n let lockingBytecodeMetadata: { lockingType?: string; derivativeIndex?: string } = { lockingType: lockingScriptForOutput.lockingType };\n\n let lockingData: PrivateKeyRecordForLibauthCompiler | undefined;\n\n switch (lockingScriptForOutput.lockingType) {\n case 'p2pkh': {\n const { lockingData: standardLockingData, derivativeIndex: standardDerivativeIndex } = await this.generateLockingDataForStandardP2PKH(\n templateIdentifier,\n outputIdentifier,\n finalRoleIdentifier,\n lockingScriptForOutput,\n );\n\n lockingData = standardLockingData;\n lockingBytecodeMetadata = {\n ...lockingBytecodeMetadata,\n derivativeIndex: standardDerivativeIndex,\n };\n break;\n }\n\n default:\n throw new TemplateLockingScriptTypeNotFoundError(output.lockingScript ?? outputIdentifier);\n }\n\n // If no locking data has been generated yet, throw an error.\n if (!lockingData) {\n throw new LockingDataNotFoundError();\n }\n\n // The locking bytecode identifier\n const scriptId = lockingScriptForOutput.lockingBytecode;\n const resultLockingBytecode = compiler.generateBytecode({\n data: lockingData,\n scriptId,\n });\n\n if (!resultLockingBytecode.success) {\n throw new LockingBytecodeGenerationFailedError();\n }\n\n const lockingBytecode = binToHex(resultLockingBytecode.bytecode);\n const scriptHash = scriptToScriptHash(hexToBin(lockingBytecode));\n\n // TODO: Consider event emitting if same guarantee is provided. Ensure that all the steps are executed without fail.\n\n // 1. Store locking bytecode and it's metadata in the state.\n // 2. Subscribe to the scriptHash updated\n // 3. Fetch and update unspent outputs for the newly generated locking bytecode.\n // 4. Store the event data in the state.\n // 5. Encrypt the new information and push it to the encryption server.\n\n // Find if a script hash already exists in the state.\n // TODO: Consider directly calling the state function and if it already exists just return.\n const existingScriptHashData = await this.state.getScriptHashData(scriptHash);\n if (existingScriptHashData) {\n // TODO: Even if the script hash already exists:\n // 1. Ensure subscribed.\n // 2. Update unspent outputs.\n // 3. Register event and push to encryption server.\n\n return existingScriptHashData.lockingBytecode;\n }\n\n // Note: No subscription identifier is provided as soon as the subscription is created.\n // 1. Either create the hash i.e the subscription identifier and store it\n // 2. OR wait for an event to be emitted and then get the identifier from the event and update the store.\n const [ firstElectrumClient ] = electrumClients.values();\n if (!firstElectrumClient) {\n throw new ElectrumClientNotFoundError();\n }\n\n await subscribeToScriptHashUpdates(firstElectrumClient, scriptHash);\n\n // TODO: Get a returned boolean value OR throw.\n await this.state.storeScriptHashData({\n lockingBytecode,\n derivationSource: lockingBytecodeMetadata,\n scriptHash,\n templateIdentifier,\n outputIdentifier,\n roleIdentifier: finalRoleIdentifier,\n });\n\n // Also lookup if any existing unspent outputs for this locking bytecode and update the state.\n await this.updateUnspentOutputsForScriptHashInStore(scriptHash);\n\n // TODO: Encrypt the new information, update the encrypted state servers.\n\n return lockingBytecode;\n }\n\n /**\n * Generates a locking bytecode using the engine's default template, output, and role identifiers.\n *\n * @returns A promise that resolves to the generated locking bytecode as a string.\n */\n async generateLockingBytecodeForDefaultParameters(): Promise<string> {\n return this.generateLockingBytecode(this.defaultTemplateIdentifier, this.defaultOutputIdentifier, this.defaultRoleIdentifier);\n }\n\n /**\n * Generate locking data and derivative index for P2PKH.\n */\n async generateLockingDataForStandardP2PKH(\n templateIdentifier: string,\n outputIdentifier: string,\n roleIdentifier: string,\n lockingScriptForOutput: XOTemplateLockingScript,\n ): Promise<{ lockingData: PrivateKeyRecordForLibauthCompiler; derivativeIndex: string }> {\n // Get the last derivative index for the P2PKH.\n const lastDerivativeIndex = await this.state.getLastDerivativeIndexForP2PKH(templateIdentifier, outputIdentifier);\n\n // If the last derivative index is null, set it to 0, otherwise increment it by 1.\n const derivativeIndex = lastDerivativeIndex === null ? '0' : (parseInt(lastDerivativeIndex, 10) + 1).toString();\n\n // Get the private key identifiers for the role.\n const role = lockingScriptForOutput.roles?.[roleIdentifier];\n const privateKeyIdentifiers: string[] = role?.state?.secrets ?? [];\n\n // Create the private key mapping for the compiler.\n const lockingData = this.crypto.derivePrivateKeyRecordForCompiler({\n compilerKeyIdentifiers: privateKeyIdentifiers,\n templateIdentifier,\n templateKeyDerivationIndex: Number(derivativeIndex),\n });\n\n return { lockingData, derivativeIndex: derivativeIndex };\n }\n\n /**\n * Fetches a stored invitation by identifier\n *\n * @param {string} invitationIdentifier - The identifier to look up.\n * @returns {Promise<StoredInvitation | undefined>} The stored invitation, or undefined.\n */\n async getInvitationOrThrow(invitationIdentifier: string): Promise<StoredInvitation> {\n // TODO: Perform validations on invitation identifier e.g 16 bytes long hex string.\n\n const invitation = await this.state.getInvitation(invitationIdentifier);\n if (invitation === undefined) {\n throw new InvitationNotFoundInStoreError(invitationIdentifier);\n }\n\n return invitation;\n }\n\n /**\n * Fetches a stored template by identifier\n *\n * @param {string} templateIdentifier - The identifier to look up.\n * @returns {Promise<XOTemplate>} The stored template.\n */\n async getTemplateOrThrow(templateIdentifier: string): Promise<XOTemplate> {\n // TODO: Perform validations on template identifier e.g 32 bytes long hex string.\n\n const template = await this.state.getTemplate(templateIdentifier);\n if (template === undefined) {\n throw new TemplateNotFoundError(templateIdentifier);\n }\n\n return template;\n }\n\n /**\n * Synchronizes the store of unspent outputs for a given script hash with the current state of the blockchain.\n *\n * This method performs the following:\n * 1. Retrieves the stored script hash data from the store.\n * 2. Fetches the current list of unspent outputs for the script hash from the store.\n * 3. Computes the corresponding scripthash from the script hash.\n * 4. Queries the blockchain for all unspent transaction outputs associated with the scripthash.\n * 5. Adds any new unspent outputs found on the blockchain but missing from the store to the store.\n * 6. Removes any unspent outputs present in the store but no longer in the blockchain.\n *\n * @param scriptHash - The script hash for which to update the stored unspent outputs.\n * @throws If the script hash is not found in the store.\n */\n async updateUnspentOutputsForScriptHashInStore(scriptHash: string): Promise<void> {\n const [ firstElectrumClient ] = electrumClients.values();\n if (!firstElectrumClient) {\n throw new ElectrumClientNotFoundError();\n }\n\n await updateUnspentOutputsForScriptHashInStore(this.state, scriptHash, async (scripthash: string) => {\n return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scripthash);\n });\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * TODO: Internal function, move elsewhere.\n *\n * Finds own inputs and prepares a list for the lookup in the store.\n *\n * @param {XOInvitationInput[]} inputs - The inputs to find resources for.\n * @returns {Promise<XOInvitationInput[]>} The list of own inputs for reservation.\n */\n private async findOwnResources(inputs: XOInvitationInput[]): Promise<XOInvitationInput[]> {\n const inputsForReservation: XOInvitationInput[] = [];\n\n if (inputs) {\n for (const input of inputs) {\n // If the input has the mergesWith property, it means it is extending from a parent commit.\n // TODO: For now it assumes that apart from unlockingbytecode all would be provided in the parent commit.\n // It's important to note that the reservation of the resources will happen by the party that owns\n // the input. So if it's being extended then it means that the party already provided other information\n // and is not providing the unlockingbytecode.\n if (input.mergesWith) {\n continue;\n }\n\n inputsForReservation.push({\n outpointTransactionHash: input.outpointTransactionHash,\n outpointIndex: input.outpointIndex,\n });\n }\n }\n\n // Return the inputs for reservation.\n return inputsForReservation;\n }\n\n /**\n * Applies an invitation append operation to a stored invitation. Signs a new commit using the\n * engine's own entity, persists the updated invitation to the store, and returns the result.\n *\n * This is the shared implementation used by both the public {@link appendInvitation} method\n * and internal callers that already hold the stored invitation in memory.\n *\n * @param {StoredInvitation} storedInvitation - The stored invitation to append to.\n * @param {AppendInvitationParameters} params - The parameters to append.\n * @returns {Promise<XOInvitation>} The updated invitation after the new commit is applied.\n */\n private async applyInvitationAppend(storedInvitation: StoredInvitation, params: AppendInvitationParameters): Promise<XOInvitation> {\n // Find the root commit identifier for the entity from the stored invitation.\n const rootCommitIdentifier = findRootCommitIdentifierInInvitation(storedInvitation, storedInvitation.entityIdentifier);\n\n // If the root commit identifier is not found, throw an error.\n if (rootCommitIdentifier === undefined) {\n throw new RootCommitNotFoundError(storedInvitation.entityIdentifier);\n }\n\n // If outputs are provided as part of the parameters then check if the outputs are merging with a parent commit.\n if (params.outputs !== undefined) {\n for (const output of params.outputs) {\n // Skip output if any of these are set:\n // - mergesWith: output is intended to merge with a parent commit,\n // - roleIdentifier: output is tied to a specific role,\n // - lockingBytecode: output already has its script generated.\n if (output.mergesWith !== undefined || output.roleIdentifier !== undefined || output.lockingBytecode !== undefined) {\n continue;\n }\n\n // If outputIdentifier is provided and lockingBytecode doesn't exist then engine must generate the locking bytecode.\n const lockingBytecode = await this.generateLockingBytecodeForDefaultParameters();\n\n // Add the locking bytecode to the output.\n output.lockingBytecode = hexToBin(lockingBytecode);\n }\n }\n\n // Create an invitation builder from the stored invitation.\n const invitationBuilder = InvitationBuilder.fromInvitation(storedInvitation);\n\n // Create an unsigned commit and sign it.\n const signedCommit = this.crypto.signInvitationCommitWithSchnorr({\n invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the builder.\n invitationBuilder.addCommit(signedCommit);\n\n // TODO: Work on the following steps.\n // 1. Create an event and store in the local state.\n // 2. Push the events to the encryption server.\n // 3. Lookup the resources (i.e inputs) and mark them as reserved\n // 4. Register this event in local state and push to the encryption server.\n // 5. Store the updated invitation in the store and sync with the remote servers.\n\n // Once signatures are added to the commit, reserve the resources.\n const inputsForReservation = await this.findOwnResources(params.inputs ?? []);\n if (inputsForReservation.length > 0) {\n await this.reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);\n }\n\n // Build the updated invitation, i.e make it an object.\n const updatedInvitation = invitationBuilder.build();\n\n // Store the updated invitation.\n await this.state.storeInvitation(updatedInvitation.invitationIdentifier, {\n ...updatedInvitation,\n entityIdentifier: storedInvitation.entityIdentifier,\n });\n\n // Return the updated invitation.\n return updatedInvitation;\n }\n\n /**\n * Reserves utxos and store information in the storage.\n *\n * @param {XOInvitationInput[]} inputs - The inputs to reserve.\n * @param {string} invitationIdentifier - The identifier of the invitation for which the resources are being reserved.\n * @returns {Promise<void>} Resolves when the reservation is complete.\n */\n private async reserveResources(inputs: XOInvitationInput[], invitationIdentifier: string): Promise<void> {\n const outpoints: Array<{ outpointTransactionHash: string; outpointIndex: number }> = [];\n\n for (const input of inputs) {\n if (!input.outpointTransactionHash || input.outpointIndex === undefined) {\n throw new InvalidInputError();\n }\n\n outpoints.push({\n outpointTransactionHash: binToHex(input.outpointTransactionHash),\n outpointIndex: input.outpointIndex,\n });\n }\n\n await this.state.executeBulkUnspentOutputReservation(outpoints, true, invitationIdentifier);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,IAAa,8BAAb,cAAiD,MAAM;CACnD,YAAY,kBAA0B;AAClC,QAAM,gDAAgD,iBAAiB,GAAG;;;;;;AAOlF,IAAa,8BAAb,cAAiD,MAAM;CACnD,YAAY,kBAA0B;AAClC,QAAM,gDAAgD,iBAAiB,GAAG;;;;;;AAOlF,IAAa,wBAAb,cAA2C,MAAM;CAC7C,YAAY,oBAA4B;AACpC,QAAM,2CAA2C,mBAAmB,GAAG;;;;;;AAO/E,IAAa,qCAAb,cAAwD,MAAM;CAC1D,YAAY,yBAAiC;AACzC,QAAM,+DAA+D,wBAAwB,GAAG;;;;;;AAOxG,IAAa,yCAAb,cAA4D,MAAM;CAC9D,YAAY,yBAAiC;AACzC,QAAM,oEAAoE,wBAAwB,GAAG;;;;;;AAO7G,IAAa,+BAAb,cAAkD,MAAM;CACpD,YAAY,2BAAoC;EAC5C,MAAM,iBAAiB;AACvB,QAAM,4BAA4B,GAAG,eAAe,+BAA+B,0BAA0B,KAAK,eAAe;;;;;;AAOzI,IAAa,sBAAb,cAAyC,MAAM;CAC3C,YAAY,kBAA2B;EACnC,MAAM,iBAAiB;AACvB,QAAM,mBAAmB,GAAG,eAAe,sBAAsB,iBAAiB,KAAK,eAAe;;;;;;AAO9G,IAAa,8BAAb,cAAiD,MAAM;CACnD,YAAY,oBAA6B;EACrC,MA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kBAAkB,OAAO;AAGnD,QAAM,KAAK,MAAM,gBAAgB,kBAAkB,sBAAsB;GACrE,GAAG;GACH,kBAAkB,iBAAiB;GACtC,CAAC;AAGF,SAAO;;;;;;;;;CAUX,MAAc,iBAAiB,QAA6B,sBAA6C;EACrG,MAAM,YAA+E,EAAE;AAEvF,OAAK,MAAM,SAAS,QAAQ;AACxB,OAAI,CAAC,MAAM,2BAA2B,MAAM,kBAAkB,OAC1D,OAAM,IAAI,mBAAmB;AAGjC,aAAU,KAAK;IACX,yBAAyB,SAAS,MAAM,wBAAwB;IAChE,eAAe,MAAM;IACxB,CAAC;;AAGN,QAAM,KAAK,MAAM,oCAAoC,WAAW,MAAM,qBAAqB"}
1
+ {"version":3,"file":"index.mjs","names":["#hdKeyNetwork","#commits","#createdAtTimestamp","#result","#storeTransactionResult","#validateMergesWithReferences","#createCommit","#state","#eventListenersInitialized","#network","#crypto","#state","#blockchainMonitor","#monitorStoredScriptHashes","#accountContext"],"sources":["../source/defaults.ts","../source/network/helper.ts","../source/errors/template.ts","../source/errors/invitation.ts","../source/errors/compilation.ts","../source/errors/transaction.ts","../source/errors/wallet.ts","../source/template.ts","../source/compilation/secrets.ts","../source/invitation/helpers/secrets.ts","../source/invitation/helpers/identifiers.ts","../source/invitation/participation/builder.ts","../source/invitation/participation/role.ts","../source/resolutions/combine.ts","../source/invitation/merge/chain.ts","../source/invitation/validation/committed-fields.ts","../source/invitation/helpers/roles.ts","../source/invitation/validation/follow-up-roles.ts","../source/invitation/validation/role-variables.ts","../source/invitation/participation/accept.ts","../source/invitation/participation/create.ts","../source/invitation/helpers/commits.ts","../source/invitation/helpers/outpoints.ts","../source/invitation/participation/apply-append.ts","../source/invitation/requirements/roles.ts","../source/invitation/participation/join.ts","../source/compilation/libauth-utils.ts","../source/compilation/compilation-keys.ts","../source/compilation/template-locking-bytecode.ts","../source/compilation/locking-script-role.ts","../source/network/electrum.ts","../source/network/blockchain.ts","../source/state/unspent-outputs.ts","../source/compilation/generate-locking-bytecode.ts","../source/invitation/participation/append.ts","../source/invitation/merge/order.ts","../source/compilation/intent-variables.ts","../source/invitation/generation/locking-bytecode.ts","../source/invitation/helpers/outputs.ts","../source/invitation/helpers/transaction-result.ts","../source/invitation/validation/invitation.ts","../source/invitation/participation/update.ts","../source/invitation/requirements/signatures.ts","../source/invitation/requirements/template.ts","../source/compilation/generate-unlocking-bytecode.ts","../source/resolutions/value-satoshis.ts","../source/resolutions/transaction-index.ts","../source/resolutions/token.ts","../source/invitation/merge/complete.ts","../source/invitation/merge/merge-commits.ts","../source/invitation/merge/merge-targets.ts","../source/invitation/helpers/merged-invitation.ts","../source/invitation/generation/transaction.ts","../source/invitation/participation/execute.ts","../source/invitation/requirements/stored.ts","../source/invitation/helpers/own-inputs.ts","../source/invitation/generation/unlocking-bytecode.ts","../source/state/default-policies.ts","../source/compilation/intent-locking-bytecode.ts","../source/invitation/change/derive.ts","../source/invitation/change/add.ts","../source/engine.ts"],"sourcesContent":["import { StorageType } from '@xo-cash/state';\nimport type { ValueOf } from '@xo-cash/types';\n\n/**\n * When an entity opts to participate in an invitation, it reserves resources (e.g., UTXOs)\n * that would otherwise be available to other invitations. To prevent resources from remaining\n * locked indefinitely, each reservation requires an expiration time, after which the resources\n * can be released.\n *\n * By default, the expiration time is set to 5 hour.\n */\nexport const DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS = 5 * 60 * 60 * 1000;\n\n/**\n * The default storage backend is IndexedDB.\n */\nexport const DEFAULT_STORAGE_TYPE = StorageType.INDEXEDDB;\n\n/**\n * The default sequence number is 0, which disables relative locktime on the input.\n */\nexport const DEFAULT_SEQUENCE_NUMBER = 0;\n\n/**\n * The default locktime is 0, which means the transaction is valid in any block and has no absolute locktime constraint.\n */\nexport const DEFAULT_LOCKTIME = 0;\n\n/**\n * The default transaction version is 2.\n */\nexport const DEFAULT_VERSION = 2;\n\n/**\n * Empty bytecode used when a token category, NFT commitment, unlocking placeholder, or similar byte field has no value yet.\n */\nexport const EMPTY_BYTECODE = new Uint8Array();\n\n/**\n * An empty unlocking bytecode used as a placeholder for inputs (unlockingBytecode) within an invitation.\n * This placeholder is used when the entities responsible for signing those inputs\n * have not yet provided their signatures for the resulting transaction.\n *\n * Using a placeholder unlocking bytecode enables the engine to construct transaction structures for the\n * libauth compiler when working on template actions, even before all participant signatures are available.\n * This is especially helpful when invitation commits are merged, as it allows the transaction to be built and it's\n * parts can be validated before all unlocking scripts have been provided.\n */\nexport const PLACEHOLDER_UNLOCKING_BYTECODE = EMPTY_BYTECODE;\n\n/**\n * The default electrum application identifier.\n */\nexport const DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER = 'xo';\n\n/**\n * Minimum output value the engine treats as spendable change (BCH dust limit).\n */\nexport const DUST_LIMIT_SATOSHIS = 546;\n\n/**\n * Minimum satoshis on a CashToken bearing output so the token remains standard and spendable.\n */\nexport const TOKEN_BEARING_OUTPUT_MINIMUM_SATOSHIS = 800;\n\n/**\n * Default value of per input fee to help in estimation of the transaction fee.\n */\nexport const DEFAULT_FEE_SATOSHIS_PER_INPUT = 160;\n\n/**\n * Default value of per output fee to help in estimation of the transaction fee.\n */\nexport const DEFAULT_FEE_SATOSHIS_PER_OUTPUT = 120;\n\n/**\n * Zero fungible token amount used when a token bearing output has no amount yet.\n */\nexport const ZERO_FUNGIBLE_TOKEN_AMOUNT = 0n;\n\n/**\n * Sort key used when a merged input or output has no transactionIndex so unordered items follow indexed items.\n */\nexport const UNDEFINED_TRANSACTION_INDEX_SORT_VALUE = Number.MAX_SAFE_INTEGER;\n\n/**\n * Requirement field names on an invitation requirements object.\n * Used to iterate over variables, inputs, and outputs in a consistent order.\n */\nexport const INVITATION_REQUIREMENT_FIELD_NAMES = {\n variables: 'variables',\n inputs: 'inputs',\n outputs: 'outputs',\n} as const;\n\n/**\n * Union of requirement field name strings on an invitation requirements object.\n */\nexport type InvitationRequirementFieldName = ValueOf<typeof INVITATION_REQUIREMENT_FIELD_NAMES>;\n\n/**\n * Requirement field names in iteration order for template and commit requirement scans.\n */\nexport const INVITATION_REQUIREMENT_FIELD_NAME_LIST: readonly InvitationRequirementFieldName[] = [\n INVITATION_REQUIREMENT_FIELD_NAMES.variables,\n INVITATION_REQUIREMENT_FIELD_NAMES.inputs,\n INVITATION_REQUIREMENT_FIELD_NAMES.outputs,\n];\n\n/**\n * Supported networks by the engine.\n */\nexport const XO_SUPPORTED_NETWORKS = {\n mainnet: 'mainnet',\n chipnet: 'chipnet',\n testnet4: 'testnet4',\n} as const;\n\n/**\n * One supported network.\n */\nexport type XONetwork = ValueOf<typeof XO_SUPPORTED_NETWORKS>;\n\n/**\n * Network used when {@link XOEngineOptions.network} is omitted.\n */\nexport const DEFAULT_XO_NETWORK: XONetwork = XO_SUPPORTED_NETWORKS.mainnet;\n\n/**\n * Base database name matching {@link State} when databaseFilename is omitted.\n */\nexport const DEFAULT_ACCOUNT_DATABASE_FILENAME = 'XO';\n\n/**\n * Name that sets the Electrum cache database apart from the account database.\n */\nexport const DEFAULT_ELECTRUM_CACHE_DATABASE_FILENAME = 'Electrum';\n","import type { HdKeyNetwork } from '@bitauth/libauth';\nimport {\n chipnetServersWithBlockchain,\n mainnetServersWithBlockchain,\n testnet4ServersWithBlockchain,\n type ElectrumServersWithBlockchain,\n} from '@electrum-cash/servers';\nimport { computeAccountHash } from '@xo-cash/crypto';\nimport { DEFAULT_ACCOUNT_DATABASE_FILENAME, DEFAULT_ELECTRUM_CACHE_DATABASE_FILENAME, XO_SUPPORTED_NETWORKS, type XONetwork } from '../defaults.ts';\n\n/**\n * Returns true when the value is a supported network.\n *\n * @param {string} value - Network name to test.\n * @returns {boolean} - Whether the value is a supported {@link XONetwork}.\n */\nexport const isXOSupportedNetwork = (value: string): value is XONetwork => {\n return value === XO_SUPPORTED_NETWORKS.mainnet || value === XO_SUPPORTED_NETWORKS.chipnet || value === XO_SUPPORTED_NETWORKS.testnet4;\n};\n\n/**\n * Maps an engine network to the libauth HD key network used for the purpose path and xpub or tpub encoding.\n *\n * Libauth {@link HdKeyNetwork} is only `mainnet` or `testnet`. Chipnet and testnet4 are not members of that type, so both use `testnet`.\n *\n * @param {XONetwork} network - Engine network.\n * @returns {HdKeyNetwork} - Mainnet encoding, or testnet encoding for chipnet and testnet4.\n */\nexport const resolveHdKeyNetwork = (network: XONetwork): HdKeyNetwork => {\n if (network === XO_SUPPORTED_NETWORKS.mainnet) {\n return 'mainnet';\n }\n\n // Chipnet and testnet4 are not HdKeyNetwork values, so they share the testnet purpose path and tpub encoding.\n return 'testnet';\n};\n\n/**\n * Resolves default Electrum hosts for a network.\n *\n * Each host carries the blockchain checkpoint and consensus parameters of that network.\n *\n * @param {XONetwork} network - Engine network.\n * @returns {ElectrumServersWithBlockchain} - Server list for that network.\n */\nexport const resolveElectrumServersForNetwork = (network: XONetwork): ElectrumServersWithBlockchain => {\n if (network === XO_SUPPORTED_NETWORKS.chipnet) {\n return chipnetServersWithBlockchain;\n }\n\n if (network === XO_SUPPORTED_NETWORKS.testnet4) {\n return testnet4ServersWithBlockchain;\n }\n\n // Mainnet keeps the published @electrum-cash/servers list.\n return mainnetServersWithBlockchain;\n};\n\n/**\n * Builds the database filename for a network.\n *\n * Every network appends the network name to the provided database filename, or to `XO` when none is provided.\n *\n * @param {XONetwork} network - Engine network.\n * @param {string} [databaseFilename] - Optional name included before the network name.\n * @returns {string} - Database filename for the network.\n */\nexport const buildNetworkDatabaseFilename = (network: XONetwork, databaseFilename?: string): string => {\n return `${databaseFilename ?? DEFAULT_ACCOUNT_DATABASE_FILENAME}-${network}`;\n};\n\n/**\n * Builds the database name used for one mnemonic on one network.\n *\n * @param {string} mnemonic - BIP39 mnemonic for the account.\n * @param {XONetwork} network - Engine network.\n * @param {string} [databaseFilename] - Optional name that already replaces `XO`.\n * @returns {string} - Full database name including account hash.\n */\nexport const buildAccountDatabaseName = (mnemonic: string, network: XONetwork, databaseFilename?: string): string => {\n const networkDatabaseFilename = buildNetworkDatabaseFilename(network, databaseFilename);\n const accountHash = computeAccountHash(mnemonic);\n\n return `${networkDatabaseFilename}-${accountHash}`;\n};\n\n/**\n * Builds the Electrum cache database filename for one account on one network.\n *\n * The name always includes `Electrum`, so it never matches the account database name built from the same database filename.\n *\n * @param {XONetwork} network - Engine network.\n * @param {string} accountHash - Account hash for this mnemonic.\n * @param {string} [databaseFilename] - Optional name included before `Electrum`.\n * @returns {string} - Cache database filename.\n */\nexport const buildElectrumCacheDatabaseFilename = (network: XONetwork, accountHash: string, databaseFilename?: string): string => {\n const electrumCacheDatabaseFilename = `${DEFAULT_ELECTRUM_CACHE_DATABASE_FILENAME}-${network}-${accountHash}`;\n\n // A provided database filename is kept in front so every database of this engine shares that name.\n if (databaseFilename !== undefined) {\n return `${databaseFilename}-${electrumCacheDatabaseFilename}`;\n }\n\n return electrumCacheDatabaseFilename;\n};\n","/* eslint-disable max-classes-per-file */\n\nimport type {\n XOTemplateActionIdentifier,\n XOTemplateIdentifier,\n XOTemplateLockingScriptIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateTransactionIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport type { WalletDefaultPolicies } from '../interfaces.ts';\n\n/**\n * Thrown when an action identifier is absent from the template.\n *\n * @group Errors\n */\nexport class TemplateActionNotFoundError extends Error {\n /**\n * Template whose action is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Action identifier that is missing.\n */\n readonly actionIdentifier: XOTemplateActionIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, actionIdentifier: XOTemplateActionIdentifier) {\n const defaultMessage = `Action \"${actionIdentifier}\" not found in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateActionNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n }\n}\n\n/**\n * Thrown when an output identifier is absent from the template.\n *\n * @group Errors\n */\nexport class TemplateOutputNotFoundError extends Error {\n /**\n * Template whose output is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output identifier that is missing.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage = `Output \"${outputIdentifier}\" not found in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateOutputNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when a locking script identifier is absent from the template.\n *\n * @group Errors\n */\nexport class TemplateLockingScriptNotFoundError extends Error {\n /**\n * Template whose locking script is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script identifier that is missing.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, lockingScriptIdentifier: XOTemplateLockingScriptIdentifier) {\n const defaultMessage = `Locking script \"${lockingScriptIdentifier}\" not found in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateLockingScriptNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n }\n}\n\n/**\n * Thrown when the template defines no unlocking script for a locking script.\n *\n * @group Errors\n */\nexport class TemplateUnlockingScriptNotFoundError extends Error {\n /**\n * Template whose unlocking script is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that has no unlocking script.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, lockingScriptIdentifier: XOTemplateLockingScriptIdentifier) {\n const defaultMessage = `Unlocking script not found for locking script \"${lockingScriptIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateUnlockingScriptNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n }\n}\n\n/**\n * Thrown when a transaction identifier is absent from the template.\n *\n * @group Errors\n */\nexport class TemplateTransactionNotFoundError extends Error {\n /**\n * Template whose transaction is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Transaction identifier that is missing.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, transactionIdentifier: XOTemplateTransactionIdentifier) {\n const defaultMessage = `Transaction \"${transactionIdentifier}\" not found in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateTransactionNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Thrown when a template action names no transaction.\n *\n * @group Errors\n */\nexport class TemplateActionTransactionNotFoundError extends Error {\n /**\n * Template that defines the action.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Action identifier whose transaction is missing.\n */\n readonly actionIdentifier: XOTemplateActionIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, actionIdentifier: XOTemplateActionIdentifier) {\n const defaultMessage = `Transaction not found on action \"${actionIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateActionTransactionNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n }\n}\n\n/**\n * Thrown when a template output has no locking script.\n *\n * @group Errors\n */\nexport class TemplateOutputLockingScriptNotFoundError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output identifier whose locking script is missing.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage = `Locking script not found on output \"${outputIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateOutputLockingScriptNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when a locking script role identifier is absent from the template.\n *\n * @group Errors\n */\nexport class TemplateLockingScriptRoleNotFoundError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script identifier that was searched.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Role identifier that is missing.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier;\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n roleIdentifier: XOTemplateRoleIdentifier,\n ) {\n const defaultMessage = `Role \"${roleIdentifier}\" not found on locking script \"${lockingScriptIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateLockingScriptRoleNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.roleIdentifier = roleIdentifier;\n }\n}\n\n/**\n * Thrown when a role sets `relevant` to CashAssembly that the engine cannot evaluate yet.\n *\n * @group Errors\n */\nexport class TemplateRoleRelevantCashAssemblyUnsupportedError extends Error {\n /**\n * Template that defines the role.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output whose role declared the unsupported expression.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n /**\n * Role whose `relevant` field is a CashAssembly string.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier;\n\n /**\n * CashAssembly expression from the role `relevant` field.\n */\n readonly relevantExpression: string;\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier: XOTemplateRoleIdentifier,\n relevantExpression: string,\n ) {\n const defaultMessage =\n `Role \"${roleIdentifier}\" relevant CashAssembly unsupported on output \"${outputIdentifier}\" in template: ${templateIdentifier}, `\n + `relevantExpression \"${relevantExpression}\"`;\n super(defaultMessage);\n this.name = 'TemplateRoleRelevantCashAssemblyUnsupportedError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n this.roleIdentifier = roleIdentifier;\n this.relevantExpression = relevantExpression;\n }\n}\n\n/**\n * Thrown when a template output token omits a category.\n *\n * @group Errors\n */\nexport class TemplateTokenCategoryMissingError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output whose token omits the category.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage = `Token category missing on output \"${outputIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateTokenCategoryMissingError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when a template output NFT omits capability.\n *\n * @group Errors\n */\nexport class TemplateTokenNftCapabilityMissingError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output whose NFT omits the capability.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage = `Token NFT capability missing on output \"${outputIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateTokenNftCapabilityMissingError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when a template output NFT capability is not recognized.\n *\n * @group Errors\n */\nexport class TemplateTokenNftCapabilityInvalidError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output whose NFT capability was rejected.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n /**\n * Capability value that was rejected.\n */\n readonly capabilityValue: string;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier, capabilityValue: string) {\n const defaultMessage =\n `Token NFT capability invalid on output \"${outputIdentifier}\" in template: ${templateIdentifier}, `\n + `expected \"none\", \"mutable\", or \"minting\", got \"${capabilityValue}\"`;\n super(defaultMessage);\n this.name = 'TemplateTokenNftCapabilityInvalidError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n this.capabilityValue = capabilityValue;\n }\n}\n\n/**\n * Thrown when a template output `valueSatoshis` string is neither CashAssembly nor a decimal integer.\n *\n * @group Errors\n */\nexport class TemplateValueSatoshisInvalidError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output identifier whose valueSatoshis could not be resolved.\n */\n readonly outputIdentifier: string;\n\n /**\n * Passed valueSatoshis string.\n */\n readonly templateValueSatoshis: string;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: string, templateValueSatoshis: string, options?: { cause?: unknown }) {\n const defaultMessage =\n `Value satoshis invalid on output \"${outputIdentifier}\" in template: ${templateIdentifier}, `\n + 'expected a CashAssembly expression or a non negative decimal integer, '\n + `got \"${templateValueSatoshis}\"`;\n\n super(defaultMessage, options);\n\n this.name = 'TemplateValueSatoshisInvalidError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n this.templateValueSatoshis = templateValueSatoshis;\n }\n}\n\n/**\n * Thrown when a template output token amount does not resolve to a valid fungible token amount.\n *\n * @group Errors\n */\nexport class TemplateTokenAmountInvalidError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Output identifier whose token amount could not be resolved.\n */\n readonly outputIdentifier: string;\n\n /**\n * Template amount, or the value its CashAssembly expression evaluated to.\n */\n readonly tokenAmount: string;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: string, tokenAmount: string) {\n const defaultMessage =\n `Token amount invalid on output \"${outputIdentifier}\" in template: ${templateIdentifier}, `\n + `expected a non negative decimal integer within the fungible token range, got \"${tokenAmount}\"`;\n super(defaultMessage);\n this.name = 'TemplateTokenAmountInvalidError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n this.tokenAmount = tokenAmount;\n }\n}\n\n/**\n * Thrown when a role is not defined on the template action an entity tries to take.\n *\n * @group Errors\n */\nexport class TemplateActionRoleNotFoundError extends Error {\n /**\n * Template that defines the action.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Action whose role is missing.\n */\n readonly actionIdentifier: XOTemplateActionIdentifier;\n\n /**\n * Role that is missing.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, actionIdentifier: XOTemplateActionIdentifier, roleIdentifier: XOTemplateRoleIdentifier) {\n const defaultMessage = `Role \"${roleIdentifier}\" not found on action \"${actionIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateActionRoleNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n this.roleIdentifier = roleIdentifier;\n }\n}\n\n/**\n * Thrown when a template action role asks the engine to generate variables that are not private keys.\n *\n * @group Errors\n */\nexport class TemplateGeneratedVariableTypeUnsupportedError extends Error {\n /**\n * Template that defines the variables.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Action the variables are generated for.\n */\n readonly actionIdentifier: XOTemplateActionIdentifier;\n\n /**\n * Role the entity takes in the action, when it takes one.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier | undefined;\n\n /**\n * Generated variables that are not defined as private keys.\n */\n readonly variableIdentifiers: XOTemplateVariableIdentifier[];\n\n /**\n * Defined type of each of those variables, undefined when the template does not define the variable.\n */\n readonly variableTypes: Array<string | undefined>;\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n actionIdentifier: XOTemplateActionIdentifier,\n variableIdentifiers: XOTemplateVariableIdentifier[],\n variableTypes: Array<string | undefined>,\n roleIdentifier?: XOTemplateRoleIdentifier,\n ) {\n const declaredTypes = variableTypes.map((variableType) => variableType ?? 'undeclared');\n const roleDescription = roleIdentifier === undefined ? '' : ` role \"${roleIdentifier}\"`;\n const defaultMessage =\n `Variables ${JSON.stringify(variableIdentifiers)} to generate for action \"${actionIdentifier}\"${roleDescription} `\n + `not private keys in template: ${templateIdentifier}, expected type \"private_key\", got ${JSON.stringify(declaredTypes)}`;\n super(defaultMessage);\n this.name = 'TemplateGeneratedVariableTypeUnsupportedError';\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n this.roleIdentifier = roleIdentifier;\n this.variableIdentifiers = variableIdentifiers;\n this.variableTypes = variableTypes;\n }\n}\n\n/**\n * Thrown when a wallet default policy names a template whose defaults do not define that policy.\n *\n * @group Errors\n */\nexport class TemplateDefaultPolicyMissingError extends Error {\n /**\n * Template whose default policy is missing.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Default policy that is missing.\n */\n readonly policy: keyof WalletDefaultPolicies;\n\n constructor(templateIdentifier: XOTemplateIdentifier, policy: keyof WalletDefaultPolicies) {\n const defaultMessage = `Default ${policy} policy missing from template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateDefaultPolicyMissingError';\n this.templateIdentifier = templateIdentifier;\n this.policy = policy;\n }\n}\n\n/**\n * Thrown when a template locking script omits its locking type.\n *\n * @group Errors\n */\nexport class TemplateLockingScriptTypeNotFoundError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that has no locking type.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, lockingScriptIdentifier: XOTemplateLockingScriptIdentifier) {\n const defaultMessage = `Locking type not found on locking script \"${lockingScriptIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateLockingScriptTypeNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n }\n}\n\n/**\n * Thrown when a template locking script omits its locking bytecode.\n *\n * @group Errors\n */\nexport class TemplateLockingScriptBytecodeNotFoundError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that has no locking bytecode.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n constructor(templateIdentifier: XOTemplateIdentifier, lockingScriptIdentifier: XOTemplateLockingScriptIdentifier) {\n const defaultMessage = `Locking bytecode not found on locking script \"${lockingScriptIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateLockingScriptBytecodeNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n }\n}\n\n/**\n * Thrown when a template output names a locking script, or a locking script names a script, that the template does not define.\n *\n * @group Errors\n */\nexport class TemplateOutputLockingScriptReferenceInvalidError extends Error {\n /**\n * Template that defines the output.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Template output whose locking script definition holds the reference.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n /**\n * Locking script or script identifier the template does not define.\n */\n readonly lockingScriptReference: string;\n\n constructor(templateIdentifier: XOTemplateIdentifier, outputIdentifier: XOTemplateOutputIdentifier, lockingScriptReference: string) {\n const defaultMessage = `Locking script reference \"${lockingScriptReference}\" invalid on output \"${outputIdentifier}\" in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'TemplateOutputLockingScriptReferenceInvalidError';\n this.templateIdentifier = templateIdentifier;\n this.outputIdentifier = outputIdentifier;\n this.lockingScriptReference = lockingScriptReference;\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type {\n XOInvitationCommitIdentifier,\n XOInvitationEntityIdentifier,\n XOInvitationIdentifier,\n XOInvitationResolutionIdentifier,\n XOTemplateDataIdentifier,\n XOTemplateIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateTransactionIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\n\n/**\n * One field that a later commit tried to set after an earlier commit already committed a value for it.\n */\nexport type InvitationItemFieldConflict = {\n\n /**\n * Whether the conflicting field belongs to an input or an output.\n */\n itemType: 'input' | 'output';\n\n /**\n * Name of the conflicting field.\n */\n fieldName: string;\n\n /**\n * Commit identifier and position of the funding item that introduced the input or output.\n */\n fundingItemKey: string;\n\n /**\n * Commit that set the field first.\n */\n earlierCommitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Commit that tried to set the field again.\n */\n laterCommitIdentifier: XOInvitationCommitIdentifier;\n};\n\n/**\n * One variable a commit provides for roles its entity does not hold.\n */\nexport type RoleVariableEntityMismatch = {\n\n /**\n * Commit that provides the variable.\n */\n commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Entity that made the commit.\n */\n entityIdentifier: XOInvitationEntityIdentifier;\n\n /**\n * Variable the commit provides.\n */\n variableIdentifier: XOTemplateVariableIdentifier;\n\n /**\n * Roles the variable belongs to, each taken by other entities.\n */\n roleIdentifiers: XOTemplateRoleIdentifier[];\n};\n\n/**\n * One entity that holds more than one role with a follow up in an invitation.\n */\nexport type EntityRolesMultipleEntry = {\n\n /**\n * Entity that takes the roles.\n */\n entityIdentifier: XOInvitationEntityIdentifier;\n\n /**\n * Every role with a follow up the entity holds, in the order its commits take them.\n */\n roleIdentifiers: XOTemplateRoleIdentifier[];\n};\n\n/**\n * Thrown when no commit in the invitation introduced a merged input, so there is no commit for a new commit to extend.\n *\n * @group Errors\n */\nexport class MergedInputCommitNotFoundError extends Error {\n /**\n * Invitation whose commits were searched.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Position of the input in the merged input list.\n */\n readonly inputIndex: number;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, inputIndex: number) {\n const defaultMessage =\n `Commit not found for merged input ${String(inputIndex)} in invitation \"${invitationIdentifier}\", `\n + 'expected a commit that introduced the input';\n super(defaultMessage);\n this.name = 'MergedInputCommitNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n }\n}\n\n/**\n * Thrown when an updated invitation diverges from the commit history already stored locally.\n *\n * @group Errors\n */\nexport class InvitationHistoryConflictError extends Error {\n /**\n * Invitation whose stored and updated histories diverge.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Stored commit at which the histories diverged.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, commitIdentifier: XOInvitationCommitIdentifier) {\n const defaultMessage =\n `Invitation \"${invitationIdentifier}\" history conflict at stored commit \"${commitIdentifier}\", `\n + 'expected the updated invitation to keep every stored commit in its stored position';\n super(defaultMessage);\n this.name = 'InvitationHistoryConflictError';\n this.invitationIdentifier = invitationIdentifier;\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Thrown when append invitation parameters omit every appendable field.\n *\n * @group Errors\n */\nexport class AppendInvitationParametersEmptyError extends Error {\n constructor() {\n const defaultMessage =\n 'Append invitation parameters empty: expected at least one of version, locktime, inputs, outputs, variables, or expiresAtTimestamp';\n super(defaultMessage);\n this.name = 'AppendInvitationParametersEmptyError';\n }\n}\n\n/**\n * Thrown when one or more invitation validation checks fail.\n * Holds one error for each failed check, in the order the checks ran.\n *\n * @group Errors\n */\nexport class InvitationValidationFailedError extends AggregateError {\n /**\n * Invitation that failed validation.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Validation errors collected before the throw.\n */\n declare readonly errors: Error[];\n\n constructor(invitationIdentifier: XOInvitationIdentifier, errors: Error[]) {\n let defaultMessage = `Invitation \"${invitationIdentifier}\" validation failed`;\n if (errors.length > 0) {\n defaultMessage = `${defaultMessage}: issues [${errors.map((issue) => issue.message).join(', ')}]`;\n }\n\n super(errors, defaultMessage);\n this.name = 'InvitationValidationFailedError';\n this.invitationIdentifier = invitationIdentifier;\n }\n}\n\n/**\n * Collected during invitation validation when an invitation field does not construct a valid primitive.\n *\n * @group Errors\n */\nexport class InvitationFieldInvalidError extends Error {\n /**\n * Location of the field inside the invitation, as object keys and array indexes.\n */\n readonly path: readonly (string | number)[];\n\n /**\n * Error thrown by the primitive that rejected the field value.\n */\n declare readonly cause: Error;\n\n constructor(path: readonly (string | number)[], cause: Error) {\n const defaultMessage = `Invitation field invalid at ${path.join('.')}: ${cause.message}`;\n super(defaultMessage, { cause });\n this.name = 'InvitationFieldInvalidError';\n this.path = path;\n }\n}\n\n/**\n * Collected during invitation validation when a commit signature does not verify or verification throws.\n *\n * @group Errors\n */\nexport class CommitSignatureInvalidError extends Error {\n /**\n * Identifier of the commit whose signature failed.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Error thrown by signature verification, when verification threw.\n */\n declare readonly cause?: Error;\n\n constructor(commitIdentifier: XOInvitationCommitIdentifier, cause?: Error) {\n const defaultMessage = `Commit signature invalid: commitIdentifier \"${commitIdentifier}\"`;\n if (cause === undefined) {\n super(defaultMessage);\n } else {\n super(defaultMessage, { cause });\n }\n\n this.name = 'CommitSignatureInvalidError';\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Collected during invitation validation when a transaction result created signature does not verify or verification throws.\n *\n * @group Errors\n */\nexport class TransactionCreatedSignatureInvalidError extends Error {\n /**\n * Template transaction identifier of the result whose signature failed.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n /**\n * Error thrown by signature verification, when verification threw.\n */\n declare readonly cause?: Error;\n\n constructor(transactionIdentifier: XOTemplateTransactionIdentifier, cause?: Error) {\n const defaultMessage = `Transaction created signature invalid: transactionIdentifier \"${transactionIdentifier}\"`;\n if (cause === undefined) {\n super(defaultMessage);\n } else {\n super(defaultMessage, { cause });\n }\n\n this.name = 'TransactionCreatedSignatureInvalidError';\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Collected during invitation validation when a transaction result broadcast signature does not verify or verification throws.\n *\n * @group Errors\n */\nexport class TransactionBroadcastSignatureInvalidError extends Error {\n /**\n * Template transaction identifier of the result whose signature failed.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n /**\n * Error thrown by signature verification, when verification threw.\n */\n declare readonly cause?: Error;\n\n constructor(transactionIdentifier: XOTemplateTransactionIdentifier, cause?: Error) {\n const defaultMessage = `Transaction broadcast signature invalid: transactionIdentifier \"${transactionIdentifier}\"`;\n if (cause === undefined) {\n super(defaultMessage);\n } else {\n super(defaultMessage, { cause });\n }\n\n this.name = 'TransactionBroadcastSignatureInvalidError';\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Collected during invitation validation when a transaction result has some but not all broadcast fields.\n *\n * @group Errors\n */\nexport class TransactionBroadcastMetadataIncompleteError extends Error {\n /**\n * Template transaction identifier of the result with incomplete broadcast fields.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n constructor(transactionIdentifier: XOTemplateTransactionIdentifier) {\n const defaultMessage = `Transaction broadcast metadata incomplete: transactionIdentifier \"${transactionIdentifier}\"`;\n super(defaultMessage);\n this.name = 'TransactionBroadcastMetadataIncompleteError';\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Collected during invitation validation when a data result signature does not verify or verification throws.\n *\n * @group Errors\n */\nexport class DataResultSignatureInvalidError extends Error {\n /**\n * Template data identifier of the result whose signature failed.\n */\n readonly dataIdentifier: XOTemplateDataIdentifier;\n\n /**\n * Error thrown by signature verification, when verification threw.\n */\n declare readonly cause?: Error;\n\n constructor(dataIdentifier: XOTemplateDataIdentifier, cause?: Error) {\n const defaultMessage = `Data result signature invalid: dataIdentifier \"${dataIdentifier}\"`;\n if (cause === undefined) {\n super(defaultMessage);\n } else {\n super(defaultMessage, { cause });\n }\n\n this.name = 'DataResultSignatureInvalidError';\n this.dataIdentifier = dataIdentifier;\n }\n}\n\n/**\n * Thrown when the root commit for an entity cannot be found in the invitation.\n *\n * @group Errors\n */\nexport class RootCommitNotFoundError extends Error {\n /**\n * Invitation identifier that was searched.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Entity whose root commit was searched.\n */\n readonly entityIdentifier: XOInvitationEntityIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, entityIdentifier: XOInvitationEntityIdentifier) {\n const defaultMessage =\n `Root commit not found for entity \"${entityIdentifier}\" in invitation: invitationIdentifier \"${invitationIdentifier}\". `\n + 'This happens when the invitation has not been accepted, or it was accepted but the updated invitation was not stored';\n super(defaultMessage);\n this.name = 'RootCommitNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.entityIdentifier = entityIdentifier;\n }\n}\n\n/**\n * Thrown when a parent commit identifier is absent from the invitation.\n *\n * @group Errors\n */\nexport class ParentCommitNotFoundError extends Error {\n /**\n * Parent commit identifier that was looked up.\n */\n readonly parentCommitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Commit that referenced the missing parent.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(parentCommitIdentifier: XOInvitationCommitIdentifier, commitIdentifier: XOInvitationCommitIdentifier) {\n const defaultMessage = `Parent commit not found in invitation: parentCommitIdentifier \"${parentCommitIdentifier}\", referenced by commit \"${commitIdentifier}\"`;\n super(defaultMessage);\n this.name = 'ParentCommitNotFoundError';\n this.parentCommitIdentifier = parentCommitIdentifier;\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Thrown when two or more merged inputs or outputs share the same transactionIndex.\n *\n * @group Errors\n */\nexport class TransactionIndexDuplicatedError extends Error {\n /**\n * Whether the conflict is among inputs or outputs.\n */\n readonly itemType: 'input' | 'output';\n\n /**\n * Groups of merged array positions that share one transactionIndex.\n */\n readonly duplicateGroups: Array<{ transactionIndex: number; itemPositions: number[] }>;\n\n constructor(itemType: 'input' | 'output', duplicateGroups: Array<{ transactionIndex: number; itemPositions: number[] }>) {\n const itemLabel = itemType === 'input' ? 'Input' : 'Output';\n const groupMessages = duplicateGroups.map((duplicateGroup) => {\n const itemLabels = duplicateGroup.itemPositions.map((itemPosition) => `${itemLabel} at merge position ${String(itemPosition + 1)}`);\n let joinedItemLabels: string;\n\n if (itemLabels.length === 2) {\n joinedItemLabels = `${itemLabels[0]} and ${itemLabels[1]}`;\n } else {\n const leadingItemLabels = itemLabels.slice(0, -1).join(', ');\n const lastItemLabel = itemLabels[itemLabels.length - 1];\n joinedItemLabels = `${leadingItemLabels}, and ${lastItemLabel}`;\n }\n\n return `${joinedItemLabels} share transactionIndex ${String(duplicateGroup.transactionIndex)}`;\n });\n\n const defaultMessage = `Transaction index duplicated in merged ${itemType}s: ${groupMessages.join(' ')}`;\n super(defaultMessage);\n this.name = 'TransactionIndexDuplicatedError';\n this.itemType = itemType;\n this.duplicateGroups = duplicateGroups;\n }\n}\n\n/**\n * Thrown when a mergesWith commit identifier is absent from the invitation.\n *\n * @group Errors\n */\nexport class MergesWithCommitNotFoundError extends Error {\n /**\n * Invitation whose commits were searched.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Commit identifier that mergesWith pointed at.\n */\n readonly mergesWithCommitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Commit that referenced the missing mergesWith commit, undefined when that commit is still being built.\n */\n readonly currentCommitIdentifier: XOInvitationCommitIdentifier | undefined;\n\n constructor(\n invitationIdentifier: XOInvitationIdentifier,\n mergesWithCommitIdentifier: XOInvitationCommitIdentifier,\n currentCommitIdentifier?: XOInvitationCommitIdentifier,\n ) {\n let referenceDetail = '';\n if (currentCommitIdentifier !== undefined) {\n referenceDetail = `, referenced by commit \"${currentCommitIdentifier}\"`;\n }\n\n const defaultMessage = `Merges with commit \"${mergesWithCommitIdentifier}\" not found in invitation \"${invitationIdentifier}\"${referenceDetail}`;\n super(defaultMessage);\n this.name = 'MergesWithCommitNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.mergesWithCommitIdentifier = mergesWithCommitIdentifier;\n this.currentCommitIdentifier = currentCommitIdentifier;\n }\n}\n\n/**\n * Thrown when an input or output at a given index is absent from a commit.\n *\n * @group Errors\n */\nexport class CommitItemNotFoundError extends Error {\n /**\n * Whether the missing item is an input or an output.\n */\n readonly itemType: 'input' | 'output';\n\n /**\n * Index that was looked up in the commit.\n */\n readonly itemIndex: number;\n\n /**\n * Commit that was searched.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(itemType: 'input' | 'output', itemIndex: number, commitIdentifier: XOInvitationCommitIdentifier) {\n const itemLabel = itemType === 'input' ? 'Input' : 'Output';\n const defaultMessage = `${itemLabel} not found in commit: itemIndex ${String(itemIndex)}, commitIdentifier \"${commitIdentifier}\"`;\n super(defaultMessage);\n this.name = 'CommitItemNotFoundError';\n this.itemType = itemType;\n this.itemIndex = itemIndex;\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Thrown when transaction version is defined in more than one commit.\n *\n * @group Errors\n */\nexport class TransactionVersionDuplicatedError extends Error {\n /**\n * Commit identifiers that each defined transaction version.\n */\n readonly commitIdentifiers: XOInvitationCommitIdentifier[];\n\n constructor(commitIdentifiers: XOInvitationCommitIdentifier[]) {\n const defaultMessage = `Transaction version duplicated in commits ${JSON.stringify(commitIdentifiers)}, expected one commit to set it`;\n super(defaultMessage);\n this.name = 'TransactionVersionDuplicatedError';\n this.commitIdentifiers = commitIdentifiers;\n }\n}\n\n/**\n * Thrown when transaction locktime is defined in more than one commit.\n *\n * @group Errors\n */\nexport class TransactionLocktimeDuplicatedError extends Error {\n /**\n * Commit identifiers that each defined transaction locktime.\n */\n readonly commitIdentifiers: XOInvitationCommitIdentifier[];\n\n constructor(commitIdentifiers: XOInvitationCommitIdentifier[]) {\n const defaultMessage = `Transaction locktime duplicated in commits ${JSON.stringify(commitIdentifiers)}, expected one commit to set it`;\n super(defaultMessage);\n this.name = 'TransactionLocktimeDuplicatedError';\n this.commitIdentifiers = commitIdentifiers;\n }\n}\n\n/**\n * Thrown when a provided template identifier does not match the invitation template identifier.\n *\n * @group Errors\n */\nexport class InvitationTemplateMismatchError extends Error {\n /**\n * Template identifier stored on the invitation.\n */\n readonly expectedTemplateIdentifier: XOTemplateIdentifier;\n\n /**\n * Template identifier that was supplied for validation.\n */\n readonly receivedTemplateIdentifier: XOTemplateIdentifier;\n\n constructor(expectedTemplateIdentifier: XOTemplateIdentifier, receivedTemplateIdentifier: XOTemplateIdentifier) {\n const defaultMessage = `Invitation template mismatch: expected \"${expectedTemplateIdentifier}\", got \"${receivedTemplateIdentifier}\"`;\n super(defaultMessage);\n this.name = 'InvitationTemplateMismatchError';\n this.expectedTemplateIdentifier = expectedTemplateIdentifier;\n this.receivedTemplateIdentifier = receivedTemplateIdentifier;\n }\n}\n\n/**\n * Thrown when a merged input to unlock has no outpoint, so there is no output for it to spend.\n *\n * @group Errors\n */\nexport class MergedInputOutpointMissingError extends Error {\n /**\n * Invitation that owns the input.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Position of the input in the merged input list.\n */\n readonly inputIndex: number;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, inputIndex: number) {\n const defaultMessage =\n `Outpoint missing on merged input ${String(inputIndex)} in invitation \"${invitationIdentifier}\", `\n + 'expected an outpoint transaction hash and index';\n super(defaultMessage);\n this.name = 'MergedInputOutpointMissingError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n }\n}\n\n/**\n * Thrown when the output a merged input spends is not tracked by this account, or is reserved by another invitation.\n *\n * @group Errors\n */\nexport class InputUnspentOutputUnavailableError extends Error {\n /**\n * Invitation that owns the input.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Position of the input in the merged input list.\n */\n readonly inputIndex: number;\n\n /**\n * Hash of the transaction that holds the spent output, as hexadecimal.\n */\n readonly outpointTransactionHash: string;\n\n /**\n * Index of the spent output in that transaction.\n */\n readonly outpointIndex: number;\n\n /**\n * Invitation that reserves the output, undefined when this account does not track the output.\n */\n readonly reservedBy: XOInvitationIdentifier | undefined;\n\n constructor(\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n outpointTransactionHash: string,\n outpointIndex: number,\n reservedBy?: XOInvitationIdentifier,\n ) {\n let unavailableReason = 'not tracked by this account';\n if (reservedBy !== undefined) {\n unavailableReason = `reserved by invitation \"${reservedBy}\"`;\n }\n\n const defaultMessage =\n `Unspent output ${outpointTransactionHash}:${String(outpointIndex)} of merged input ${String(inputIndex)} `\n + `in invitation \"${invitationIdentifier}\" ${unavailableReason}, expected an output this account tracks that is free or reserved by this invitation`;\n super(defaultMessage);\n this.name = 'InputUnspentOutputUnavailableError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n this.outpointTransactionHash = outpointTransactionHash;\n this.outpointIndex = outpointIndex;\n this.reservedBy = reservedBy;\n }\n}\n\n/**\n * Thrown when an invitation result signature fails verification.\n *\n * @group Errors\n */\nexport class InvitationResultSignatureInvalidError extends Error {\n /**\n * Invitation whose result signature failed.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Kind of invitation result that was verified.\n */\n readonly resultKind: 'transaction_created' | 'transaction_broadcasted' | 'data';\n\n /**\n * Result identifier whose signature failed.\n */\n readonly resultIdentifier: string;\n\n constructor(\n invitationIdentifier: XOInvitationIdentifier,\n resultKind: 'transaction_created' | 'transaction_broadcasted' | 'data',\n resultIdentifier: string,\n ) {\n const defaultMessage =\n `Invitation result signature invalid: invitationIdentifier \"${invitationIdentifier}\", resultKind \"${resultKind}\", `\n + `resultIdentifier \"${resultIdentifier}\"`;\n super(defaultMessage);\n this.name = 'InvitationResultSignatureInvalidError';\n this.invitationIdentifier = invitationIdentifier;\n this.resultKind = resultKind;\n this.resultIdentifier = resultIdentifier;\n }\n}\n\n/**\n * Thrown when the same commit identifier appears more than once in an invitation.\n *\n * @group Errors\n */\nexport class CommitIdentifierDuplicatedError extends Error {\n /**\n * Commit identifiers that appear more than once.\n */\n readonly commitIdentifiers: XOInvitationCommitIdentifier[];\n\n constructor(commitIdentifiers: XOInvitationCommitIdentifier[]) {\n const defaultMessage = `Commits ${JSON.stringify(commitIdentifiers)} duplicated in invitation, expected each commit identifier once`;\n super(defaultMessage);\n this.name = 'CommitIdentifierDuplicatedError';\n this.commitIdentifiers = commitIdentifiers;\n }\n}\n\n/**\n * Thrown when a commit does not name the commit stored immediately before it as its previous commit.\n *\n * @group Errors\n */\nexport class CommitChainOrderInvalidError extends Error {\n /**\n * Commit whose previous commit identifier breaks the chain.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Identifier of the commit stored immediately before it, or undefined for the first commit.\n */\n readonly expectedPreviousCommitIdentifier: XOInvitationCommitIdentifier | undefined;\n\n /**\n * Previous commit identifier the commit actually carries.\n */\n readonly receivedPreviousCommitIdentifier: XOInvitationCommitIdentifier | undefined;\n\n constructor(\n commitIdentifier: XOInvitationCommitIdentifier,\n expectedPreviousCommitIdentifier?: XOInvitationCommitIdentifier,\n receivedPreviousCommitIdentifier?: XOInvitationCommitIdentifier,\n ) {\n const defaultMessage =\n `Commit \"${commitIdentifier}\" chain order invalid in invitation, `\n + `expected previous commit \"${String(expectedPreviousCommitIdentifier)}\", got \"${String(receivedPreviousCommitIdentifier)}\"`;\n super(defaultMessage);\n this.name = 'CommitChainOrderInvalidError';\n this.commitIdentifier = commitIdentifier;\n this.expectedPreviousCommitIdentifier = expectedPreviousCommitIdentifier;\n this.receivedPreviousCommitIdentifier = receivedPreviousCommitIdentifier;\n }\n}\n\n/**\n * Thrown when a mergesWith reference points at the same commit or a later commit instead of an earlier one.\n *\n * @group Errors\n */\nexport class MergesWithCommitNotEarlierError extends Error {\n /**\n * Commit identifier that mergesWith pointed at.\n */\n readonly mergesWithCommitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Commit that contains the mergesWith reference.\n */\n readonly currentCommitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(mergesWithCommitIdentifier: XOInvitationCommitIdentifier, currentCommitIdentifier: XOInvitationCommitIdentifier) {\n const defaultMessage =\n `Merges with commit \"${mergesWithCommitIdentifier}\" not earlier than commit \"${currentCommitIdentifier}\", `\n + 'expected a commit stored before the one that extends it';\n super(defaultMessage);\n this.name = 'MergesWithCommitNotEarlierError';\n this.mergesWithCommitIdentifier = mergesWithCommitIdentifier;\n this.currentCommitIdentifier = currentCommitIdentifier;\n }\n}\n\n/**\n * Thrown when invitation commits carry variable identifiers that contain a dot.\n *\n * The compiler reads a dotted identifier as an operation on a variable, such as `someKey.public_key`, and looks that\n * identifier up in the same bytecode map as variable values. A dotted variable would replace the value that operation\n * derives from a key.\n *\n * @group Errors\n */\nexport class InvitationVariableIdentifierInvalidError extends Error {\n /**\n * Each invalid variable identifier with the commit that supplied it.\n */\n readonly invalidVariables: Array<{ variableIdentifier: string; commitIdentifier: XOInvitationCommitIdentifier }>;\n\n constructor(invalidVariables: Array<{ variableIdentifier: string; commitIdentifier: XOInvitationCommitIdentifier }>) {\n const variableIdentifiers: string[] = [];\n\n for (const invalidVariable of invalidVariables) {\n variableIdentifiers.push(invalidVariable.variableIdentifier);\n }\n\n const defaultMessage = `Variables ${JSON.stringify(variableIdentifiers)} invalid in invitation commits, expected identifiers without \".\"`;\n super(defaultMessage);\n this.name = 'InvitationVariableIdentifierInvalidError';\n this.invalidVariables = invalidVariables;\n }\n}\n\n/**\n * Thrown when a later commit sets an input or output field that an earlier commit already set, even to the same value.\n *\n * @group Errors\n */\nexport class InvitationItemFieldConflictError extends Error {\n /**\n * Every conflicting field with the commits involved.\n */\n readonly conflicts: InvitationItemFieldConflict[];\n\n constructor(conflicts: InvitationItemFieldConflict[]) {\n const conflictDescriptions: string[] = [];\n\n for (const conflict of conflicts) {\n conflictDescriptions.push(`${conflict.itemType} ${conflict.fundingItemKey} ${conflict.fieldName} set by \"${conflict.earlierCommitIdentifier}\", set again by \"${conflict.laterCommitIdentifier}\"`);\n }\n\n const defaultMessage = `Fields ${JSON.stringify(conflictDescriptions)} conflict in invitation commits, expected later commits to fill only empty fields`;\n super(defaultMessage);\n this.name = 'InvitationItemFieldConflictError';\n this.conflicts = conflicts;\n }\n}\n\n/**\n * Thrown when an intent passed with an invitation names a different template or action than the invitation.\n *\n * @group Errors\n */\nexport class InvitationIntentMismatchError extends Error {\n /**\n * Intent field that does not match the invitation.\n */\n readonly field: 'templateIdentifier' | 'action';\n\n /**\n * Value the invitation has for the field.\n */\n readonly invitationValue: string;\n\n /**\n * Value the intent has for the field.\n */\n readonly intentValue: string;\n\n constructor(field: 'templateIdentifier' | 'action', invitationValue: string, intentValue: string) {\n const defaultMessage = `Invitation intent ${field} mismatch, expected \"${invitationValue}\", got \"${intentValue}\"`;\n super(defaultMessage);\n this.name = 'InvitationIntentMismatchError';\n this.field = field;\n this.invitationValue = invitationValue;\n this.intentValue = intentValue;\n }\n}\n\n/**\n * Thrown when the role an entity takes is given both directly and on the intent.\n *\n * @group Errors\n */\nexport class InvitationRoleDuplicatedError extends Error {\n /**\n * Role given directly.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier;\n\n /**\n * Role given on the intent.\n */\n readonly intentRoleIdentifier: XOTemplateRoleIdentifier;\n\n constructor(roleIdentifier: XOTemplateRoleIdentifier, intentRoleIdentifier: XOTemplateRoleIdentifier) {\n const defaultMessage =\n 'Invitation role given twice, expected either roleIdentifier or intent.role, '\n + `got roleIdentifier \"${roleIdentifier}\" and intent.role \"${intentRoleIdentifier}\"`;\n super(defaultMessage);\n this.name = 'InvitationRoleDuplicatedError';\n this.roleIdentifier = roleIdentifier;\n this.intentRoleIdentifier = intentRoleIdentifier;\n }\n}\n\n/**\n * Thrown when a resolution names something other than an operation on a template key, since only key operations can be\n * resolved by the participant holding the key.\n *\n * @group Errors\n */\nexport class InvitationResolutionIdentifierInvalidError extends Error {\n /**\n * Identifiers that are not operations on a template key.\n */\n readonly resolutionIdentifiers: XOInvitationResolutionIdentifier[];\n\n constructor(resolutionIdentifiers: XOInvitationResolutionIdentifier[]) {\n const defaultMessage =\n `Resolution identifiers ${JSON.stringify(resolutionIdentifiers)} invalid in invitation, `\n + 'expected an operation on a template key such as someKey.public_key';\n super(defaultMessage);\n this.name = 'InvitationResolutionIdentifierInvalidError';\n this.resolutionIdentifiers = resolutionIdentifiers;\n }\n}\n\n/**\n * Thrown when a commit provides a variable that belongs to a role its entity does not hold, since only an entity\n * holding the role may provide its variables.\n *\n * @group Errors\n */\nexport class RoleVariableEntityMismatchError extends Error {\n /**\n * Every variable provided by an entity that does not hold its role.\n */\n readonly mismatches: RoleVariableEntityMismatch[];\n\n constructor(mismatches: RoleVariableEntityMismatch[]) {\n const mismatchDescriptions: string[] = [];\n\n for (const mismatch of mismatches) {\n mismatchDescriptions.push(`${mismatch.variableIdentifier} for ${JSON.stringify(mismatch.roleIdentifiers)} by \"${mismatch.entityIdentifier}\" in \"${mismatch.commitIdentifier}\"`);\n }\n\n const defaultMessage =\n `Variables ${JSON.stringify(mismatchDescriptions)} provided by entities that do not hold their role, `\n + 'expected only the entities that took a role to provide its variables';\n super(defaultMessage);\n this.name = 'RoleVariableEntityMismatchError';\n this.mismatches = mismatches;\n }\n}\n\n/**\n * Thrown when an entity holds more than one role with a follow up action.\n *\n * @group Errors\n */\nexport class EntityMultipleRolesWithFollowUpUnsupportedError extends Error {\n /**\n * Every entity that holds more than one role with a follow up, with those roles.\n */\n readonly entities: EntityRolesMultipleEntry[];\n\n constructor(entities: EntityRolesMultipleEntry[]) {\n const entityDescriptions: string[] = [];\n\n for (const entity of entities) {\n entityDescriptions.push(`\"${entity.entityIdentifier}\" takes ${JSON.stringify(entity.roleIdentifiers)}`);\n }\n\n const defaultMessage =\n `Entities ${JSON.stringify(entityDescriptions)} take more than one role with a follow up in the invitation outputs, `\n + 'expected at most one such role per entity. Multiple roles with a follow up from a single account are not supported yet';\n super(defaultMessage);\n this.name = 'EntityMultipleRolesWithFollowUpUnsupportedError';\n this.entities = entities;\n }\n}\n\n/**\n * Thrown when an entity tries to join an invitation with a role that has no free slot left.\n *\n * @group Errors\n */\nexport class InvitationRoleUnavailableError extends Error {\n /**\n * Invitation the entity tries to join.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Role that has no free slot.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier;\n\n /**\n * Roles that still have a free slot.\n */\n readonly availableRoleIdentifiers: XOTemplateRoleIdentifier[];\n\n constructor(\n invitationIdentifier: XOInvitationIdentifier,\n roleIdentifier: XOTemplateRoleIdentifier,\n availableRoleIdentifiers: XOTemplateRoleIdentifier[],\n ) {\n const defaultMessage = `Role \"${roleIdentifier}\" unavailable in invitation \"${invitationIdentifier}\", expected one of ${JSON.stringify(availableRoleIdentifiers)}`;\n super(defaultMessage);\n this.name = 'InvitationRoleUnavailableError';\n this.invitationIdentifier = invitationIdentifier;\n this.roleIdentifier = roleIdentifier;\n this.availableRoleIdentifiers = availableRoleIdentifiers;\n }\n}\n\n/**\n * Thrown when an output appended to an invitation names a template output but carries no locking bytecode.\n *\n * @group Errors\n */\nexport class OutputLockingBytecodeNotProvidedError extends Error {\n /**\n * Invitation the output is appended to.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Template output that has no locking bytecode.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage =\n `Locking bytecode not provided for output \"${outputIdentifier}\" appended to invitation \"${invitationIdentifier}\", `\n + 'expected locking bytecode on every appended output that names a template output';\n super(defaultMessage);\n this.name = 'OutputLockingBytecodeNotProvidedError';\n this.invitationIdentifier = invitationIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when the merged invitation has no input at the index asked to be unlocked.\n *\n * @group Errors\n */\nexport class MergedInputNotFoundError extends Error {\n /**\n * Invitation whose merged inputs were searched.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Position in the merged input list that has no input.\n */\n readonly inputIndex: number;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, inputIndex: number) {\n const defaultMessage = `No input available at the given index to unlock: inputIndex ${String(inputIndex)}, invitationIdentifier \"${invitationIdentifier}\"`;\n super(defaultMessage);\n this.name = 'MergedInputNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n }\n}\n\n/**\n * Thrown when change is added to an invitation but no locking bytecode was provided, the template defines no change policy,\n * and the wallet has no default change policy.\n *\n * @group Errors\n */\nexport class ChangeLockingBytecodeMissingError extends Error {\n /**\n * Invitation the change was added to.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Template of the invitation, which defines no change policy.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, templateIdentifier: XOTemplateIdentifier) {\n const defaultMessage =\n `No change locking bytecode created for invitation \"${invitationIdentifier}\", `\n + `expected a provided locking bytecode, a change policy in template \"${templateIdentifier}\", or a wallet default change policy`;\n super(defaultMessage);\n this.name = 'ChangeLockingBytecodeMissingError';\n this.invitationIdentifier = invitationIdentifier;\n this.templateIdentifier = templateIdentifier;\n }\n}\n\n/**\n * Thrown when a merged input has neither valueSatoshis nor an outpoint, or a merged output has no valueSatoshis.\n *\n * @group Errors\n */\nexport class MergedItemValueSatoshisMissingError extends Error {\n /**\n * Whether the item is a merged input or a merged output.\n */\n readonly itemType: 'input' | 'output';\n\n /**\n * Position of the item in the merged input or output list.\n */\n readonly itemIndex: number;\n\n /**\n * Commit that last wrote the item.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(itemType: 'input' | 'output', itemIndex: number, commitIdentifier: XOInvitationCommitIdentifier) {\n const defaultMessage = `Merged ${itemType} is missing valueSatoshis: ${itemType}Index ${String(itemIndex)}, from commit: ${commitIdentifier}`;\n super(defaultMessage);\n this.name = 'MergedItemValueSatoshisMissingError';\n this.itemType = itemType;\n this.itemIndex = itemIndex;\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Thrown when a merged output names a template output that defines no locking script and the commit that last wrote it provides no locking bytecode.\n *\n * @group Errors\n */\nexport class MergedOutputLockingBytecodeMissingError extends Error {\n /**\n * Template output the merged output names.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n /**\n * Position of the output in the merged output list.\n */\n readonly outputIndex: number;\n\n /**\n * Position of the output in the transaction when the commit or the template action sets it.\n */\n readonly transactionIndex: number | undefined;\n\n /**\n * Commit that last wrote the output.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Template whose output defines no locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n constructor(\n outputIdentifier: XOTemplateOutputIdentifier,\n outputIndex: number,\n transactionIndex: number | undefined,\n commitIdentifier: XOInvitationCommitIdentifier,\n templateIdentifier: XOTemplateIdentifier,\n ) {\n let transactionIndexDetail = '';\n if (transactionIndex !== undefined) {\n transactionIndexDetail = `, transactionIndex ${String(transactionIndex)}`;\n }\n\n const defaultMessage =\n `Locking bytecode missing on merged output ${String(outputIndex)} \"${outputIdentifier}\"${transactionIndexDetail} from commit: ${commitIdentifier}, `\n + `expected the commit to provide it because the output defines no locking script in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'MergedOutputLockingBytecodeMissingError';\n this.outputIdentifier = outputIdentifier;\n this.outputIndex = outputIndex;\n this.transactionIndex = transactionIndex;\n this.commitIdentifier = commitIdentifier;\n this.templateIdentifier = templateIdentifier;\n }\n}\n\n/**\n * Thrown when the token on a merged input or output is missing its category or amount.\n *\n * @group Errors\n */\nexport class MergedItemTokenIncompleteError extends Error {\n /**\n * Whether the item is a merged input or a merged output.\n */\n readonly itemType: 'input' | 'output';\n\n /**\n * Position of the item in the merged input or output list.\n */\n readonly itemIndex: number;\n\n /**\n * Commit that last wrote the item.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n constructor(itemType: 'input' | 'output', itemIndex: number, commitIdentifier: XOInvitationCommitIdentifier) {\n const defaultMessage = `Merged ${itemType} token is missing category or amount: ${itemType}Index ${String(itemIndex)}, from commit: ${commitIdentifier}`;\n super(defaultMessage);\n this.name = 'MergedItemTokenIncompleteError';\n this.itemType = itemType;\n this.itemIndex = itemIndex;\n this.commitIdentifier = commitIdentifier;\n }\n}\n\n/**\n * Thrown when a token a commit supplies on an output has no category.\n *\n * @group Errors\n */\nexport class CommitTokenCategoryMissingError extends Error {\n /**\n * Commit that last wrote the output.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Position of the output in the merged output list.\n */\n readonly outputIndex: number;\n\n constructor(commitIdentifier: XOInvitationCommitIdentifier, outputIndex: number) {\n const defaultMessage = `Token category missing on output ${String(outputIndex)} from commit: ${commitIdentifier}`;\n super(defaultMessage);\n this.name = 'CommitTokenCategoryMissingError';\n this.commitIdentifier = commitIdentifier;\n this.outputIndex = outputIndex;\n }\n}\n\n/**\n * Thrown when an NFT a commit supplies on an output has no capability.\n *\n * @group Errors\n */\nexport class CommitTokenNftCapabilityMissingError extends Error {\n /**\n * Commit that last wrote the output.\n */\n readonly commitIdentifier: XOInvitationCommitIdentifier;\n\n /**\n * Position of the output in the merged output list.\n */\n readonly outputIndex: number;\n\n constructor(commitIdentifier: XOInvitationCommitIdentifier, outputIndex: number) {\n const defaultMessage = `Token NFT capability missing on output ${String(outputIndex)} from commit: ${commitIdentifier}`;\n super(defaultMessage);\n this.name = 'CommitTokenNftCapabilityMissingError';\n this.commitIdentifier = commitIdentifier;\n this.outputIndex = outputIndex;\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type { IncompleteScriptCompilation, ScriptCompilationErrorDetail } from '@xo-cash/crypto';\nimport type {\n XOInvitationIdentifier,\n XOInvitationResolutionIdentifier,\n XOTemplateIdentifier,\n XOTemplateLockingScriptIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateSecretIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\n\n/**\n * Thrown when a number variable value is not a valid integer for CashAssembly compilation.\n *\n * @group Errors\n */\nexport class CashAssemblyVariableNotIntegerError extends Error {\n /**\n * Variable name whose value was rejected.\n */\n readonly variableName: XOTemplateVariableIdentifier;\n\n /**\n * Numeric value that was not an integer.\n */\n readonly value: number;\n\n constructor(variableName: XOTemplateVariableIdentifier, value: number) {\n const defaultMessage = `CashAssembly variable not integer: variableName \"${variableName}\", expected an integer, got ${String(value)}`;\n super(defaultMessage);\n this.name = 'CashAssemblyVariableNotIntegerError';\n this.variableName = variableName;\n this.value = value;\n }\n}\n\n/**\n * Thrown when a template locking script compiled from variables alone fails to compile.\n *\n * @group Errors\n */\nexport class LockingScriptCompilationFailedError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that failed to compile.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Every error message the compiler reported.\n */\n readonly compilationErrorMessages: string[];\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n compilationErrorMessages: string[],\n ) {\n const defaultMessage =\n `Locking script \"${lockingScriptIdentifier}\" compilation failed in template: ${templateIdentifier}, `\n + `errors ${JSON.stringify(compilationErrorMessages)}`;\n super(defaultMessage);\n this.name = 'LockingScriptCompilationFailedError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.compilationErrorMessages = compilationErrorMessages;\n }\n}\n\n/**\n * Thrown when a locking script stops compiling before it produces bytecode.\n *\n * @group Errors\n */\nexport class LockingBytecodeGenerationFailedError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that failed to compile.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Script the compiler was compiling.\n */\n readonly scriptId: string;\n\n /**\n * Compiler stage that stopped.\n */\n readonly compilationStage: IncompleteScriptCompilation['compilationStage'];\n\n /**\n * Every error the compiler reported, with its source range.\n */\n readonly compilationErrors: ScriptCompilationErrorDetail[];\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n incompleteCompilation: IncompleteScriptCompilation,\n ) {\n const errorMessages: string[] = [];\n\n for (const compilationError of incompleteCompilation.compilationErrors) {\n errorMessages.push(compilationError.message);\n }\n\n const defaultMessage =\n `Locking bytecode generation failed for locking script \"${lockingScriptIdentifier}\" in template: ${templateIdentifier}, `\n + `script \"${incompleteCompilation.scriptId}\" stopped at the ${incompleteCompilation.compilationStage} stage, `\n + `errors ${JSON.stringify(errorMessages)}`;\n super(defaultMessage);\n this.name = 'LockingBytecodeGenerationFailedError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.scriptId = incompleteCompilation.scriptId;\n this.compilationStage = incompleteCompilation.compilationStage;\n this.compilationErrors = incompleteCompilation.compilationErrors;\n }\n}\n\n/**\n * Thrown when an unlocking script stops compiling before it produces bytecode.\n *\n * @group Errors\n */\nexport class UnlockingBytecodeGenerationFailedError extends Error {\n /**\n * Merged input whose unlocking script failed to compile.\n */\n readonly inputIndex: number;\n\n /**\n * Script the compiler was compiling.\n */\n readonly scriptId: string;\n\n /**\n * Compiler stage that stopped.\n */\n readonly compilationStage: IncompleteScriptCompilation['compilationStage'];\n\n /**\n * Every error the compiler reported, with its source range.\n */\n readonly compilationErrors: ScriptCompilationErrorDetail[];\n\n constructor(inputIndex: number, incompleteCompilation: IncompleteScriptCompilation) {\n const errorMessages: string[] = [];\n\n for (const compilationError of incompleteCompilation.compilationErrors) {\n errorMessages.push(compilationError.message);\n }\n\n const defaultMessage =\n `Unlocking bytecode generation failed for input ${String(inputIndex)}, script \"${incompleteCompilation.scriptId}\" `\n + `stopped at the ${incompleteCompilation.compilationStage} stage, errors ${JSON.stringify(errorMessages)}`;\n super(defaultMessage);\n this.name = 'UnlockingBytecodeGenerationFailedError';\n this.inputIndex = inputIndex;\n this.scriptId = incompleteCompilation.scriptId;\n this.compilationStage = incompleteCompilation.compilationStage;\n this.compilationErrors = incompleteCompilation.compilationErrors;\n }\n}\n\n/**\n * Thrown when a locking script uses existing secrets that this account has not generated for the invitation it is built for.\n * Only a generate list creates a secret, so a secret the script expects to exist is never generated in its place.\n *\n * @group Errors\n */\nexport class LockingScriptSecretsNotFoundError extends Error {\n /**\n * Template that defines the locking script.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script that uses the secrets.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Secrets the locking script uses that the invitation does not hold.\n */\n readonly secretIdentifiers: XOTemplateSecretIdentifier[];\n\n /**\n * Role the locking script was built for, when one was given.\n */\n readonly roleIdentifier: XOTemplateRoleIdentifier | undefined;\n\n /**\n * Invitation whose secrets were searched, when it is known.\n */\n readonly invitationIdentifier: XOInvitationIdentifier | undefined;\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n secretIdentifiers: XOTemplateSecretIdentifier[],\n roleIdentifier?: XOTemplateRoleIdentifier,\n invitationIdentifier?: XOInvitationIdentifier,\n ) {\n let roleDetail = '';\n if (roleIdentifier !== undefined) {\n roleDetail = ` role \"${roleIdentifier}\"`;\n }\n\n let invitationDetail = 'the invitation';\n if (invitationIdentifier !== undefined) {\n invitationDetail = `invitation \"${invitationIdentifier}\"`;\n }\n\n const defaultMessage =\n `Secrets ${JSON.stringify(secretIdentifiers)} not found in ${invitationDetail} for locking script \"${lockingScriptIdentifier}\"${roleDetail} `\n + `in template: ${templateIdentifier}, expected secrets this account generated for the invitation`;\n super(defaultMessage);\n this.name = 'LockingScriptSecretsNotFoundError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.secretIdentifiers = secretIdentifiers;\n this.roleIdentifier = roleIdentifier;\n this.invitationIdentifier = invitationIdentifier;\n }\n}\n\n/**\n * Thrown when a locking script cannot be compiled yet because the compiler reports identifiers missing from the\n * compilation data, such as a public key of a key another entity holds. The operations the compiler resolved from this\n * account's keys are carried so they can be provided to the invitation.\n *\n * @group Errors\n */\nexport class LockingScriptResolutionsMissingError extends Error {\n /**\n * Locking script that could not be compiled.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Identifiers the compiler reports as missing.\n */\n readonly missingIdentifiers: XOInvitationResolutionIdentifier[];\n\n /**\n * Operations on this account's keys the compiler resolved, keyed by their full identifier.\n */\n readonly resolvedKeyOperations: Record<XOInvitationResolutionIdentifier, Uint8Array>;\n\n /**\n * Compiler errors with their source position, missing identifier, and owning entity.\n */\n readonly compilationErrors: ScriptCompilationErrorDetail[];\n\n constructor(\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n missingIdentifiers: XOInvitationResolutionIdentifier[],\n resolvedKeyOperations: Record<XOInvitationResolutionIdentifier, Uint8Array>,\n compilationErrors: ScriptCompilationErrorDetail[],\n ) {\n const defaultMessage =\n `Identifiers ${JSON.stringify(missingIdentifiers)} missing for locking script \"${lockingScriptIdentifier}\", `\n + 'expected the entities holding those keys to provide them in the invitation';\n super(defaultMessage);\n this.name = 'LockingScriptResolutionsMissingError';\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.missingIdentifiers = missingIdentifiers;\n this.resolvedKeyOperations = resolvedKeyOperations;\n this.compilationErrors = compilationErrors;\n }\n}\n\n/**\n * Thrown when an input's unlocking script cannot be compiled yet because the compiler reports identifiers missing from\n * the compilation data, such as a signature of a key another entity holds. The operations the compiler resolved from\n * this account's keys are carried so they can be provided to the invitation.\n *\n * @group Errors\n */\nexport class UnlockingScriptResolutionsMissingError extends Error {\n /**\n * Merged input whose unlocking script could not be compiled.\n */\n readonly inputIndex: number;\n\n /**\n * Identifiers the compiler reports as missing.\n */\n readonly missingIdentifiers: XOInvitationResolutionIdentifier[];\n\n /**\n * Operations on this account's keys the compiler resolved, keyed by their full identifier.\n */\n readonly resolvedKeyOperations: Record<XOInvitationResolutionIdentifier, Uint8Array>;\n\n /**\n * Compiler errors with their source position, missing identifier, and owning entity.\n */\n readonly compilationErrors: ScriptCompilationErrorDetail[];\n\n constructor(\n inputIndex: number,\n missingIdentifiers: XOInvitationResolutionIdentifier[],\n resolvedKeyOperations: Record<XOInvitationResolutionIdentifier, Uint8Array>,\n compilationErrors: ScriptCompilationErrorDetail[],\n ) {\n const defaultMessage =\n `Identifiers ${JSON.stringify(missingIdentifiers)} missing for the unlocking script of input ${String(inputIndex)}, `\n + 'expected the entities holding those keys to provide them in the invitation';\n super(defaultMessage);\n this.name = 'UnlockingScriptResolutionsMissingError';\n this.inputIndex = inputIndex;\n this.missingIdentifiers = missingIdentifiers;\n this.resolvedKeyOperations = resolvedKeyOperations;\n this.compilationErrors = compilationErrors;\n }\n}\n\n/**\n * Thrown when an unlocking bytecode built with values other participants provided does not unlock the output it spends.\n *\n * @group Errors\n */\nexport class UnlockingBytecodeVerificationFailedError extends Error {\n /**\n * Merged input whose unlocking bytecode failed.\n */\n readonly inputIndex: number;\n\n /**\n * Hash of the transaction that holds the spent output, as hexadecimal.\n */\n readonly outpointTransactionHash: string;\n\n /**\n * Index of the spent output in that transaction.\n */\n readonly outpointIndex: number;\n\n /**\n * Failure reported by the virtual machine.\n */\n readonly reason: string;\n\n constructor(inputIndex: number, outpointTransactionHash: string, outpointIndex: number, reason: string) {\n const defaultMessage =\n `Unlocking bytecode of input ${String(inputIndex)} spending ${outpointTransactionHash}:${String(outpointIndex)} `\n + `failed verification: ${reason}`;\n super(defaultMessage);\n this.name = 'UnlockingBytecodeVerificationFailedError';\n this.inputIndex = inputIndex;\n this.outpointTransactionHash = outpointTransactionHash;\n this.outpointIndex = outpointIndex;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown when the unlocking compilation of a merged input carries no compilation context to verify the unlocking bytecode against.\n *\n * @group Errors\n */\nexport class UnlockingCompilationContextMissingError extends Error {\n /**\n * Invitation that owns the input.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Merged input whose compilation has no context.\n */\n readonly inputIndex: number;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, inputIndex: number) {\n const defaultMessage =\n `Compilation context missing for the unlocking bytecode of input ${String(inputIndex)} in invitation \"${invitationIdentifier}\", `\n + 'expected the transaction and source outputs the input is signed against';\n super(defaultMessage);\n this.name = 'UnlockingCompilationContextMissingError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n }\n}\n\n/**\n * Thrown when this account is asked to add its own resolutions for an output, but it resolved none that the invitation\n * does not already hold.\n *\n * @group Errors\n */\nexport class OutputOwnResolutionsNotFoundError extends Error {\n /**\n * Invitation the output belongs to.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Template output the resolutions were asked for.\n */\n readonly outputIdentifier: XOTemplateOutputIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, outputIdentifier: XOTemplateOutputIdentifier) {\n const defaultMessage =\n `Own resolutions for output \"${outputIdentifier}\" not found in invitation \"${invitationIdentifier}\", `\n + \"expected at least one value resolved from this account's keys that the invitation does not hold yet\";\n super(defaultMessage);\n this.name = 'OutputOwnResolutionsNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.outputIdentifier = outputIdentifier;\n }\n}\n\n/**\n * Thrown when this account is asked to add its own resolutions for an input, but it resolved none that the invitation\n * does not already hold.\n *\n * @group Errors\n */\nexport class InputOwnResolutionsNotFoundError extends Error {\n /**\n * Invitation the input belongs to.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Merged input the resolutions were asked for.\n */\n readonly inputIndex: number;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, inputIndex: number) {\n const defaultMessage =\n `Own resolutions for input ${String(inputIndex)} not found in invitation \"${invitationIdentifier}\", `\n + \"expected at least one value resolved from this account's keys that the invitation does not hold yet\";\n super(defaultMessage);\n this.name = 'InputOwnResolutionsNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.inputIndex = inputIndex;\n }\n}\n\n/**\n * Thrown when a secret used to derive a key is declared in the template with a type other than private_key.\n *\n * @group Errors\n */\nexport class SecretIdentifierTypeInvalidError extends Error {\n /**\n * Template that declares the secret.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Secret identifier whose template variable is not a private key.\n */\n readonly secretIdentifier: XOTemplateSecretIdentifier;\n\n /**\n * Type the template declares for the secret, undefined when the template does not declare it.\n */\n readonly declaredType: string | undefined;\n\n constructor(templateIdentifier: XOTemplateIdentifier, secretIdentifier: XOTemplateSecretIdentifier, declaredType?: string) {\n const defaultMessage =\n `Secret \"${secretIdentifier}\" type invalid in template: ${templateIdentifier}, `\n + `expected \"private_key\", got \"${declaredType ?? 'undeclared'}\"`;\n super(defaultMessage);\n this.name = 'SecretIdentifierTypeInvalidError';\n this.templateIdentifier = templateIdentifier;\n this.secretIdentifier = secretIdentifier;\n this.declaredType = declaredType;\n }\n}\n\n/**\n * Thrown when variables an intent requires are missing from the provided values.\n *\n * @group Errors\n */\nexport class IntentVariablesMissingError extends Error {\n /**\n * Template that defines the intent.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script the intent generates.\n */\n readonly lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Variables the intent requires that have no provided value.\n */\n readonly variableIdentifiers: XOTemplateVariableIdentifier[];\n\n constructor(\n templateIdentifier: XOTemplateIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n variableIdentifiers: XOTemplateVariableIdentifier[],\n ) {\n const defaultMessage =\n `Variables ${JSON.stringify(variableIdentifiers)} required by intent for locking script \"${lockingScriptIdentifier}\" `\n + `missing from provided values in template: ${templateIdentifier}`;\n super(defaultMessage);\n this.name = 'IntentVariablesMissingError';\n this.templateIdentifier = templateIdentifier;\n this.lockingScriptIdentifier = lockingScriptIdentifier;\n this.variableIdentifiers = variableIdentifiers;\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type { XOInvitationIdentifier, XOTemplateActionIdentifier, XOTemplateIdentifier, XOTemplateTransactionIdentifier } from '@xo-cash/types';\n\n/**\n * Thrown when a parent transaction has no output at the requested index.\n *\n * @group Errors\n */\nexport class TransactionOutputNotFoundError extends Error {\n /**\n * Parent transaction hash that was searched.\n */\n readonly transactionHash: string;\n\n /**\n * Output index that was looked up.\n */\n readonly outputIndex: number;\n\n constructor(transactionHash: string, outputIndex: number) {\n const defaultMessage = `Transaction output not found: outputIndex ${String(outputIndex)}, transactionHash \"${transactionHash}\"`;\n super(defaultMessage);\n this.name = 'TransactionOutputNotFoundError';\n this.transactionHash = transactionHash;\n this.outputIndex = outputIndex;\n }\n}\n\n/**\n * Thrown when transaction generation fails.\n *\n * @group Errors\n */\nexport class TransactionGenerationFailedError extends Error {\n /**\n * Template that defines the action.\n */\n readonly templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Action whose transaction failed to generate.\n */\n readonly actionIdentifier: XOTemplateActionIdentifier;\n\n /**\n * Generation failure reported by Libauth.\n */\n readonly reason: string;\n\n constructor(templateIdentifier: XOTemplateIdentifier, actionIdentifier: XOTemplateActionIdentifier, reason: string) {\n const defaultMessage = `Transaction generation failed for action \"${actionIdentifier}\" in template: ${templateIdentifier}, ${reason}`;\n super(defaultMessage);\n this.name = 'TransactionGenerationFailedError';\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown when a transaction result already exists for the given template transaction identifier.\n *\n * @group Errors\n */\nexport class TransactionResultAlreadyExistsError extends Error {\n /**\n * Invitation that already has the result.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Template transaction identifier that already has a result.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, transactionIdentifier: XOTemplateTransactionIdentifier) {\n const defaultMessage = `Transaction result already exists: invitationIdentifier \"${invitationIdentifier}\", transactionIdentifier \"${transactionIdentifier}\"`;\n super(defaultMessage);\n this.name = 'TransactionResultAlreadyExistsError';\n this.invitationIdentifier = invitationIdentifier;\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Thrown when a transaction result is absent for the given template transaction identifier.\n *\n * @group Errors\n */\nexport class TransactionResultNotFoundError extends Error {\n /**\n * Invitation that was searched.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Template transaction identifier whose result was missing.\n */\n readonly transactionIdentifier: XOTemplateTransactionIdentifier;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, transactionIdentifier: XOTemplateTransactionIdentifier) {\n const defaultMessage = `Transaction result not found: invitationIdentifier \"${invitationIdentifier}\", transactionIdentifier \"${transactionIdentifier}\"`;\n super(defaultMessage);\n this.name = 'TransactionResultNotFoundError';\n this.invitationIdentifier = invitationIdentifier;\n this.transactionIdentifier = transactionIdentifier;\n }\n}\n\n/**\n * Thrown when a built invitation transaction cannot be broadcast to the network.\n *\n * @group Errors\n */\nexport class TransactionBroadcastFailedError extends Error {\n /**\n * Invitation the transaction was built from.\n */\n readonly invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * Hash of the transaction that was broadcast.\n */\n readonly transactionHash: string;\n\n /**\n * Reason the Electrum servers reported for rejecting the transaction.\n */\n readonly reason: string;\n\n constructor(invitationIdentifier: XOInvitationIdentifier, transactionHash: string, reason: string, options?: { cause?: unknown }) {\n const defaultMessage = `Transaction broadcast failed for transaction hash \"${transactionHash}\" of invitation \"${invitationIdentifier}\": ${reason}`;\n super(defaultMessage, options);\n this.name = 'TransactionBroadcastFailedError';\n this.invitationIdentifier = invitationIdentifier;\n this.transactionHash = transactionHash;\n this.reason = reason;\n }\n}\n","/* eslint-disable max-classes-per-file */\n\nimport type { WalletDefaultPolicies } from '../interfaces.ts';\n\n/**\n * Thrown when a wallet default policy is used before it has been set.\n *\n * @group Errors\n */\nexport class DefaultPolicyNotSetError extends Error {\n /**\n * Default policy that was looked up.\n */\n readonly policy: keyof WalletDefaultPolicies;\n\n constructor(policy: keyof WalletDefaultPolicies) {\n const defaultMessage = `Default ${policy} policy not set, expected it to be set with setDefaultPolicies`;\n super(defaultMessage);\n this.name = 'DefaultPolicyNotSetError';\n this.policy = policy;\n }\n}\n\n/**\n * Thrown when a wallet name is empty or contains only whitespace.\n *\n * @group Errors\n */\nexport class WalletNameMissingError extends Error {\n constructor() {\n const defaultMessage = 'Wallet name missing, expected at least one character that is not whitespace';\n super(defaultMessage);\n this.name = 'WalletNameMissingError';\n }\n}\n","import type {\n XOTemplate,\n XOTemplateAction,\n XOTemplateActionIdentifier,\n XOTemplateActionIntent,\n XOTemplateLockingScript,\n XOTemplateLockingScriptIdentifier,\n XOTemplateLockingScriptRole,\n XOTemplateRoleIdentifier,\n XOTemplateOutput,\n XOTemplateOutputIdentifier,\n XOTemplateTransaction,\n XOTemplateTransactionIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport {\n TemplateActionNotFoundError,\n TemplateActionRoleNotFoundError,\n TemplateActionTransactionNotFoundError,\n TemplateGeneratedVariableTypeUnsupportedError,\n TemplateLockingScriptNotFoundError,\n TemplateLockingScriptRoleNotFoundError,\n TemplateLockingScriptTypeNotFoundError,\n TemplateOutputLockingScriptNotFoundError,\n TemplateOutputNotFoundError,\n TemplateTransactionNotFoundError,\n} from './errors/index.ts';\n\n/**\n * Returns an output definition by identifier.\n *\n * @param {XOTemplate} template - Template whose outputs are searched.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Output identifier to look up.\n * @returns {XOTemplateOutput} - Output definition for that identifier.\n * @throws {@link TemplateOutputNotFoundError} - When the output is absent from the template.\n */\nexport const getTemplateOutputOrThrow = (template: XOTemplate, outputIdentifier: XOTemplateOutputIdentifier): XOTemplateOutput => {\n const output = template.outputs[outputIdentifier];\n\n // If the output is not defined, throw an error.\n if (output === undefined) {\n throw new TemplateOutputNotFoundError(generateTemplateIdentifier(template), outputIdentifier);\n }\n\n return output;\n};\n\n/**\n * Returns the locking script identifier declared on an output.\n *\n * @param {XOTemplate} template - Template whose outputs are searched.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Output whose locking script is read.\n * @returns {XOTemplateLockingScriptIdentifier} - Locking script identifier on that output.\n * @throws {@link TemplateOutputNotFoundError} - When the output is absent from the template.\n * @throws {@link TemplateOutputLockingScriptNotFoundError} - When the output has no locking script reference.\n */\nexport const getTemplateLockingScriptIdentifierOrThrow = (\n template: XOTemplate,\n outputIdentifier: XOTemplateOutputIdentifier,\n): XOTemplateLockingScriptIdentifier => {\n // If the output is not defined, throw an error.\n const output = getTemplateOutputOrThrow(template, outputIdentifier);\n\n // If the output has no locking script, throw an error.\n if (output.lockingScript === undefined) {\n throw new TemplateOutputLockingScriptNotFoundError(generateTemplateIdentifier(template), outputIdentifier);\n }\n\n // Return the locking script identifier.\n return output.lockingScript;\n};\n\n/**\n * Returns a locking script definition by identifier.\n *\n * @param {XOTemplate} template - Template whose locking scripts are searched.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script identifier to look up.\n * @returns {XOTemplateLockingScript} - Locking script definition for that identifier.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is absent from the template.\n * @throws {@link TemplateLockingScriptTypeNotFoundError} - When the locking script omits lockingType.\n */\nexport const getTemplateLockingScriptOrThrow = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n): XOTemplateLockingScript => {\n const lockingScript = template.lockingScripts[lockingScriptIdentifier];\n\n // If the locking script is not defined, throw an error.\n if (lockingScript === undefined) {\n throw new TemplateLockingScriptNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier);\n }\n\n // If the locking script has no locking type, throw an error.\n if (lockingScript.lockingType === undefined) {\n throw new TemplateLockingScriptTypeNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier);\n }\n\n return lockingScript;\n};\n\n/**\n * Returns a role definition on a locking script.\n *\n * @param {XOTemplate} template - Template whose locking scripts are searched.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script that owns the role.\n * @param {XOTemplateRoleIdentifier} roleIdentifier - Role identifier to look up.\n * @returns {XOTemplateLockingScriptRole} - Role definition on that locking script.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is absent from the template.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When the role is absent from the locking script.\n */\nexport const getTemplateRoleOrThrow = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n roleIdentifier: XOTemplateRoleIdentifier,\n): XOTemplateLockingScriptRole => {\n // If the locking script is not defined, throw an error.\n const lockingScript = getTemplateLockingScriptOrThrow(template, lockingScriptIdentifier);\n\n // Get the role definition.\n const role = lockingScript.roles?.[roleIdentifier];\n\n // If the role is not defined, throw an error.\n if (role === undefined) {\n throw new TemplateLockingScriptRoleNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier, roleIdentifier);\n }\n\n // Return the role definition.\n return role;\n};\n\n/**\n * Returns secret identifiers tracked for a locking script or one of its roles.\n *\n * @param {XOTemplate} template - Template whose locking scripts are searched.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script whose secrets are read.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role whose secrets are used when provided.\n * @returns {string[]} - Secret identifiers from the role or from the locking script.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is absent from the template.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When a role is provided but is absent.\n */\nexport const listTemplateSecrets = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): string[] => {\n // If a role is provided, return its secret list.\n if (roleIdentifier !== undefined) {\n const role = getTemplateRoleOrThrow(template, lockingScriptIdentifier, roleIdentifier);\n\n // Return the role's secret list.\n return role.state?.secrets ?? [];\n }\n\n // If no role is provided, return the secret list of the locking script.\n const lockingScript = getTemplateLockingScriptOrThrow(template, lockingScriptIdentifier);\n\n // Return the locking script's secret list.\n return lockingScript.state?.secrets ?? [];\n};\n\n/**\n * Returns an action definition by identifier.\n *\n * @param {XOTemplate} template - Template whose actions are searched.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action identifier to look up.\n * @returns {XOTemplateAction} - Action definition for that identifier.\n * @throws {@link TemplateActionNotFoundError} - When the action is absent from the template.\n */\nexport const getTemplateActionOrThrow = (template: XOTemplate, actionIdentifier: XOTemplateActionIdentifier): XOTemplateAction => {\n const action = template.actions[actionIdentifier];\n\n // If the action is not defined, throw an error.\n if (action === undefined) {\n throw new TemplateActionNotFoundError(generateTemplateIdentifier(template), actionIdentifier);\n }\n\n // Return the action definition.\n return action;\n};\n\n/**\n * Returns the transaction identifier an action names.\n *\n * @param {XOTemplate} template - Template that defines the action.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action whose transaction is read.\n * @returns {XOTemplateTransactionIdentifier} - Transaction identifier the action names.\n * @throws {@link TemplateActionNotFoundError} - When the action is absent from the template.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action names no transaction.\n */\nexport const getTemplateActionTransactionIdentifierOrThrow = (\n template: XOTemplate,\n actionIdentifier: XOTemplateActionIdentifier,\n): XOTemplateTransactionIdentifier => {\n // If the action is not defined, throw an error.\n const action = getTemplateActionOrThrow(template, actionIdentifier);\n\n // If the action has no transaction, throw an error.\n if (action.transaction === undefined) {\n throw new TemplateActionTransactionNotFoundError(generateTemplateIdentifier(template), actionIdentifier);\n }\n\n // Return the transaction identifier.\n return action.transaction;\n};\n\n/**\n * Lists one action intent for every action the template defines.\n *\n * Each intent names only its action. It carries no role, constants, variables, or generate list.\n *\n * @param {XOTemplate} template - Template whose actions are listed.\n * @returns {XOTemplateActionIntent[]} - One intent per action identifier, in the order the template declares them.\n */\nexport const listTemplateActionIntents = (template: XOTemplate): XOTemplateActionIntent[] => {\n const actionIntents: XOTemplateActionIntent[] = [];\n\n // For each action, create an intent that names the action alone.\n for (const actionIdentifier of Object.keys(template.actions)) {\n actionIntents.push({\n action: actionIdentifier,\n });\n }\n\n // Return the action intents.\n return actionIntents;\n};\n\n/**\n * Returns a transaction definition by identifier.\n *\n * @param {XOTemplate} template - Template whose transactions are searched.\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Transaction identifier to look up.\n * @returns {XOTemplateTransaction} - Transaction definition for that identifier.\n * @throws {@link TemplateTransactionNotFoundError} - When the transaction is absent from the template.\n */\nexport const getTemplateTransactionOrThrow = (\n template: XOTemplate,\n transactionIdentifier: XOTemplateTransactionIdentifier,\n): XOTemplateTransaction => {\n // If the transaction is not defined, throw an error.\n const transaction = template.transactions?.[transactionIdentifier];\n\n if (transaction === undefined) {\n throw new TemplateTransactionNotFoundError(generateTemplateIdentifier(template), transactionIdentifier);\n }\n\n // Return the transaction definition.\n return transaction;\n};\n\n/**\n * Lists the variables to generate for an entity that takes part in an action.\n *\n * Combines the generate list of an intent with the generate list of the action role. A variable in both, or listed\n * twice, is one variable. The action role's list comes from the template, so an intent can add variables but never drop one the\n * action needs.\n *\n * Every variable is checked, and all variables that are not declared as private keys are reported together as private_key type\n * is the only supported type.\n *\n * @param {XOTemplate} template - Template that defines the action and declares the variables.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action the entity takes part in.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role the entity takes, when it takes one.\n * @param {XOTemplateVariableIdentifier[]} [intentGenerate] - Generate list of an intent, when one is given.\n * @returns {XOTemplateVariableIdentifier[]} - Variables to generate, each listed once, empty when nothing is asked for.\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the action.\n * @throws {@link TemplateActionRoleNotFoundError} - When the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - When a listed variable is not declared as a private key.\n */\nexport const listVariableIdentifiersToGenerate = (\n template: XOTemplate,\n actionIdentifier: XOTemplateActionIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n intentGenerate?: XOTemplateVariableIdentifier[],\n): XOTemplateVariableIdentifier[] => {\n // The action is read from the template so its roles always belong to the given action identifier.\n const action = getTemplateActionOrThrow(template, actionIdentifier);\n\n // The requested variable identifiers are the intent generate list and the action role generate list.\n const requestedVariableIdentifiers: XOTemplateVariableIdentifier[] = [];\n\n // If an intent generate list is provided, include it in the requested variable identifiers.\n if (intentGenerate !== undefined) {\n requestedVariableIdentifiers.push(...intentGenerate);\n }\n\n // If a role identifier is provided, get the role definition.\n if (roleIdentifier !== undefined) {\n const role = action.roles?.[roleIdentifier];\n\n // If the role is not defined, throw an error.\n if (role === undefined) {\n throw new TemplateActionRoleNotFoundError(generateTemplateIdentifier(template), actionIdentifier, roleIdentifier);\n }\n\n // If the role has a generate list, include it in the requested variable identifiers.\n if (role.generate !== undefined) {\n requestedVariableIdentifiers.push(...role.generate);\n }\n }\n\n // Remove duplicates from the requested variable identifiers.\n const variableIdentifiers = [ ...new Set(requestedVariableIdentifiers) ];\n\n // The unsupported variable identifiers and types are collected.\n const unsupportedVariableIdentifiers: XOTemplateVariableIdentifier[] = [];\n const unsupportedVariableTypes: Array<string | undefined> = [];\n\n // For each variable, check if it is declared as a private key.\n for (const variableIdentifier of variableIdentifiers) {\n const variableType = template.variables?.[variableIdentifier]?.type;\n\n // If the variable is not declared as a private key, add it to the unsupported variable identifiers and types.\n if (variableType !== 'private_key') {\n unsupportedVariableIdentifiers.push(variableIdentifier);\n unsupportedVariableTypes.push(variableType);\n }\n }\n\n // If there are unsupported variable identifiers and types, throw an error.\n if (unsupportedVariableIdentifiers.length > 0) {\n throw new TemplateGeneratedVariableTypeUnsupportedError(\n generateTemplateIdentifier(template),\n actionIdentifier,\n unsupportedVariableIdentifiers,\n unsupportedVariableTypes,\n roleIdentifier,\n );\n }\n\n // Return the variable identifiers.\n return variableIdentifiers;\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { State, StoredCommitSecret } from '@xo-cash/state';\nimport type { XOTemplateIdentifier, XOTemplateVariableIdentifier } from '@xo-cash/types';\nimport type { AccountContext } from '../invitation/interfaces';\n\n/**\n * Returns the public key of a secret whose value is entropy. If the value is not entropy or the secret\n * doesn't exist, undefined is returned.\n *\n * @param {Pick<Required<AccountContext>, 'state' | 'crypto'>} context - State and signing for this account.\n * @param {string} secretLookupKey - Lookup key the secret is stored under.\n * @returns {Promise<string | undefined>} - The compressed public key as hex, or undefined when the secret holds no entropy.\n */\nexport const getSecretPublicKey = async (\n context: Pick<Required<AccountContext>, 'state' | 'crypto'>,\n secretLookupKey: string,\n): Promise<string | undefined> => {\n const secretData = await context.state.getSecretData(secretLookupKey);\n\n if (secretData === undefined) {\n return undefined;\n }\n\n // A value that is not entropy names no key to derive.\n if (secretData.isEntropy === false) {\n return undefined;\n }\n\n // The stored value is the derivation index the key was generated at under its template.\n const publicKey = context.crypto.derivePublicKey({\n templateIdentifier: secretData.templateIdentifier,\n derivationIndex: Number(secretData.value),\n });\n\n return binToHex(publicKey);\n};\n\n/**\n * Generates and stores private keys for template variables.\n *\n * Each key takes the next derivation index for the template. Only that index is stored, so the key itself is derived\n * again whenever it is used and never stored.\n *\n * @param {State} state - State that allocates derivation indexes and stores secrets for this account.\n * @param {XOTemplateIdentifier} templateIdentifier - Template that declares the variables, which scopes the derivation indexes.\n * @param {XOTemplateVariableIdentifier[]} variableIdentifiers - Private key variables to generate.\n * @returns {Promise<StoredCommitSecret[]>} - Each generated key with the lookup key its secret data is stored under.\n */\nexport const generateTemplatePrivateKeysData = async (\n state: State,\n templateIdentifier: XOTemplateIdentifier,\n variableIdentifiers: XOTemplateVariableIdentifier[],\n): Promise<StoredCommitSecret[]> => {\n const generatedSecrets: StoredCommitSecret[] = [];\n\n for (const variableIdentifier of variableIdentifiers) {\n // A fresh derivation index gives every generated key its own position in this template's key tree.\n const derivationIndex = await state.generateNextDerivativeIndex(templateIdentifier);\n\n // The secret data records the index under the variable name and its template so the key can be derived again for signing.\n const secretLookupKey = await state.storeSecretData({\n secretIdentifier: variableIdentifier,\n isPrivate: true,\n isEntropy: true,\n value: derivationIndex.toString(),\n templateIdentifier,\n });\n\n generatedSecrets.push({ secretIdentifier: variableIdentifier, secretLookupKey, templateIdentifier });\n }\n\n return generatedSecrets;\n};\n","import { SecretDataNotFoundError, type State, type StoredCommitSecret, type StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitationCommit, XOInvitationCommitIdentifier, XOInvitationIdentifier } from '@xo-cash/types';\nimport { scriptToScriptHash } from '@xo-cash/utils';\n\n/**\n * Finds the secrets this account introduced with a commit, keyed by that commit.\n *\n * When this account generates a locking script, it stores the lookup key of every secret used to build it with the\n * script hash. An output of the commit that is locked to such a script therefore leads to those secrets. Only scripts\n * the engine built for this invitation count. An output locked to one of this account's other scripts, such as an\n * existing address a participant supplied through a variable, introduces nothing, and outputs locked to anyone else\n * have no stored script hash at all.\n *\n * @param {State} state - State that stores this account's script hashes and secrets.\n * @param {XOInvitationCommit} commit - Commit this account is adding.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the commit belongs to.\n * @returns {Promise<Record<XOInvitationCommitIdentifier, StoredCommitSecret[]> | undefined>} - The commit's secrets, or\n * undefined when the commit introduces none.\n * @throws {@link SecretDataNotFoundError} - When a stored script hash lists a secret that is not in the secret store.\n */\nexport const listCommitSecrets = async (\n state: State,\n commit: XOInvitationCommit,\n invitationIdentifier: XOInvitationIdentifier,\n): Promise<Record<XOInvitationCommitIdentifier, StoredCommitSecret[]> | undefined> => {\n // A commit that adds no outputs introduces no secret through a locking script.\n if (commit.data.outputs === undefined) {\n return undefined;\n }\n\n const commitSecrets: StoredCommitSecret[] = [];\n const seenSecretLookupKeys = new Set<string>();\n\n for (const output of commit.data.outputs) {\n // An extension that only fills other fields of an earlier output carries no locking bytecode of its own.\n if (output.lockingBytecode === undefined) {\n continue;\n }\n\n const scriptHashData = await state.getScriptHashData(scriptToScriptHash(output.lockingBytecode));\n\n // A script this account did not generate, or one built without secrets, adds nothing.\n if (scriptHashData?.secrets === undefined) {\n continue;\n }\n\n // A script built outside this invitation already existed, so its secrets were not introduced here.\n if (scriptHashData.invitationIdentifier !== invitationIdentifier) {\n continue;\n }\n\n for (const secretLookupKey of scriptHashData.secrets) {\n // Two outputs can be locked to the same script, so each secret is listed once.\n if (seenSecretLookupKeys.has(secretLookupKey)) {\n continue;\n }\n\n const secretData = await state.getSecretData(secretLookupKey);\n\n // The script hash lists this secret, so a missing secret means the account storage is incomplete.\n if (secretData === undefined) {\n throw new SecretDataNotFoundError(secretLookupKey);\n }\n\n seenSecretLookupKeys.add(secretLookupKey);\n\n // A script's secrets are generated under the script's template, which their keys are derived with.\n commitSecrets.push({\n secretIdentifier: secretData.secretIdentifier,\n secretLookupKey,\n templateIdentifier: scriptHashData.templateIdentifier,\n });\n }\n }\n\n if (commitSecrets.length === 0) {\n return undefined;\n }\n\n return { [commit.commitIdentifier]: commitSecrets };\n};\n\n/**\n * Lists every secret this account introduced to an invitation, in the order its commits were recorded.\n *\n * @param {StoredInvitation} storedInvitation - Stored invitation whose recorded secrets are read.\n * @returns {StoredCommitSecret[]} - The recorded secrets, empty when the account introduced none.\n */\nexport const listInvitationSecrets = (storedInvitation: StoredInvitation): StoredCommitSecret[] => {\n const invitationSecrets: StoredCommitSecret[] = [];\n\n // An invitation this account introduced no secrets to holds none.\n if (storedInvitation.secretsByCommitIdentifier === undefined) {\n return invitationSecrets;\n }\n\n for (const commitSecrets of Object.values(storedInvitation.secretsByCommitIdentifier)) {\n invitationSecrets.push(...commitSecrets);\n }\n\n return invitationSecrets;\n};\n","import { generateRandomBytes } from '@bitauth/libauth';\nimport { COMMIT_IDENTIFIER_BYTE_LENGTH, CommitIdentifier, INVITATION_IDENTIFIER_BYTE_LENGTH, InvitationIdentifier } from '@xo-cash/primitives';\nimport type { XOInvitationCommitIdentifier, XOInvitationIdentifier } from '@xo-cash/types';\n\n/**\n * Generates a random invitation identifier from {@link INVITATION_IDENTIFIER_BYTE_LENGTH} random bytes.\n *\n * @returns {XOInvitationIdentifier} - The generated invitation identifier as a hex string.\n * @throws {@link InvitationIdentifierAllZeroesError} - If the random bytes are all zeroes.\n * @throws {@link InvitationIdentifierMaximumError} - If the random bytes are all 0xFF.\n * @throws {Error} - If {@link generateRandomBytes} rejects the environment cryptographically secure pseudo-random number generator.\n */\nexport const generateInvitationIdentifier = (): XOInvitationIdentifier => {\n const invitationIdentifier = new InvitationIdentifier(generateRandomBytes(INVITATION_IDENTIFIER_BYTE_LENGTH));\n\n return invitationIdentifier.toHex();\n};\n\n/**\n * Generates a random commit identifier from {@link COMMIT_IDENTIFIER_BYTE_LENGTH} random bytes.\n *\n * @returns {XOInvitationCommitIdentifier} - The generated commit identifier as a hex string.\n * @throws {@link CommitIdentifierAllZeroesError} - If the random bytes are all zeroes.\n * @throws {@link CommitIdentifierMaximumError} - If the random bytes are all 0xFF.\n * @throws {Error} - If {@link generateRandomBytes} rejects the environment cryptographically secure pseudo-random number generator.\n */\nexport const generateCommitIdentifier = (): XOInvitationCommitIdentifier => {\n const commitIdentifier = new CommitIdentifier(generateRandomBytes(COMMIT_IDENTIFIER_BYTE_LENGTH));\n\n return commitIdentifier.toHex();\n};\n","import type { HdKeyNetwork } from '@bitauth/libauth';\nimport { DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS, type XONetwork } from '../../defaults.ts';\nimport type {\n XOInvitation,\n XOInvitationCommit,\n XOInvitationCommitIdentifier,\n XOInvitationIdentifier,\n XOInvitationInput,\n XOInvitationOutput,\n XOInvitationResolution,\n XOInvitationResult,\n XOInvitationTransactionResult,\n XOInvitationVariable,\n XOTemplateActionIdentifier,\n XOTemplateIdentifier,\n XOTemplateRoleIdentifier,\n XOInvitationTransactionVersion,\n XOInvitationTransactionLocktime,\n XOInvitationTimestamp,\n XOTemplateTransactionIdentifier,\n} from '@xo-cash/types';\nimport { verifyInvitationTransactionBroadcastedResultSignature, verifyInvitationTransactionCreatedResultSignature } from '@xo-cash/crypto';\nimport {\n InvitationResultSignatureInvalidError,\n MergesWithCommitNotFoundError,\n TransactionResultAlreadyExistsError,\n TransactionResultNotFoundError,\n} from '../../errors/index.ts';\nimport { ExtendedPublicKey, SchnorrSignature, TemplateIdentifier, Timestamp, TransactionHash } from '@xo-cash/primitives';\nimport { resolveHdKeyNetwork } from '../../network/helper.ts';\nimport { generateCommitIdentifier, generateInvitationIdentifier } from '../helpers/identifiers.ts';\nimport type { InvitationParameters, InvitationTransactionBroadcastedResultInput, InvitationTransactionCreatedResultInput } from '../interfaces.ts';\n\n/**\n * Data an unsigned commit is created from.\n */\ntype UnsignedCommitParameters = {\n inputs?: XOInvitationInput[];\n outputs?: XOInvitationOutput[];\n variables?: XOInvitationVariable[];\n resolutions?: XOInvitationResolution[];\n roleIdentifier?: XOTemplateRoleIdentifier;\n transactionVersion?: XOInvitationTransactionVersion;\n transactionLocktime?: XOInvitationTransactionLocktime;\n expiresAtTimestamp?: XOInvitationTimestamp;\n};\n\n/**\n * Data a commit is created from, with its expiration set and the commit it follows.\n */\ntype CommitCreationParameters = Omit<UnsignedCommitParameters, 'expiresAtTimestamp'>\n & Required<Pick<UnsignedCommitParameters, 'expiresAtTimestamp'>> & { previousCommitIdentifier?: XOInvitationCommitIdentifier };\n\n/**\n * Builder for the XOInvitation\n */\nexport class InvitationBuilder {\n /**\n * The identifier of the current invitation.\n */\n public invitationIdentifier: XOInvitationIdentifier;\n\n /**\n * The identifier of the template for the invitation.\n */\n public templateIdentifier: XOTemplateIdentifier;\n\n /**\n * The identifier of the action for the invitation.\n */\n public actionIdentifier: XOTemplateActionIdentifier;\n\n /**\n * The timestamp when the invitation is created.\n */\n #createdAtTimestamp: number;\n\n /**\n * The commits in the invitation.\n */\n #commits: XOInvitationCommit[];\n\n /**\n * The result of the invitation process.\n */\n #result?: XOInvitationResult;\n\n /**\n * HD network for entity identifiers on this network.\n */\n readonly #hdKeyNetwork: HdKeyNetwork;\n\n /**\n * Create a new InvitationBuilder.\n * @param {InvitationParameters} params - Context for invitation creation.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n */\n constructor(params: InvitationParameters, network: XONetwork) {\n // Store the network encoding so entity identifier checks use xpub or tpub for this engine.\n this.#hdKeyNetwork = resolveHdKeyNetwork(network);\n const { templateIdentifier, actionIdentifier } = params;\n\n // Validate template identifier.\n new TemplateIdentifier(templateIdentifier);\n\n this.templateIdentifier = templateIdentifier;\n this.actionIdentifier = actionIdentifier;\n\n // Initialize the commits array.\n this.#commits = [];\n\n this.invitationIdentifier = generateInvitationIdentifier();\n\n // Assign the current timestamp when the invitation is created.\n this.#createdAtTimestamp = Date.now();\n }\n\n /**\n * Create a builder from an existing invitation.\n * @param {XOInvitation} invitation - An existing invitation.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @returns {InvitationBuilder} - A builder initialized from the invitation.\n */\n static fromInvitation(invitation: XOInvitation, network: XONetwork): InvitationBuilder {\n const builder = new InvitationBuilder(\n {\n templateIdentifier: invitation.templateIdentifier,\n actionIdentifier: invitation.actionIdentifier,\n },\n network,\n );\n\n builder.invitationIdentifier = invitation.invitationIdentifier;\n\n // Overwrite the created at timestamp\n builder.#createdAtTimestamp = invitation.createdAtTimestamp;\n\n // Overwrite the commits\n builder.#commits = [ ...invitation.commits ];\n\n builder.#result = invitation.result;\n\n return builder;\n }\n\n /**\n * Build the invitation object to be shared.\n * @returns {XOInvitation} - The built invitation.\n */\n build(): XOInvitation {\n const invitation: XOInvitation = {\n invitationIdentifier: this.invitationIdentifier,\n templateIdentifier: this.templateIdentifier,\n actionIdentifier: this.actionIdentifier,\n createdAtTimestamp: this.#createdAtTimestamp,\n commits: this.#commits,\n };\n\n // The result is only set when present, because the invitation type rejects an optional field that holds undefined.\n if (this.#result !== undefined) {\n invitation.result = this.#result;\n }\n\n return invitation;\n }\n\n /**\n * Replaces the entire invitation result.\n *\n * @param {XOInvitationResult} result - Result to attach to the invitation.\n * @returns {this} - Builder instance for chaining.\n */\n setResult(result: XOInvitationResult): this {\n this.#result = result;\n\n return this;\n }\n\n /**\n * Returns the current invitation result, if any.\n *\n * @returns {XOInvitationResult | undefined} - Invitation result or undefined when no result is attached.\n */\n getResult(): XOInvitationResult | undefined {\n return this.#result;\n }\n\n /**\n * Removes one transaction result from the invitation result.\n *\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier to remove.\n * @returns {this} - Builder instance for chaining.\n */\n removeTransactionResult(transactionIdentifier: XOTemplateTransactionIdentifier): this {\n if (this.#result?.transactions?.[transactionIdentifier] === undefined) {\n return this;\n }\n\n const remainingTransactions = { ...this.#result.transactions };\n\n delete remainingTransactions[transactionIdentifier];\n\n const remainingDataEntries = this.#result.data === undefined ? [] : Object.keys(this.#result.data);\n\n if (Object.keys(remainingTransactions).length === 0) {\n if (remainingDataEntries.length === 0) {\n this.#result = undefined;\n\n return this;\n }\n\n this.#result = {\n ...this.#result,\n transactions: undefined,\n };\n\n return this;\n }\n\n this.#result = {\n ...this.#result,\n transactions: remainingTransactions,\n };\n\n return this;\n }\n\n /**\n * Adds one transaction result to the invitation result.\n *\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier for the action.\n * @param {InvitationTransactionCreatedResultInput} transactionResult - Transaction result payload to store.\n * @returns {this} - Builder instance for chaining.\n * @throws {@link TransactionResultAlreadyExistsError} - When a result already exists for this transaction identifier.\n * @throws {@link InvitationResultSignatureInvalidError} - When the created result signature does not verify.\n * @throws {Error} - When a present field fails {@link TransactionHash}, {@link Timestamp},\n * {@link ExtendedPublicKey}, or {@link SchnorrSignature} construction.\n */\n addTransactionCreatedResult(\n transactionIdentifier: XOTemplateTransactionIdentifier,\n transactionResult: InvitationTransactionCreatedResultInput,\n ): this {\n const { transactionHash, createdAtTimestamp, createdByEntityIdentifier, createdBySignature } = transactionResult;\n\n // Since the builder already has the transaction result added, throw if this function tried to update it.\n if (this.#result?.transactions?.[transactionIdentifier] !== undefined) {\n // Include invitation identifier so the error names the invitation and not only the transaction id.\n throw new TransactionResultAlreadyExistsError(this.invitationIdentifier, transactionIdentifier);\n }\n\n // Parse each field through primitives so malformed values fail before signature verification.\n new TransactionHash(transactionHash);\n new Timestamp(createdAtTimestamp);\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(createdByEntityIdentifier, this.#hdKeyNetwork);\n new SchnorrSignature(createdBySignature);\n\n const storedTransactionResult: XOInvitationTransactionResult = {\n transactionHash,\n createdAtTimestamp,\n createdByEntityIdentifier,\n createdBySignature,\n };\n\n const isCreatedSignatureValid = verifyInvitationTransactionCreatedResultSignature({\n invitationIdentifier: this.invitationIdentifier,\n transactionResult: storedTransactionResult,\n });\n\n if (isCreatedSignatureValid === false) {\n // Include invitation identifier so signature failures name the invitation and not only the transaction id.\n throw new InvitationResultSignatureInvalidError(this.invitationIdentifier, 'transaction_created', transactionIdentifier);\n }\n\n return this.#storeTransactionResult(transactionIdentifier, storedTransactionResult);\n }\n\n /**\n * Records broadcast metadata on an existing invitation transaction result.\n *\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier for the action.\n * @param {InvitationTransactionBroadcastedResultInput} transactionResult - Broadcast result fields to merge into the stored transaction result.\n * @returns {this} - Builder instance for chaining.\n * @throws {@link TransactionResultNotFoundError} - When no created transaction result exists for this identifier.\n * @throws {@link InvitationResultSignatureInvalidError} - When the broadcast result signature does not verify.\n * @throws {Error} - When a present field fails {@link Timestamp}, {@link ExtendedPublicKey}, or {@link SchnorrSignature} construction.\n */\n addTransactionBroadcastedResult(\n transactionIdentifier: XOTemplateTransactionIdentifier,\n transactionResult: InvitationTransactionBroadcastedResultInput,\n ): this {\n const { broadcastedAtTimestamp, broadcastedByEntityIdentifier, broadcastedBySignature } = transactionResult;\n const existingTransactionResult = this.#result?.transactions?.[transactionIdentifier];\n\n if (existingTransactionResult === undefined) {\n throw new TransactionResultNotFoundError(this.invitationIdentifier, transactionIdentifier);\n }\n\n // Parse each field through primitives so malformed values fail before signature verification.\n new Timestamp(broadcastedAtTimestamp);\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(broadcastedByEntityIdentifier, this.#hdKeyNetwork);\n new SchnorrSignature(broadcastedBySignature);\n\n const mergedTransactionResult = {\n ...existingTransactionResult,\n broadcastedAtTimestamp,\n broadcastedByEntityIdentifier,\n broadcastedBySignature,\n };\n\n const isBroadcastSignatureValid = verifyInvitationTransactionBroadcastedResultSignature({\n invitationIdentifier: this.invitationIdentifier,\n transactionResult: mergedTransactionResult,\n });\n\n if (isBroadcastSignatureValid === false) {\n throw new InvitationResultSignatureInvalidError(this.invitationIdentifier, 'transaction_broadcasted', transactionIdentifier);\n }\n\n return this.#storeTransactionResult(transactionIdentifier, mergedTransactionResult);\n }\n\n /**\n * Add a commit to the invitation.\n * @param {XOInvitationCommit} commit - The commit to add.\n * @returns {this} - The builder instance.\n */\n addCommit(commit: XOInvitationCommit): this {\n new SchnorrSignature(commit.signature);\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(commit.entityIdentifier, this.#hdKeyNetwork);\n\n this.#commits.push(commit);\n\n return this;\n }\n\n /**\n * Returns the commit identifier of the last commit in the invitation.\n * @returns {XOInvitationCommitIdentifier | undefined} - The last commit identifier, or undefined if there are no commits.\n */\n getLastCommitIdentifier(): XOInvitationCommitIdentifier | undefined {\n return this.#commits[this.#commits.length - 1]?.commitIdentifier;\n }\n\n /**\n * Returns the last commit in the invitation.\n * @returns {XOInvitationCommit | undefined} - The last commit, or undefined if there are no commits.\n */\n getLastCommit(): XOInvitationCommit | undefined {\n return this.#commits[this.#commits.length - 1];\n }\n\n /**\n * Creates an unsigned commit without adding it to the invitation.\n * This allows for atomic commit creation with signature.\n *\n * @param {object} params - Parameters for creating the commit.\n * @param {XOInvitationInput[]} [params.inputs] - Optional array of inputs to add.\n * @param {XOInvitationOutput[]} [params.outputs] - Optional array of outputs to add.\n * @param {XOInvitationVariable[]} [params.variables] - Optional array of variables to add.\n * @param {number} [params.transactionVersion] - Optional transaction version.\n * @param {number} [params.transactionLocktime] - Optional transaction locktime.\n * @param {number} [params.expiresAtTimestamp] - Optional expiration timestamp.\n * Defaults to now plus {@link DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS}.\n * @returns {Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'>} - The unsigned commit without signature.\n */\n createUnsignedCommit(params: UnsignedCommitParameters): Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'> {\n const { inputs, outputs, variables, resolutions, roleIdentifier, transactionVersion, transactionLocktime, expiresAtTimestamp } = params;\n\n if (inputs) {\n this.#validateMergesWithReferences(inputs);\n }\n\n if (outputs) {\n this.#validateMergesWithReferences(outputs);\n }\n\n // Create commit using private helper method\n return this.#createCommit({\n previousCommitIdentifier: this.getLastCommitIdentifier(),\n inputs,\n outputs,\n variables,\n resolutions,\n roleIdentifier,\n transactionVersion,\n transactionLocktime,\n expiresAtTimestamp: expiresAtTimestamp ?? Date.now() + DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS,\n });\n }\n\n /**\n * Creates a new commit from the provided data.\n *\n * @param {CommitCreationParameters} params - Commit fields, the previous commit identifier, and the expiration timestamp.\n * @returns {Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'>} - The commit before it is signed and given its entity.\n */\n #createCommit(params: CommitCreationParameters): Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'> {\n const data: XOInvitationCommit['data'] = {};\n\n // Variables, inputs, and outputs are only set when present, because the invitation type rejects an optional field that holds undefined.\n if (params.variables !== undefined && params.variables.length > 0) {\n data.variables = params.variables;\n }\n\n if (params.inputs !== undefined && params.inputs.length > 0) {\n data.inputs = params.inputs;\n }\n\n if (params.outputs !== undefined && params.outputs.length > 0) {\n data.outputs = params.outputs;\n }\n\n // Resolutions are only set when present, so a commit without them serializes and signs the same as before.\n if (params.resolutions !== undefined && params.resolutions.length > 0) {\n data.resolutions = params.resolutions;\n }\n\n // The role is only set when the entity takes one, so a commit without it serializes and signs the same as before.\n if (params.roleIdentifier !== undefined) {\n data.roleIdentifier = params.roleIdentifier;\n }\n\n if (params.transactionVersion !== undefined) {\n data.transactionVersion = params.transactionVersion;\n }\n\n if (params.transactionLocktime !== undefined) {\n data.transactionLocktime = params.transactionLocktime;\n }\n\n const commitIdentifier = generateCommitIdentifier();\n\n return {\n commitIdentifier,\n previousCommitIdentifier: params.previousCommitIdentifier,\n createdAtTimestamp: Date.now(),\n data,\n expiresAtTimestamp: params.expiresAtTimestamp,\n };\n }\n\n /**\n * Validates mergesWith references for inputs and outputs.\n *\n * @param {Array<{ mergesWith?: { commitIdentifier: XOInvitationCommitIdentifier } }>} items - Commit inputs or outputs that may reference\n * earlier commits.\n * @throws {@link MergesWithCommitNotFoundError} - When mergesWith points at an unknown commit.\n */\n #validateMergesWithReferences(items: Array<{ mergesWith?: { commitIdentifier: XOInvitationCommitIdentifier } }>): void {\n for (const item of items) {\n if (item.mergesWith !== undefined) {\n const parentCommit = this.#commits.find((commit) => commit.commitIdentifier === item.mergesWith?.commitIdentifier);\n if (!parentCommit) {\n throw new MergesWithCommitNotFoundError(this.invitationIdentifier, item.mergesWith.commitIdentifier);\n }\n }\n }\n }\n\n /**\n * Stores a transaction result under its template transaction identifier, keeping every other result.\n *\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier for the action.\n * @param {XOInvitationTransactionResult} transactionResult - Transaction result to store.\n * @returns {this} - Builder instance for chaining.\n */\n #storeTransactionResult(transactionIdentifier: XOTemplateTransactionIdentifier, transactionResult: XOInvitationTransactionResult): this {\n const updatedResult: XOInvitationResult = this.#result ?? {};\n\n // Replace only this transaction's result, so results recorded for other transactions and data stay.\n this.#result = {\n ...updatedResult,\n transactions: {\n ...(updatedResult.transactions ?? {}),\n [transactionIdentifier]: transactionResult,\n },\n };\n\n return this;\n }\n}\n","import type { XOTemplateActionIdentifier, XOTemplateIdentifier, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport { TemplateIdentifier } from '@xo-cash/primitives';\nimport { InvitationIntentMismatchError, InvitationRoleDuplicatedError } from '../../errors/index.ts';\nimport type { InvitationCreationParameters } from '../interfaces.ts';\n\n/**\n * Resolves the role this account takes, and checks that an intent passed with it belongs to the invitation.\n *\n * An intent is built by the caller, so it is checked against the invitation rather than trusted. It must be for the\n * invitation's template and action. The role comes from the intent when it names one, otherwise from the role given\n * directly, and giving it in both places is refused.\n *\n * @param {Pick<InvitationCreationParameters, 'intent' | 'roleIdentifier'>} parameters - Intent and role the caller gave.\n * @param {XOTemplateIdentifier} templateIdentifier - Template of the invitation.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action of the invitation.\n * @returns {XOTemplateRoleIdentifier | undefined} - Role this account takes, or undefined when none was given.\n * @throws {@link InvitationIntentMismatchError} - When the intent names another template or action.\n * @throws {@link InvitationRoleDuplicatedError} - When the role is given both directly and on the intent.\n */\nexport const resolveParticipationRole = (\n parameters: Pick<InvitationCreationParameters, 'intent' | 'roleIdentifier'>,\n templateIdentifier: XOTemplateIdentifier,\n actionIdentifier: XOTemplateActionIdentifier,\n): XOTemplateRoleIdentifier | undefined => {\n const { intent, roleIdentifier } = parameters;\n\n // Without an intent the role, if any, is the one given directly.\n if (intent === undefined) {\n return roleIdentifier;\n }\n\n // An intent for another template lists that template's variables, so it cannot generate keys for this one.\n if (intent.templateIdentifier !== undefined) {\n const invitationTemplateIdentifier = new TemplateIdentifier(templateIdentifier);\n const intentTemplateIdentifier = new TemplateIdentifier(intent.templateIdentifier);\n\n if (intentTemplateIdentifier.equals(invitationTemplateIdentifier) === false) {\n throw new InvitationIntentMismatchError('templateIdentifier', invitationTemplateIdentifier.toHex(), intentTemplateIdentifier.toHex());\n }\n }\n\n if (intent.action !== actionIdentifier) {\n throw new InvitationIntentMismatchError('action', actionIdentifier, intent.action);\n }\n\n if (intent.role === undefined) {\n return roleIdentifier;\n }\n\n // Two sources for the role could disagree, so only one may name it.\n if (roleIdentifier !== undefined) {\n throw new InvitationRoleDuplicatedError(roleIdentifier, intent.role);\n }\n\n return intent.role;\n};\n","import type { XOInvitationCommit, XOInvitationResolution, XOInvitationResolutionIdentifier } from '@xo-cash/types';\n\n/**\n * Collects the resolutions every commit of an invitation provides in its commit data, keyed by the key operation.\n *\n * These are the public keys and data signatures participants shared. When two commits resolve one operation, the\n * earlier value is kept, the same way an earlier commit's input and output fields are kept.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @returns {Record<XOInvitationResolutionIdentifier, Uint8Array>} - The resolved value of each key operation.\n */\nexport const listInvitationResolutions = (commits: readonly XOInvitationCommit[]): Record<XOInvitationResolutionIdentifier, Uint8Array> => {\n const resolvedValues: Record<XOInvitationResolutionIdentifier, Uint8Array> = {};\n\n for (const commit of commits) {\n for (const resolution of commit.data.resolutions ?? []) {\n // The first commit to resolve an operation owns its value.\n if (resolvedValues[resolution.resolutionIdentifier] !== undefined) {\n continue;\n }\n\n resolvedValues[resolution.resolutionIdentifier] = resolution.value;\n }\n }\n\n return resolvedValues;\n};\n\n/**\n * Combines two versions of one input's resolutions into one list.\n *\n * Each entity extends the input with its own resolutions, so the later list adds the operations the earlier list does\n * not resolve. An operation both lists resolve keeps the earlier value.\n *\n * @param {XOInvitationResolution[]} earlierResolutions - Resolutions of the earlier version.\n * @param {XOInvitationResolution[]} laterResolutions - Resolutions of the later version.\n * @returns {XOInvitationResolution[]} - Every operation either list resolves, earlier resolutions first.\n */\nexport const combineResolutions = (\n earlierResolutions: XOInvitationResolution[],\n laterResolutions: XOInvitationResolution[],\n): XOInvitationResolution[] => {\n const combinedResolutions: XOInvitationResolution[] = [ ...earlierResolutions ];\n const resolvedIdentifiers = new Set<XOInvitationResolutionIdentifier>();\n\n for (const earlierResolution of earlierResolutions) {\n resolvedIdentifiers.add(earlierResolution.resolutionIdentifier);\n }\n\n for (const laterResolution of laterResolutions) {\n // An operation the earlier version already resolves keeps that value.\n if (resolvedIdentifiers.has(laterResolution.resolutionIdentifier)) {\n continue;\n }\n\n resolvedIdentifiers.add(laterResolution.resolutionIdentifier);\n combinedResolutions.push(laterResolution);\n }\n\n return combinedResolutions;\n};\n","import type { XOInvitationCommitIdentifier, XOInvitationCommit, XOInvitationIdentifier } from '@xo-cash/types';\nimport {\n CommitChainOrderInvalidError,\n CommitIdentifierDuplicatedError,\n CommitItemNotFoundError,\n MergesWithCommitNotEarlierError,\n MergesWithCommitNotFoundError,\n ParentCommitNotFoundError,\n} from '../../errors/index.ts';\nimport { combineResolutions } from '../../resolutions/combine.ts';\nimport type {\n MergeItemType,\n MergeableItem,\n CommittedItem,\n MergeChain,\n MergeChainLookup,\n MergedItemWithIntroductionOrder,\n SourcedMergedItem,\n} from './types.ts';\n\n/**\n * Validates that the commits form one chain in stored order and returns the position of each commit.\n *\n * Merging treats a commit stored earlier as authoritative over a commit stored later. That only holds when stored\n * order and the previous commit links agree, so every commit must name the commit stored immediately before it.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @returns {Map<XOInvitationCommitIdentifier, number>} - Position of each commit in the chain.\n * @throws {@link CommitIdentifierDuplicatedError} - When a commit identifier appears more than once.\n * @throws {@link ParentCommitNotFoundError} - When a commit names a previous commit that is not in the invitation.\n * @throws {@link CommitChainOrderInvalidError} - When a commit names a previous commit other than the one stored before it.\n */\nexport const validateCommitChain = (commits: readonly XOInvitationCommit[]): Map<XOInvitationCommitIdentifier, number> => {\n const commitPositionByIdentifier = new Map<XOInvitationCommitIdentifier, number>();\n const duplicatedCommitIdentifiers: XOInvitationCommitIdentifier[] = [];\n\n // Positions are recorded first so a previous commit link can be checked against every commit.\n for (const [ commitPosition, commit ] of commits.entries()) {\n if (commitPositionByIdentifier.has(commit.commitIdentifier)) {\n duplicatedCommitIdentifiers.push(commit.commitIdentifier);\n\n continue;\n }\n\n commitPositionByIdentifier.set(commit.commitIdentifier, commitPosition);\n }\n\n // Every duplicate is reported together because each one hides the items of the other copy.\n if (duplicatedCommitIdentifiers.length > 0) {\n throw new CommitIdentifierDuplicatedError(duplicatedCommitIdentifiers);\n }\n\n for (const [ commitPosition, commit ] of commits.entries()) {\n const { previousCommitIdentifier } = commit;\n\n // A link to a commit that is not in the invitation is reported as missing rather than as out of order.\n const isPreviousCommitMissing = previousCommitIdentifier !== undefined && commitPositionByIdentifier.has(previousCommitIdentifier) === false;\n\n if (isPreviousCommitMissing) {\n throw new ParentCommitNotFoundError(previousCommitIdentifier, commit.commitIdentifier);\n }\n\n // The first commit has no previous commit, and every later commit links to the one stored right before it.\n let expectedPreviousCommitIdentifier: XOInvitationCommitIdentifier | undefined;\n\n if (commitPosition > 0) {\n expectedPreviousCommitIdentifier = commits[commitPosition - 1].commitIdentifier;\n }\n\n if (previousCommitIdentifier !== expectedPreviousCommitIdentifier) {\n throw new CommitChainOrderInvalidError(commit.commitIdentifier, expectedPreviousCommitIdentifier, previousCommitIdentifier);\n }\n }\n\n return commitPositionByIdentifier;\n};\n\n/**\n * Lists every input or every output in commit order, together with the commit and position that supplied it.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @param {(commit: XOInvitationCommit) => Item[] | undefined} readCommitItems - Reads the inputs or the outputs of one commit.\n * @returns {Array<CommittedItem<Item>>} - Committed inputs or outputs in commit order.\n */\nexport const listCommittedItems = <Item extends MergeableItem>(\n commits: readonly XOInvitationCommit[],\n readCommitItems: (commit: XOInvitationCommit) => Item[] | undefined,\n): Array<CommittedItem<Item>> => {\n const committedItems: Array<CommittedItem<Item>> = [];\n\n for (const [ commitPosition, commit ] of commits.entries()) {\n const commitItems = readCommitItems(commit);\n\n // A commit that only adds other data has none of these items to list.\n if (commitItems === undefined) {\n continue;\n }\n\n // Commit order is kept because the funding introduction order is read from it.\n for (const [ itemIndex, item ] of commitItems.entries()) {\n committedItems.push({\n item,\n commitIdentifier: commit.commitIdentifier,\n commitPosition,\n itemIndex,\n itemKey: `${commit.commitIdentifier}:${String(itemIndex)}`,\n });\n }\n }\n\n return committedItems;\n};\n\n/**\n * Indexes committed items by the key that mergesWith references resolve to.\n *\n * @param {Array<CommittedItem<Item>>} committedItems - Committed inputs or outputs.\n * @returns {Map<string, CommittedItem<Item>>} - Committed items keyed by commit identifier and position.\n */\nexport const indexCommittedItemsByKey = <Item extends MergeableItem>(\n committedItems: Array<CommittedItem<Item>>,\n): Map<string, CommittedItem<Item>> => {\n const committedItemsByKey = new Map<string, CommittedItem<Item>>();\n\n // A mergesWith reference names a commit and a position, so the chain walk can look the target up directly.\n for (const committedItem of committedItems) {\n committedItemsByKey.set(committedItem.itemKey, committedItem);\n }\n\n return committedItemsByKey;\n};\n\n/**\n * Collects the keys of items that a later commit extends.\n *\n * An extended item is an intermediate version. Emitting it next to its extension would list one logical item twice\n * and make both claim the same transactionIndex.\n *\n * @param {Array<CommittedItem<Item>>} committedItems - Committed inputs or outputs.\n * @returns {Set<string>} - Keys of every item some commit extends.\n */\nconst listExtendedItemKeys = <Item extends MergeableItem>(committedItems: Array<CommittedItem<Item>>): Set<string> => {\n const extendedItemKeys = new Set<string>();\n\n for (const committedItem of committedItems) {\n const { mergesWith } = committedItem.item;\n\n // A funding item extends nothing.\n if (mergesWith === undefined) {\n continue;\n }\n\n extendedItemKeys.add(`${mergesWith.commitIdentifier}:${String(mergesWith.itemIndex)}`);\n }\n\n return extendedItemKeys;\n};\n\n/**\n * Numbers the funding items in the order commits introduced them.\n *\n * @param {Array<CommittedItem<Item>>} committedItems - Committed inputs or outputs in commit order.\n * @returns {Map<string, number>} - Introduction order keyed by funding item key.\n */\nconst assignFundingIntroductionOrder = <Item extends MergeableItem>(committedItems: Array<CommittedItem<Item>>): Map<string, number> => {\n const introductionOrderByFundingKey = new Map<string, number>();\n let nextIntroductionOrder = 0;\n\n for (const committedItem of committedItems) {\n // Only funding items are numbered. An extension takes the number of the funding item it grew from.\n if (committedItem.item.mergesWith !== undefined) {\n continue;\n }\n\n introductionOrderByFundingKey.set(committedItem.itemKey, nextIntroductionOrder);\n nextIntroductionOrder += 1;\n }\n\n return introductionOrderByFundingKey;\n};\n\n/**\n * Walks one leaf item back through mergesWith to the funding item that introduced it.\n *\n * Every reference must point at a commit stored earlier than the one that holds it. Each step therefore moves to an\n * earlier commit, so the walk always ends and references can never form a loop.\n *\n * @param {CommittedItem<Item>} leafItem - Item that no later commit extends.\n * @param {MergeChainLookup<Item>} mergeChainLookup - Invitation, committed items, commit positions, and the item type for this walk.\n * @returns {MergeChain<Item>} - Funding item and the extensions that lead to the leaf.\n * @throws {@link MergesWithCommitNotFoundError} - When a reference names a commit that is not in the invitation.\n * @throws {@link MergesWithCommitNotEarlierError} - When a reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When the referenced commit has no item at the referenced index.\n */\nexport const buildMergeChain = <Item extends MergeableItem>(\n leafItem: CommittedItem<Item>,\n mergeChainLookup: MergeChainLookup<Item>,\n): MergeChain<Item> => {\n const { invitationIdentifier, committedItemsByKey, commitPositionByIdentifier, itemType } = mergeChainLookup;\n\n // Extensions are found from the leaf backwards and reversed at the end so combining starts at the funding item.\n const extensionsFromLeaf: Array<CommittedItem<Item>> = [];\n let currentItem = leafItem;\n\n while (currentItem.item.mergesWith !== undefined) {\n const { mergesWith } = currentItem.item;\n const referencedCommitPosition = commitPositionByIdentifier.get(mergesWith.commitIdentifier);\n\n // The referenced commit is checked first so a missing commit is reported apart from a missing item.\n if (referencedCommitPosition === undefined) {\n throw new MergesWithCommitNotFoundError(invitationIdentifier, mergesWith.commitIdentifier, currentItem.commitIdentifier);\n }\n\n // Earlier commits are authoritative, so an extension may only build on a commit stored before its own.\n if (referencedCommitPosition >= currentItem.commitPosition) {\n throw new MergesWithCommitNotEarlierError(mergesWith.commitIdentifier, currentItem.commitIdentifier);\n }\n\n const referencedItem = committedItemsByKey.get(`${mergesWith.commitIdentifier}:${String(mergesWith.itemIndex)}`);\n\n // The referenced commit exists but has no item at the referenced index.\n if (referencedItem === undefined) {\n throw new CommitItemNotFoundError(itemType, mergesWith.itemIndex, mergesWith.commitIdentifier);\n }\n\n extensionsFromLeaf.push(currentItem);\n currentItem = referencedItem;\n }\n\n // The walk stops at the first item without mergesWith, which is the funding item.\n return {\n fundingItem: currentItem,\n extensions: extensionsFromLeaf.reverse(),\n };\n};\n\n/**\n * Copies fields from a later version into an earlier one only where the earlier version has no value.\n *\n * This is the single rule that stops an extension from overwriting a committed value. Fields are read and written\n * through Reflect because the item types differ between inputs and outputs and neither type has a string index.\n * Resolutions are the one list that grows, since each participant adds its own, and an operation keeps its first value.\n *\n * @param {Item} earlierVersion - Version whose set fields must be kept.\n * @param {Item} laterVersion - Version that may supply fields the earlier version left empty.\n * @returns {Item} - Copy of the earlier version with its empty fields filled from the later version.\n */\nexport const fillEmptyFields = <Item extends MergeableItem>(earlierVersion: Item, laterVersion: Item): Item => {\n const filledVersion: Item = { ...earlierVersion };\n\n // Each entity extends the input with its own resolutions, so a later list adds the operations the earlier list lacks.\n if (earlierVersion.resolutions !== undefined && laterVersion.resolutions !== undefined) {\n filledVersion.resolutions = combineResolutions(earlierVersion.resolutions, laterVersion.resolutions);\n }\n\n for (const [ fieldName, laterValue ] of Object.entries(laterVersion)) {\n const earlierValue: unknown = Reflect.get(filledVersion, fieldName);\n\n // Only an empty field takes the later value, so nothing committed earlier is overwritten.\n const isFillable = earlierValue === undefined && laterValue !== undefined;\n\n if (isFillable) {\n Reflect.set(filledVersion, fieldName, laterValue);\n }\n }\n\n return filledVersion;\n};\n\n/**\n * Combines every version in a merge chain into one item.\n *\n * Versions are applied from the funding item to the leaf. Values from earlier commits stay authoritative and each\n * extension can only add what was still missing, such as unlocking bytecode.\n *\n * @param {MergeChain<Item>} mergeChain - Funding item and its extensions.\n * @returns {Item} - Combined item without a mergesWith reference.\n */\nconst combineMergeChain = <Item extends MergeableItem>(mergeChain: MergeChain<Item>): Item => {\n let combinedItem: Item = { ...mergeChain.fundingItem.item };\n\n for (const extension of mergeChain.extensions) {\n combinedItem = fillEmptyFields(combinedItem, extension.item);\n }\n\n // The reference only located the earlier version and is not part of the merged item.\n delete combinedItem.mergesWith;\n\n return combinedItem;\n};\n\n/**\n * Combines each committed input or output that no commit extends with the earlier versions it extends.\n *\n * @param {Array<CommittedItem<Item>>} committedItems - Committed inputs or outputs in commit order.\n * @param {ReadonlyMap<XOInvitationCommitIdentifier, number>} commitPositionByIdentifier - Position of each commit in the chain.\n * @param {MergeItemType} itemType - Whether the items are inputs or outputs.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation whose commits hold the items, named in errors.\n * @returns {Array<MergedItemWithIntroductionOrder<SourcedMergedItem<Item>>>} - Each combined item tagged with the leaf commit\n * that last wrote it, together with its funding introduction order.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an item that does not exist.\n */\nexport const combineCommittedItems = <Item extends MergeableItem>(\n committedItems: Array<CommittedItem<Item>>,\n commitPositionByIdentifier: ReadonlyMap<XOInvitationCommitIdentifier, number>,\n itemType: MergeItemType,\n invitationIdentifier: XOInvitationIdentifier,\n): Array<MergedItemWithIntroductionOrder<SourcedMergedItem<Item>>> => {\n // Only items that no commit extends become merged items. The extended ones are earlier versions of them.\n const extendedItemKeys = listExtendedItemKeys(committedItems);\n const introductionOrderByFundingKey = assignFundingIntroductionOrder(committedItems);\n const mergeChainLookup: MergeChainLookup<Item> = {\n invitationIdentifier,\n committedItemsByKey: indexCommittedItemsByKey(committedItems),\n commitPositionByIdentifier,\n itemType,\n };\n\n const combinedItemsWithIntroductionOrder: Array<MergedItemWithIntroductionOrder<SourcedMergedItem<Item>>> = [];\n\n for (const committedItem of committedItems) {\n if (extendedItemKeys.has(committedItem.itemKey)) {\n continue;\n }\n\n const mergeChain = buildMergeChain(committedItem, mergeChainLookup);\n const combinedItem = combineMergeChain(mergeChain);\n\n // Every funding item was numbered, so the fallback only covers the map lookup type.\n const introductionOrder = introductionOrderByFundingKey.get(mergeChain.fundingItem.itemKey) ?? introductionOrderByFundingKey.size;\n\n combinedItemsWithIntroductionOrder.push({\n // The leaf commit is the last commit that wrote this item.\n mergedItem: { ...combinedItem, sourceCommitIdentifier: committedItem.commitIdentifier },\n introductionOrder,\n });\n }\n\n return combinedItemsWithIntroductionOrder;\n};\n","import type { XOInvitation, XOInvitationCommitIdentifier, XOInvitationIdentifier } from '@xo-cash/types';\nimport { InvitationItemFieldConflictError, type InvitationItemFieldConflict } from '../../errors/index.ts';\nimport { buildMergeChain, indexCommittedItemsByKey, listCommittedItems, validateCommitChain } from '../merge/chain.ts';\nimport type { CommittedItem, MergeChainLookup, MergeItemType, MergeableItem } from '../merge/types.ts';\n\n/**\n * Tells whether a committed field value counts as not set.\n *\n * An empty unlocking script is the placeholder for an input that is not signed yet, so it counts as not set and a\n * later signature may still fill it.\n *\n * @param {string} fieldName - Name of the committed field.\n * @param {unknown} committedValue - Value the commit carries for that field.\n * @returns {boolean} - True when the field has no committed value.\n */\nconst isCommittedValueUnset = (fieldName: string, committedValue: unknown): boolean => {\n if (committedValue === undefined) {\n return true;\n }\n\n // Only the unlocking script uses an empty value as a stand in for a value that does not exist yet.\n const isEmptyUnlockingScript = fieldName === 'unlockingBytecode' && committedValue instanceof Uint8Array && committedValue.length === 0;\n\n return isEmptyUnlockingScript;\n};\n\n/**\n * Finds every field that a later commit sets after earlier commits already committed a value for it.\n *\n * Items are replayed in commit order. Every version of one input or output, including siblings that extend the same\n * funding item, is folded into one combined state. A later version may fill a field that is still unset, and may not\n * set a field that is already set, even to the same value.\n *\n * @param {Array<CommittedItem<Item>>} committedItems - Committed inputs or outputs in commit order.\n * @param {ReadonlyMap<XOInvitationCommitIdentifier, number>} commitPositionByIdentifier - Position of each commit in the chain.\n * @param {MergeItemType} itemType - Whether the items are inputs or outputs.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation whose commits hold the items, named in errors.\n * @returns {InvitationItemFieldConflict[]} - Every conflicting field, empty when no commit sets a committed field again.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an item that does not exist.\n */\nconst listCommittedFieldConflicts = <Item extends MergeableItem>(\n committedItems: Array<CommittedItem<Item>>,\n commitPositionByIdentifier: ReadonlyMap<XOInvitationCommitIdentifier, number>,\n itemType: MergeItemType,\n invitationIdentifier: XOInvitationIdentifier,\n): InvitationItemFieldConflict[] => {\n const mergeChainLookup: MergeChainLookup<Item> = {\n invitationIdentifier,\n committedItemsByKey: indexCommittedItemsByKey(committedItems),\n commitPositionByIdentifier,\n itemType,\n };\n\n // For each funding item, the value committed so far for every field and the commit that set it.\n const committedValuesByFundingKey = new Map<string, Map<string, { committedValue: unknown; commitIdentifier: XOInvitationCommitIdentifier }>>();\n const conflicts: InvitationItemFieldConflict[] = [];\n\n for (const committedItem of committedItems) {\n let fundingItemKey = committedItem.itemKey;\n\n // An extension belongs to the input or output its chain started from, and so does every sibling of it.\n if (committedItem.item.mergesWith !== undefined) {\n fundingItemKey = buildMergeChain(committedItem, mergeChainLookup).fundingItem.itemKey;\n }\n\n let committedValues = committedValuesByFundingKey.get(fundingItemKey);\n\n // A funding item comes before its extensions, so its first appearance creates the entry they later read.\n if (committedValues === undefined) {\n committedValues = new Map();\n committedValuesByFundingKey.set(fundingItemKey, committedValues);\n }\n\n for (const [ fieldName, laterValue ] of Object.entries(committedItem.item)) {\n // The reference only locates the earlier version, and an unset value changes nothing.\n if (fieldName === 'mergesWith' || isCommittedValueUnset(fieldName, laterValue)) {\n continue;\n }\n\n // Each entity adds its own resolutions to the list, so a longer list is not a changed value.\n if (fieldName === 'resolutions') {\n continue;\n }\n\n const earlierEntry = committedValues.get(fieldName);\n\n // The first commit to set a field owns its value.\n if (earlierEntry === undefined || isCommittedValueUnset(fieldName, earlierEntry.committedValue)) {\n committedValues.set(fieldName, { committedValue: laterValue, commitIdentifier: committedItem.commitIdentifier });\n\n continue;\n }\n\n // A field already set is owned by the commit that set it, so any later value for it is a conflict, the same value included.\n conflicts.push({\n itemType,\n fieldName,\n fundingItemKey,\n earlierCommitIdentifier: earlierEntry.commitIdentifier,\n laterCommitIdentifier: committedItem.commitIdentifier,\n });\n }\n }\n\n return conflicts;\n};\n\n/**\n * Checks that no commit changes a value an earlier commit already set on the same input or output.\n *\n * The merge keeps the earliest value and ignores a changed one, so a changed value never takes effect. Rejecting it\n * before the commit is stored surfaces the defect, and keeps an invitation free of commits whose values are ignored.\n * A later commit may still fill an unset field or repeat a value that is already set.\n *\n * @param {XOInvitation} invitation - Invitation whose commits are checked in stored order, including the commit being added.\n * @returns {void}\n * @throws {@link CommitIdentifierDuplicatedError} - When a commit identifier appears more than once.\n * @throws {@link ParentCommitNotFoundError} - When a commit names a previous commit that is not in the invitation.\n * @throws {@link CommitChainOrderInvalidError} - When a commit does not name the commit stored before it.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an item that does not exist.\n * @throws {@link InvitationItemFieldConflictError} - When any commit changes a value an earlier commit set.\n */\nexport const assertCommitsDoNotChangeCommittedFields = (invitation: XOInvitation): void => {\n const { invitationIdentifier, commits } = invitation;\n const commitPositionByIdentifier = validateCommitChain(commits);\n\n // Inputs and outputs are checked together so every conflict in the invitation is reported at once.\n const conflicts = [\n ...listCommittedFieldConflicts(\n listCommittedItems(commits, (commit) => commit.data.inputs),\n commitPositionByIdentifier,\n 'input',\n invitationIdentifier,\n ),\n ...listCommittedFieldConflicts(\n listCommittedItems(commits, (commit) => commit.data.outputs),\n commitPositionByIdentifier,\n 'output',\n invitationIdentifier,\n ),\n ];\n\n if (conflicts.length > 0) {\n throw new InvitationItemFieldConflictError(conflicts);\n }\n};\n","import type {\n XOInvitation,\n XOInvitationCommit,\n XOInvitationEntityIdentifier,\n XOTemplate,\n XOTemplateAction,\n XOTemplateRoleIdentifier,\n XOTemplateActionIdentifier,\n XOTemplateLockingScriptIdentifier,\n} from '@xo-cash/types';\nimport { getTemplateActionOrThrow } from '../../template.ts';\nimport { isCashAssemblyExpression } from '@xo-cash/utils';\n\n/**\n * Lists the roles a commit takes for its entity.\n *\n * A commit takes a role when it names the role in its data, or when it tags a variable, input, output, or resolution\n * with the role. This is the same rule the slot count of a role uses.\n *\n * @param {XOInvitationCommit} commit - Commit whose roles are read.\n * @returns {Set<XOTemplateRoleIdentifier>} - Every role the commit takes.\n */\nexport const listCommitRoleIdentifiers = (commit: XOInvitationCommit): Set<XOTemplateRoleIdentifier> => {\n const { variables, inputs, outputs, resolutions, roleIdentifier } = commit.data;\n const commitRoleIdentifiers = new Set<XOTemplateRoleIdentifier>();\n\n // The role a commit names is the one its entity joined with.\n if (roleIdentifier !== undefined) {\n commitRoleIdentifiers.add(roleIdentifier);\n }\n\n // A tagged item takes the role for the entity too, as it does in the slot count.\n for (const commitItem of [ ...(variables ?? []), ...(inputs ?? []), ...(outputs ?? []), ...(resolutions ?? []) ]) {\n if (commitItem.roleIdentifier !== undefined) {\n commitRoleIdentifiers.add(commitItem.roleIdentifier);\n }\n }\n\n return commitRoleIdentifiers;\n};\n\n/**\n * Reads the maximum number of entities each role of an action takes.\n *\n * @param {XOTemplateAction} action - Action whose participant slots are read.\n * @returns {Map<XOTemplateRoleIdentifier, number | undefined>} - Maximum per role. A role without a maximum, or one the action\n * lists no slots for, takes any number of entities.\n */\nexport const readRoleMaximumSlots = (action: XOTemplateAction): Map<XOTemplateRoleIdentifier, number | undefined> => {\n const roleMaximumSlots = new Map<XOTemplateRoleIdentifier, number | undefined>();\n\n for (const roleSlot of action.requirements?.participants ?? []) {\n roleMaximumSlots.set(roleSlot.role, roleSlot.slots.max);\n }\n\n return roleMaximumSlots;\n};\n\n/**\n * Records the roles one commit takes for its entity, in place.\n *\n * An entity that already holds a role keeps it, and a new entity takes a role only while one of its slots is free.\n *\n * @param {XOInvitationCommit} commit - Commit whose roles are taken.\n * @param {Map<XOTemplateRoleIdentifier, number | undefined>} roleMaximumSlots - Maximum entities per role.\n * @param {Map<XOTemplateRoleIdentifier, Set<XOInvitationEntityIdentifier>>} roleEntityIdentifiers - Entities holding each role so far.\n * @returns {void}\n */\nexport const takeCommitRoles = (\n commit: XOInvitationCommit,\n roleMaximumSlots: Map<XOTemplateRoleIdentifier, number | undefined>,\n roleEntityIdentifiers: Map<XOTemplateRoleIdentifier, Set<XOInvitationEntityIdentifier>>,\n): void => {\n for (const roleIdentifier of listCommitRoleIdentifiers(commit)) {\n const holderEntityIdentifiers = roleEntityIdentifiers.get(roleIdentifier) ?? new Set<XOInvitationEntityIdentifier>();\n const maximumSlots = roleMaximumSlots.get(roleIdentifier);\n const hasFreeSlot = maximumSlots === undefined || holderEntityIdentifiers.size < maximumSlots;\n\n // An entity that already holds the role keeps it, and a new one takes it only while a slot is free.\n if (holderEntityIdentifiers.has(commit.entityIdentifier) === false && hasFreeSlot) {\n holderEntityIdentifiers.add(commit.entityIdentifier);\n }\n\n roleEntityIdentifiers.set(roleIdentifier, holderEntityIdentifiers);\n }\n};\n\n/**\n * Lists the entities holding each role of an invitation's action.\n *\n * Roles are taken in commit order, by naming the role in the commit data or by tagging an item with it, and a role\n * holds at most the maximum number of entities its slots allow. This is who may provide each role's variables.\n *\n * @param {XOInvitation} invitation - Invitation whose commits take the roles.\n * @param {XOTemplate} template - Template that defines the invitation action and its slots.\n * @returns {Record<XOTemplateRoleIdentifier, XOInvitationEntityIdentifier[]>} - Entities holding each taken role, in the order they took it.\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the invitation action.\n */\nexport const listRoleHolderEntities = (\n invitation: XOInvitation,\n template: XOTemplate,\n): Record<XOTemplateRoleIdentifier, XOInvitationEntityIdentifier[]> => {\n const roleMaximumSlots = readRoleMaximumSlots(getTemplateActionOrThrow(template, invitation.actionIdentifier));\n const roleEntityIdentifiers = new Map<XOTemplateRoleIdentifier, Set<XOInvitationEntityIdentifier>>();\n\n for (const commit of invitation.commits) {\n takeCommitRoles(commit, roleMaximumSlots, roleEntityIdentifiers);\n }\n\n const roleHolderEntities: Record<XOTemplateRoleIdentifier, XOInvitationEntityIdentifier[]> = {};\n\n for (const [ roleIdentifier, holderEntityIdentifiers ] of roleEntityIdentifiers) {\n roleHolderEntities[roleIdentifier] = [ ...holderEntityIdentifiers ];\n }\n\n return roleHolderEntities;\n};\n\n/**\n * Lists the roles that have a follow up in the outputs an action produces.\n *\n * A locking script names, for each role it declares, what that role does with an output locked to it, such as the\n * state it saves, the actions it can take next, and how the output counts toward its balance. A role has a follow up\n * when the locking script of any output in the action's transaction declares it. An output whose locking script is a\n * CashAssembly expression declares no roles.\n *\n * @param {XOTemplate} template - Template that defines the action, its transaction, outputs, and locking scripts.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action whose produced outputs are read.\n * @returns {Set<XOTemplateRoleIdentifier>} - Roles declared by a locking script of the action's outputs.\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the action.\n */\nexport const listFollowUpRoleIdentifiers = (template: XOTemplate, actionIdentifier: XOTemplateActionIdentifier): Set<XOTemplateRoleIdentifier> => {\n const action = getTemplateActionOrThrow(template, actionIdentifier);\n const followUpRoleIdentifiers = new Set<XOTemplateRoleIdentifier>();\n\n // An action without a transaction produces no outputs.\n if (action.transaction === undefined) {\n return followUpRoleIdentifiers;\n }\n\n for (const transactionOutput of template.transactions?.[action.transaction]?.outputs ?? []) {\n const lockingScriptIdentifier = template.outputs?.[transactionOutput.output]?.lockingScript;\n\n if (lockingScriptIdentifier === undefined || isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n continue;\n }\n\n for (const roleIdentifier of Object.keys(template.lockingScripts?.[lockingScriptIdentifier]?.roles ?? {})) {\n followUpRoleIdentifiers.add(roleIdentifier);\n }\n }\n\n return followUpRoleIdentifiers;\n};\n\n/**\n * Finds the role an entity holds in an invitation that a locking script declares.\n *\n * An output added without a role is built for the role its entity already holds, when the output's locking script\n * declares exactly one of the entity's roles. That role decides the keys the script is built with and the follow up\n * stored for it.\n *\n * @param {XOInvitation} invitation - Invitation whose commits give the entity its roles.\n * @param {XOTemplate} template - Template that defines the invitation action and the locking script.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - Entity whose role is looked up.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script whose declared roles are read.\n * @returns {XOTemplateRoleIdentifier | undefined} - The one role the entity holds that the locking script declares, or undefined when\n * there is none or more than one.\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the invitation action.\n */\nexport const findEntityLockingScriptRole = (\n invitation: XOInvitation,\n template: XOTemplate,\n entityIdentifier: XOInvitationEntityIdentifier,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n): XOTemplateRoleIdentifier | undefined => {\n const roleHolderEntities = listRoleHolderEntities(invitation, template);\n const heldRoleIdentifiers: XOTemplateRoleIdentifier[] = [];\n\n for (const declaredRoleIdentifier of Object.keys(template.lockingScripts?.[lockingScriptIdentifier]?.roles ?? {})) {\n if (roleHolderEntities[declaredRoleIdentifier]?.includes(entityIdentifier) === true) {\n heldRoleIdentifiers.push(declaredRoleIdentifier);\n }\n }\n\n // Only a single matching role names the output's role without guessing between several.\n if (heldRoleIdentifiers.length !== 1) {\n return undefined;\n }\n\n return heldRoleIdentifiers[0];\n};\n","import type { XOInvitation, XOInvitationEntityIdentifier, XOTemplate, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport { EntityMultipleRolesWithFollowUpUnsupportedError, type EntityRolesMultipleEntry } from '../../errors/index.ts';\nimport { listCommitRoleIdentifiers, listFollowUpRoleIdentifiers } from '../helpers/roles.ts';\n\n/**\n * Checks that no entity in an invitation holds more than one role with a follow up.\n *\n * Any role identifier in a commit means its entity joins as that role, whether the commit names the role in its data\n * or tags a variable, input, output, or resolution with it. An entity may hold several roles, but at most one of them\n * may have a follow up in the outputs the action produces, so every produced output has one role that decides what\n * happens with it next.\n *\n * Allowing a single account to hold more than one role with a follow up is not supported yet.\n *\n * @param {XOInvitation} invitation - Invitation whose commits are checked, including the commits being added.\n * @param {XOTemplate} template - Template that defines the invitation action and the locking scripts of its outputs.\n * @returns {void}\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the invitation action.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - When an entity holds more than one role with a follow up.\n */\nexport const assertEntityFollowUpRoles = (invitation: XOInvitation, template: XOTemplate): void => {\n const followUpRoleIdentifiers = listFollowUpRoleIdentifiers(template, invitation.actionIdentifier);\n const followUpRoleIdentifiersByEntity = new Map<XOInvitationEntityIdentifier, XOTemplateRoleIdentifier[]>();\n\n for (const commit of invitation.commits) {\n const entityFollowUpRoleIdentifiers = followUpRoleIdentifiersByEntity.get(commit.entityIdentifier) ?? [];\n\n // Only roles with a follow up are counted, each once per entity, in the order the entity takes it.\n for (const commitRoleIdentifier of listCommitRoleIdentifiers(commit)) {\n const isFollowUpRole = followUpRoleIdentifiers.has(commitRoleIdentifier);\n const isNewFollowUpRole = isFollowUpRole && entityFollowUpRoleIdentifiers.includes(commitRoleIdentifier) === false;\n\n if (isNewFollowUpRole) {\n entityFollowUpRoleIdentifiers.push(commitRoleIdentifier);\n }\n }\n\n followUpRoleIdentifiersByEntity.set(commit.entityIdentifier, entityFollowUpRoleIdentifiers);\n }\n\n const entitiesWithMultipleFollowUpRoles: EntityRolesMultipleEntry[] = [];\n\n // Allowing a single account to hold more than one role with a follow up is not supported yet, so a second one is refused.\n for (const [ entityIdentifier, roleIdentifiers ] of followUpRoleIdentifiersByEntity) {\n if (roleIdentifiers.length > 1) {\n entitiesWithMultipleFollowUpRoles.push({ entityIdentifier, roleIdentifiers });\n }\n }\n\n // Every entity with more than one role with a follow up is reported together so all offending commits can be fixed at once.\n if (entitiesWithMultipleFollowUpRoles.length > 0) {\n throw new EntityMultipleRolesWithFollowUpUnsupportedError(entitiesWithMultipleFollowUpRoles);\n }\n};\n","import type { XOInvitation, XOInvitationEntityIdentifier, XOTemplate, XOTemplateRoleIdentifier, XOTemplateVariableIdentifier } from '@xo-cash/types';\nimport { RoleVariableEntityMismatchError, type RoleVariableEntityMismatch } from '../../errors/index.ts';\nimport { getTemplateActionOrThrow } from '../../template.ts';\nimport { readRoleMaximumSlots, takeCommitRoles } from '../helpers/roles.ts';\n\n/**\n * Checks that every variable of a role is provided by an entity holding that role.\n *\n * A variable belongs to the role it is tagged with. An untagged variable belongs to every role whose requirements in\n * the action list it. Roles are taken in commit order, and a role holds at most the maximum number of entities its\n * slots allow, so an entity that tries to take a full role does not hold it. A commit may provide a variable of a role\n * only when its entity holds one of the variable's roles. A variable that belongs to no role may be provided by anyone.\n *\n * @param {XOInvitation} invitation - Invitation whose commits are checked, including the commits being added.\n * @param {XOTemplate} template - Template that defines the invitation action, its roles, and their slots.\n * @returns {void}\n * @throws {@link TemplateActionNotFoundError} - When the template does not define the invitation action.\n * @throws {@link RoleVariableEntityMismatchError} - When a commit provides a variable of a role its entity does not hold.\n */\nexport const assertRoleVariablesProvidedByRoleEntities = (invitation: XOInvitation, template: XOTemplate): void => {\n const action = getTemplateActionOrThrow(template, invitation.actionIdentifier);\n const roleMaximumSlots = readRoleMaximumSlots(action);\n const variableRoleIdentifiers = new Map<XOTemplateVariableIdentifier, XOTemplateRoleIdentifier[]>();\n const roleEntityIdentifiers = new Map<XOTemplateRoleIdentifier, Set<XOInvitationEntityIdentifier>>();\n const mismatches: RoleVariableEntityMismatch[] = [];\n\n // The action's role requirements name the variables each role provides.\n for (const [ roleIdentifier, actionRole ] of Object.entries(action.roles ?? {})) {\n for (const variableIdentifier of actionRole.requirements?.variables ?? []) {\n variableRoleIdentifiers.set(variableIdentifier, [ ...(variableRoleIdentifiers.get(variableIdentifier) ?? []), roleIdentifier ]);\n }\n }\n\n for (const commit of invitation.commits) {\n // The commit's roles are taken before its variables are checked, so a variable that takes its own role is allowed.\n takeCommitRoles(commit, roleMaximumSlots, roleEntityIdentifiers);\n\n for (const variable of commit.data.variables ?? []) {\n let ownerRoleIdentifiers = variableRoleIdentifiers.get(variable.variableIdentifier) ?? [];\n\n // A tagged variable belongs to the role it names.\n if (variable.roleIdentifier !== undefined) {\n ownerRoleIdentifiers = [ variable.roleIdentifier ];\n }\n\n let isHeldByEntity = false;\n\n for (const ownerRoleIdentifier of ownerRoleIdentifiers) {\n const holderEntityIdentifiers = roleEntityIdentifiers.get(ownerRoleIdentifier);\n\n if (holderEntityIdentifiers?.has(commit.entityIdentifier) === true) {\n isHeldByEntity = true;\n }\n }\n\n // Only a variable of no role, or one of a role this entity holds, may be provided.\n const isAllowed = ownerRoleIdentifiers.length === 0 || isHeldByEntity;\n\n if (isAllowed === false) {\n mismatches.push({\n commitIdentifier: commit.commitIdentifier,\n entityIdentifier: commit.entityIdentifier,\n variableIdentifier: variable.variableIdentifier,\n roleIdentifiers: ownerRoleIdentifiers,\n });\n }\n }\n }\n\n // Every mismatch is reported together so all offending commits can be fixed at once.\n if (mismatches.length > 0) {\n throw new RoleVariableEntityMismatchError(mismatches);\n }\n};\n","import type { StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitation } from '@xo-cash/types';\nimport { parseInvitation } from '@xo-cash/utils';\nimport { listVariableIdentifiersToGenerate } from '../../template.ts';\nimport { generateTemplatePrivateKeysData } from '../../compilation/secrets.ts';\nimport { listCommitSecrets } from '../helpers/secrets.ts';\nimport type { AccountContext, InvitationAcceptanceParameters } from '../interfaces.ts';\nimport { InvitationBuilder } from './builder.ts';\nimport { resolveParticipationRole } from './role.ts';\nimport { assertCommitsDoNotChangeCommittedFields } from '../validation/committed-fields.ts';\nimport { assertEntityFollowUpRoles } from '../validation/follow-up-roles.ts';\nimport { assertRoleVariablesProvidedByRoleEntities } from '../validation/role-variables.ts';\n\n/**\n * Accepts an invitation, an entity accepts an invitation and becomes part of the invitation.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} receivedInvitation - The invitation to be accepted.\n * @param {InvitationAcceptanceParameters} [params] - Optional parameters for accepting the invitation, including the role or intent\n * this account acts on.\n * @returns {Promise<StoredInvitation>} - The accepted invitation as stored, including this account's entity identifier.\n * @throws {@link InvitationInvalidError} - If the invitation does not match the XOInvitation type.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link InvitationIntentMismatchError} - If the intent names another template or another action than the invitation.\n * @throws {@link InvitationRoleDuplicatedError} - If the role is given both directly and on the intent.\n * @throws {@link TemplateActionNotFoundError} - If the template does not define the invitation action.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n * @throws {@link InvitationValidationFailedError} - If invitation validation fails once implemented.\n * @throws {@link InvitationItemFieldConflictError} - If a received commit changes a value an earlier commit set.\n * @throws {@link RoleVariableEntityMismatchError} - If a commit provides a variable of a role its entity does not hold.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If a commit gives an entity more than one role with a follow up.\n * @throws {@link SecretDataNotFoundError} - If a script hash of this account lists a secret that is not stored.\n */\nexport const acceptInvitation = async (\n context: Required<AccountContext>,\n receivedInvitation: XOInvitation,\n params?: InvitationAcceptanceParameters,\n): Promise<StoredInvitation> => {\n const { state, crypto, network } = context;\n\n // The invitation is received from outside, parse and validate it.\n const invitation = parseInvitation(receivedInvitation);\n\n // Get the template from the store.\n const storedTemplate = await state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n const acceptanceParameters = params ?? {};\n const roleIdentifier = resolveParticipationRole(acceptanceParameters, invitation.templateIdentifier, invitation.actionIdentifier);\n\n const generatedVariableIdentifiers = listVariableIdentifiersToGenerate(\n template,\n invitation.actionIdentifier,\n roleIdentifier,\n acceptanceParameters.intent?.generate,\n );\n\n // Fetch the invitation from the store.\n const invitationFromStore = await state.getInvitation(invitation.invitationIdentifier);\n\n // If the invitation already exists in the store, return it.\n if (invitationFromStore !== undefined) {\n return invitationFromStore;\n }\n\n // Create an invitation builder from the existing invitation.\n const invitationBuilder = InvitationBuilder.fromInvitation(invitation, network);\n // The joining commit records the role this account takes, so other participants can see which roles are filled.\n const invitationCommit = invitationBuilder.createUnsignedCommit({ ...params, roleIdentifier });\n\n // The entity is accepting the invitation, so this is the first commit in the invitation for this entity.\n // This means that the commit identifier generated will also be the root commit identifier for the entity.\n const rootCommitIdentifier = invitationCommit.commitIdentifier;\n\n // Create an unsigned commit and sign it.\n const signedCommit = crypto.signInvitationCommitWithSchnorr({\n invitationCommit,\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the invitation builder.\n invitationBuilder.addCommit(signedCommit);\n\n // Build the invitation, i.e. make it an object.\n const acceptedInvitation = invitationBuilder.build();\n\n // A received commit that changes a value an earlier commit set is refused before the invitation is first stored.\n assertCommitsDoNotChangeCommittedFields(acceptedInvitation);\n\n // So is a variable provided for a role by an entity that does not hold it.\n assertRoleVariablesProvidedByRoleEntities(acceptedInvitation, template);\n\n // So is a commit that gives an entity a second role with a follow up.\n assertEntityFollowUpRoles(acceptedInvitation, template);\n\n // Store the invitation and entity identifier.\n const storedInvitation: StoredInvitation = {\n invitation: acceptedInvitation,\n entityIdentifier: signedCommit.entityIdentifier,\n };\n\n // Keys the intent and the role ask for are generated now and introduced with this account's first commit.\n const commitSecrets = await generateTemplatePrivateKeysData(state, invitation.templateIdentifier, generatedVariableIdentifiers);\n\n // Outputs of this account's commit locked to scripts it generated introduce their secrets with that commit too.\n const outputSecretsByCommitIdentifier = await listCommitSecrets(state, signedCommit, acceptedInvitation.invitationIdentifier);\n\n if (outputSecretsByCommitIdentifier !== undefined) {\n commitSecrets.push(...outputSecretsByCommitIdentifier[signedCommit.commitIdentifier]);\n }\n\n if (commitSecrets.length > 0) {\n storedInvitation.secretsByCommitIdentifier = { [signedCommit.commitIdentifier]: commitSecrets };\n }\n\n await state.storeNewInvitation(acceptedInvitation.invitationIdentifier, storedInvitation);\n\n // Return the invitation as stored, with the fields storage sets such as its timestamps.\n return state.getInvitationOrThrow(acceptedInvitation.invitationIdentifier);\n};\n","import type { StoredInvitation } from '@xo-cash/state';\nimport { listVariableIdentifiersToGenerate } from '../../template.ts';\nimport { generateTemplatePrivateKeysData } from '../../compilation/secrets.ts';\nimport { listCommitSecrets } from '../helpers/secrets.ts';\nimport type { AccountContext, InvitationCreationParameters } from '../interfaces.ts';\nimport { InvitationBuilder } from './builder.ts';\nimport { resolveParticipationRole } from './role.ts';\nimport { assertEntityFollowUpRoles } from '../validation/follow-up-roles.ts';\n\n/**\n * Creates an invitation that can be shared with other entities, user, application, etc.\n * Invitation is the fundamental communication unit in XO, all the interactions done using the\n * xo template are done using invitations.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {InvitationCreationParameters} params - The parameters for invitation creation, including the role or intent this account acts on.\n * @returns {Promise<StoredInvitation>} - The constructed invitation as stored, including this account's entity identifier.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n * @throws {@link InvitationIntentMismatchError} - If the intent names another template or action.\n * @throws {@link InvitationRoleDuplicatedError} - If the role is given both directly and on the intent.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n * @throws {@link UnspentOutputReservationExternalConflictError} - If a local outpoint is already reserved by another invitation.\n * @throws {@link UnspentOutputReservationInternalConflictError} - If a local outpoint is already reserved by this invitation.\n * @throws {@link SecretDataNotFoundError} - If a script hash of this account lists a secret that is not stored.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If the first commit gives this account more than one role with a follow up.\n * @todo Create an event for the new invitation and push it to the encryption server.\n * @todo Expire the invitation, remove it from storage after it expires, and emit an event for the expiration.\n * @todo Sync the invitation with the remote servers.\n */\nexport const createInvitation = async (context: Required<AccountContext>, params: InvitationCreationParameters): Promise<StoredInvitation> => {\n const { state, crypto, network } = context;\n\n // Get the template from the state.\n const storedTemplate = await state.getTemplateOrThrow(params.templateIdentifier);\n const template = storedTemplate.template;\n\n // The intent and the role decide which keys are generated. Both are checked before anything is signed or stored.\n const roleIdentifier = resolveParticipationRole(params, params.templateIdentifier, params.actionIdentifier);\n const generatedVariableIdentifiers = listVariableIdentifiersToGenerate(\n template,\n params.actionIdentifier,\n roleIdentifier,\n params.intent?.generate,\n );\n\n // Create an invitation builder\n const invitationBuilder = new InvitationBuilder(params, network);\n const invitationCommit = invitationBuilder.createUnsignedCommit({\n variables: params.variables,\n inputs: params.inputs,\n outputs: params.outputs,\n resolutions: params.resolutions,\n roleIdentifier,\n expiresAtTimestamp: params.expiresAtTimestamp,\n });\n\n // Generate the root commit identifier for the invitation. This commit is the first commit of the invitation for this\n // entity and hence it's also the root commit identifier.\n // The invitation when stored will also store this identifier to re-create the identity(extended public key) of the entity.\n const rootCommitIdentifier = invitationCommit.commitIdentifier;\n\n // Create an unsigned invitation commit and sign it.\n const signedCommit = crypto.signInvitationCommitWithSchnorr({\n invitationCommit,\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the builder.\n invitationBuilder.addCommit(signedCommit);\n\n // Build the invitation, i.e. make an object\n const invitation = invitationBuilder.build();\n\n // The first commit may name a role and tag items with roles, and an entity holds at most one role with a follow up.\n assertEntityFollowUpRoles(invitation, template);\n\n // Store the invitation and entity identifier\n const storedInvitation: StoredInvitation = {\n invitation,\n entityIdentifier: signedCommit.entityIdentifier,\n };\n\n // Keys the intent and the role ask for are generated now and introduced with this account's first commit.\n const commitSecrets = await generateTemplatePrivateKeysData(state, params.templateIdentifier, generatedVariableIdentifiers);\n\n // Outputs of this account's commit locked to scripts it generated introduce their secrets with that commit too.\n const outputSecretsByCommitIdentifier = await listCommitSecrets(state, signedCommit, invitation.invitationIdentifier);\n\n if (outputSecretsByCommitIdentifier !== undefined) {\n commitSecrets.push(...outputSecretsByCommitIdentifier[signedCommit.commitIdentifier]);\n }\n\n if (commitSecrets.length > 0) {\n storedInvitation.secretsByCommitIdentifier = { [signedCommit.commitIdentifier]: commitSecrets };\n }\n\n await state.storeNewInvitation(invitation.invitationIdentifier, storedInvitation);\n\n // Only a commit that adds inputs has outpoints of this account to reserve.\n if (params.inputs !== undefined) {\n await state.reserveOwnUnspentOutputsForInvitation(invitation.invitationIdentifier, params.inputs);\n }\n\n // Return the invitation as stored, with the fields storage sets such as its timestamps.\n return state.getInvitationOrThrow(invitation.invitationIdentifier);\n};\n","import type { XOInvitation, XOInvitationCommit, XOInvitationCommitIdentifier, XOInvitationEntityIdentifier } from '@xo-cash/types';\n\n/**\n * Comparison between the locally stored invitation and incoming shared invitation JSON.\n */\nexport type InvitationCommitHistoryComparison = {\n storedCommitCount: number;\n incomingCommitCount: number;\n sharedHistoryCommitCount: number;\n newCommitCount: number;\n newCommits: XOInvitationCommit[];\n historyConflictCommitIdentifier: XOInvitationCommitIdentifier | null;\n};\n\n/**\n * Compares stored and incoming commit chains for shared prefix history and appended commits.\n *\n * @param {XOInvitation} storedInvitation - Invitation currently in local storage.\n * @param {XOInvitation} incomingInvitation - Invitation from shared JSON or remote sync.\n * @returns {InvitationCommitHistoryComparison} - Diff of the shared commit prefix and the commits that were appended.\n */\nexport const compareInvitationCommitHistories = (\n storedInvitation: XOInvitation,\n incomingInvitation: XOInvitation,\n): InvitationCommitHistoryComparison => {\n const storedCommits = storedInvitation.commits;\n const incomingCommits = incomingInvitation.commits;\n let sharedHistoryCommitCount = 0;\n let historyConflictCommitIdentifier: XOInvitationCommitIdentifier | null = null;\n\n for (let commitIndex = 0; commitIndex < storedCommits.length; commitIndex++) {\n const storedCommit = storedCommits[commitIndex];\n const incomingCommit = incomingCommits[commitIndex];\n\n if (incomingCommit === undefined) {\n historyConflictCommitIdentifier = storedCommit.commitIdentifier;\n break;\n }\n\n if (incomingCommit.commitIdentifier !== storedCommit.commitIdentifier || incomingCommit.signature !== storedCommit.signature) {\n historyConflictCommitIdentifier = storedCommit.commitIdentifier;\n break;\n }\n\n sharedHistoryCommitCount++;\n }\n\n const newCommits = incomingCommits.slice(sharedHistoryCommitCount);\n\n return {\n storedCommitCount: storedCommits.length,\n incomingCommitCount: incomingCommits.length,\n sharedHistoryCommitCount,\n newCommitCount: newCommits.length,\n newCommits,\n historyConflictCommitIdentifier,\n };\n};\n\n/**\n * Finds the root commit identifier for a given entity in an invitation. The root commit is\n * the first commit the entity added to the invitation.\n *\n * @param {XOInvitation} invitation - The invitation whose commits are searched.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - The entity identifier to search for among the invitation commits.\n * @returns {XOInvitationCommitIdentifier | undefined} - The root commit identifier if the entity has a commit in the invitation, otherwise undefined.\n */\nexport const findRootCommitIdentifierInInvitation = (\n invitation: XOInvitation,\n entityIdentifier: XOInvitationEntityIdentifier,\n): XOInvitationCommitIdentifier | undefined => {\n // Find the root commit identifier for the entity by iterating through the commits.\n for (const commit of invitation.commits) {\n if (commit.entityIdentifier === entityIdentifier) {\n return commit.commitIdentifier;\n }\n }\n\n // If the root commit identifier is not found, return undefined.\n return undefined;\n};\n\n/**\n * Finds all commits in the invitation that were made by the specified entity.\n * The returned array preserves the original commit order.\n *\n * @param {XOInvitation} invitation - The invitation to examine.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - The entity whose commits should be returned.\n * @returns {XOInvitationCommit[]} - Commits that belong to the entity, in the order they appear in the invitation.\n */\nexport const listCommitsForEntity = (invitation: XOInvitation, entityIdentifier: XOInvitationEntityIdentifier): XOInvitationCommit[] => {\n return (invitation.commits ?? []).filter((commit) => commit.entityIdentifier === entityIdentifier);\n};\n","import { TransactionHash } from '@xo-cash/primitives';\nimport type { XOInvitation, XOInvitationInput } from '@xo-cash/types';\nimport { UnspentOutputReservationInternalConflictError } from '@xo-cash/state';\n\n/**\n * Each input that names a parent transaction and an output index spends that coin.\n * A transaction can spend a coin only once.\n * This check runs before those inputs are signed onto the invitation.\n * It rejects a coin already spent by an earlier commit, and a coin listed twice among the inputs being added.\n *\n * An input with `mergesWith` can supply the outpoint of the input it extends only when no earlier commit set it, so its\n * outpoint is checked like the outpoint of a new input.\n *\n * @param {XOInvitation} invitation - Invitation before the new inputs are added.\n * @param {XOInvitationInput[]} inputs - Inputs whose outpoints are checked for a repeated coin.\n * @throws {@link UnspentOutputReservationInternalConflictError} - When an outpoint would be spent twice.\n */\nexport const assertNoDuplicateOutpoints = (invitation: XOInvitation, inputs: XOInvitationInput[]): void => {\n // Coins already named by earlier commits are the spends these inputs must not repeat.\n const committedOutpointKeys = new Set<string>();\n\n for (const commit of invitation.commits) {\n for (const committedInput of commit.data.inputs ?? []) {\n if (committedInput.outpointTransactionHash === undefined || committedInput.outpointIndex === undefined) {\n // An input without both outpoint fields is not yet a spend.\n continue;\n }\n\n // Normalize through TransactionHash so hex and byte encodings compare as the same coin.\n const committedOutpointTransactionHash = new TransactionHash(committedInput.outpointTransactionHash).toHex();\n committedOutpointKeys.add(`${committedOutpointTransactionHash}:${String(committedInput.outpointIndex)}`);\n }\n }\n\n // Coins already listed among these inputs are tracked separately so a repeated coin is rejected before it is signed.\n const listedOutpointKeys = new Set<string>();\n\n for (const input of inputs) {\n if (input.outpointTransactionHash === undefined || input.outpointIndex === undefined) {\n // An input without both outpoint fields is not yet a spend.\n continue;\n }\n\n // Normalize through TransactionHash so this coin matches the keys collected from earlier commits.\n const outpointTransactionHash = new TransactionHash(input.outpointTransactionHash).toHex();\n const outpointKey = `${outpointTransactionHash}:${String(input.outpointIndex)}`;\n\n if (listedOutpointKeys.has(outpointKey) === true || committedOutpointKeys.has(outpointKey) === true) {\n // Refuse these inputs before they are signed, because the merged transaction can spend this coin only once.\n throw new UnspentOutputReservationInternalConflictError(outpointKey, invitation.invitationIdentifier);\n }\n\n // Remember the coin so a later input in this list cannot spend it again.\n listedOutpointKeys.add(outpointKey);\n }\n};\n","import type { StoredCommitSecret, StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitationCommitIdentifier } from '@xo-cash/types';\nimport { AppendInvitationParametersEmptyError, OutputLockingBytecodeNotProvidedError, RootCommitNotFoundError } from '../../errors/index.ts';\nimport { listCommitSecrets, listInvitationSecrets } from '../helpers/secrets.ts';\nimport { findRootCommitIdentifierInInvitation } from '../helpers/commits.ts';\nimport { assertNoDuplicateOutpoints } from '../helpers/outpoints.ts';\nimport type { AccountContext, AppendInvitationParameters } from '../interfaces.ts';\nimport { InvitationBuilder } from './builder.ts';\nimport { assertCommitsDoNotChangeCommittedFields } from '../validation/committed-fields.ts';\nimport { assertEntityFollowUpRoles } from '../validation/follow-up-roles.ts';\nimport { assertRoleVariablesProvidedByRoleEntities } from '../validation/role-variables.ts';\n\n/**\n * Ensures append parameters carry at least one appendable field so the engine never signs and stores a commit\n * that changes nothing.\n *\n * @param {AppendInvitationParameters} appendParameters - Append parameters checked for at least one field.\n * @returns {void}\n * @throws {@link AppendInvitationParametersEmptyError} - When every appendable field is omitted.\n */\nconst assertAppendInvitationParametersAreNotEmpty = (appendParameters: AppendInvitationParameters): void => {\n const appendableFieldPresenceFlags: boolean[] = [\n appendParameters.version !== undefined,\n appendParameters.locktime !== undefined,\n appendParameters.expiresAtTimestamp !== undefined,\n appendParameters.inputs !== undefined && appendParameters.inputs.length > 0,\n appendParameters.outputs !== undefined && appendParameters.outputs.length > 0,\n appendParameters.variables !== undefined && appendParameters.variables.length > 0,\n appendParameters.resolutions !== undefined && appendParameters.resolutions.length > 0,\n appendParameters.roleIdentifier !== undefined,\n ];\n const hasAtLeastOneAppendableField = appendableFieldPresenceFlags.includes(true);\n\n if (hasAtLeastOneAppendableField === false) {\n throw new AppendInvitationParametersEmptyError();\n }\n};\n\n/**\n * Applies an invitation append operation to a stored invitation. Signs a new commit using the\n * engine's own entity, persists the updated invitation to the store, and returns the result.\n *\n * @param {Required<AccountContext>} context - State, signing, network, and locking bytecode generation for this account.\n * @param {StoredInvitation} storedInvitation - The stored invitation to append to.\n * @param {AppendInvitationParameters} params - The parameters to append.\n * @param {StoredCommitSecret[]} [generatedSecrets] - Secrets generated for this commit, recorded as introduced by it.\n * @returns {Promise<StoredInvitation>} - The stored invitation after the new commit is persisted, including the local entity identifier.\n * @throws {@link AppendInvitationParametersEmptyError} - When every appendable field is omitted.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link UnspentOutputReservationInternalConflictError} - If an append reuses an outpoint already on this invitation.\n * @throws {@link InvitationItemFieldConflictError} - If the new commit changes a value an earlier commit set.\n * @throws {@link RoleVariableEntityMismatchError} - If the new commit provides a variable of a role its entity does not hold.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If the new commit gives this account more than one role with a follow up.\n * @throws {@link SecretDataNotFoundError} - If a script hash of this account lists a secret that is not stored.\n * @throws {@link RootCommitNotFoundError} - If the entity root commit is not in the stored invitation.\n * @throws {@link OutputLockingBytecodeNotProvidedError} - If an output names a template output but carries no locking bytecode.\n * @todo Verify whether an appended value is a CashAssembly evaluation, and require the provided value to equal the resolved value when it is.\n * @todo Create an event for the append, store it locally, and push it to the encryption server.\n * @todo Sync the updated invitation with the remote servers.\n */\nexport const applyInvitationAppend = async (\n context: Required<AccountContext>,\n storedInvitation: StoredInvitation,\n params: AppendInvitationParameters,\n generatedSecrets: StoredCommitSecret[] = [],\n): Promise<StoredInvitation> => {\n assertAppendInvitationParametersAreNotEmpty(params);\n\n // Find the root commit identifier for the entity from the stored invitation.\n const rootCommitIdentifier = findRootCommitIdentifierInInvitation(storedInvitation.invitation, storedInvitation.entityIdentifier);\n\n // If the root commit identifier is not found then it means that the invitation has not been accepted by the entity\n if (rootCommitIdentifier === undefined) {\n throw new RootCommitNotFoundError(storedInvitation.invitation.invitationIdentifier, storedInvitation.entityIdentifier);\n }\n\n // If new inputs are being provided to the invitation, then ensure that no duplicate outpoints are provided.\n if (params.inputs !== undefined) {\n assertNoDuplicateOutpoints(storedInvitation.invitation, params.inputs);\n }\n\n // If outputs are provided as part of the parameters then it means new outputs are to be added to the invitation\n // If only the identifier of the output is provided then the function will try to auto-generate the locking bytecode for the output\n // and store it in the state.\n if (params.outputs !== undefined) {\n // Ensure that the output's identifier mentioned are not duplicated.\n for (const output of params.outputs) {\n if (output.outputIdentifier !== undefined && output.lockingBytecode === undefined) {\n throw new OutputLockingBytecodeNotProvidedError(storedInvitation.invitation.invitationIdentifier, output.outputIdentifier);\n }\n }\n // Also ensure that the relevant flag is set to false if the mentioned lockingbytecode is not relevant to the role\n }\n\n // Create an invitation builder from the stored invitation.\n const invitationBuilder = InvitationBuilder.fromInvitation(storedInvitation.invitation, context.network);\n\n // Create an unsigned commit and sign it.\n const signedCommit = context.crypto.signInvitationCommitWithSchnorr({\n invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),\n invitationIdentifier: invitationBuilder.invitationIdentifier,\n rootCommitIdentifier,\n templateIdentifier: invitationBuilder.templateIdentifier,\n actionIdentifier: invitationBuilder.actionIdentifier,\n });\n\n // Add the signed commit to the builder.\n invitationBuilder.addCommit(signedCommit);\n\n const updatedInvitation = invitationBuilder.build();\n\n // Reject a commit that changes a value an earlier commit set before any output is reserved or the commit is stored.\n assertCommitsDoNotChangeCommittedFields(updatedInvitation);\n\n const storedTemplate = await context.state.getTemplateOrThrow(updatedInvitation.templateIdentifier);\n const template = storedTemplate.template;\n\n // Reject it too when it provides a variable for a role another entity holds.\n assertRoleVariablesProvidedByRoleEntities(updatedInvitation, template);\n\n // Reject it too when it gives this account a second role with a follow up.\n assertEntityFollowUpRoles(updatedInvitation, template);\n\n // Only a commit that adds inputs has outpoints of this account to reserve.\n if (params.inputs !== undefined) {\n await context.state.reserveOwnUnspentOutputsForInvitation(updatedInvitation.invitationIdentifier, params.inputs);\n }\n\n // Outputs of the new commit locked to scripts this account generated lead to the secrets used to build them.\n const outputSecretsByCommitIdentifier = await listCommitSecrets(context.state, signedCommit, updatedInvitation.invitationIdentifier);\n\n let addedSecretsByCommitIdentifier: Record<XOInvitationCommitIdentifier, StoredCommitSecret[]> | undefined;\n\n // Secrets generated for this commit are introduced by it.\n const addedSecrets: StoredCommitSecret[] = [ ...generatedSecrets ];\n\n if (outputSecretsByCommitIdentifier !== undefined) {\n const recordedSecretLookupKeys = new Set<string>();\n\n for (const recordedSecret of listInvitationSecrets(storedInvitation)) {\n recordedSecretLookupKeys.add(recordedSecret.secretLookupKey);\n }\n\n // A secret an earlier commit already introduced, such as a reused role key, is not introduced again by this commit.\n for (const outputSecret of outputSecretsByCommitIdentifier[signedCommit.commitIdentifier]) {\n if (recordedSecretLookupKeys.has(outputSecret.secretLookupKey) === false) {\n addedSecrets.push(outputSecret);\n }\n }\n }\n\n if (addedSecrets.length > 0) {\n addedSecretsByCommitIdentifier = { [signedCommit.commitIdentifier]: addedSecrets };\n }\n\n // Storage replaces only the shared invitation and adds the new commit's secrets, keeping this account's other fields.\n await context.state.updateInvitation(updatedInvitation.invitationIdentifier, updatedInvitation, addedSecretsByCommitIdentifier);\n\n // Return the invitation as stored, with the merged secrets and the time of this update.\n return context.state.getInvitationOrThrow(updatedInvitation.invitationIdentifier);\n};\n","import type { XOInvitation, XOTemplateAction, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport type { InvitationMissingParticipant } from '../interfaces.ts';\n\n/**\n * Counts the number of distinct entities that have filled a specific role in the invitation.\n * An entity is considered to have filled a role if any of its commits contain data\n * (variables, inputs, or outputs) associated with that role identifier.\n *\n * @param {XOInvitation} invitation - The invitation to examine.\n * @param {XOTemplateRoleIdentifier} roleIdentifier - The role identifier to count filled slots for.\n * @returns {number} - The number of unique entities that have contributed data for the specified role.\n * @todo Determine how an authorized entity joins the invitation process.\n */\nconst countFilledSlotsForRole = (invitation: XOInvitation, roleIdentifier: XOTemplateRoleIdentifier): number => {\n const entityIdentifiers = new Set<string>();\n\n for (const commit of invitation.commits ?? []) {\n const { variables, inputs, outputs, resolutions } = commit.data;\n\n // Check if any item in this commit is associated with the target role.\n // A public key resolution also counts, since a participant joining with a new key shares it under its role.\n // So does the role a commit records the entity taking, such as when it joins without any data.\n let hasRoleData = commit.data.roleIdentifier === roleIdentifier;\n for (const list of [ variables ?? [], inputs ?? [], outputs ?? [], resolutions ?? [] ]) {\n for (const item of list) {\n if (item.roleIdentifier === roleIdentifier) {\n hasRoleData = true;\n break;\n }\n }\n\n if (hasRoleData) {\n break;\n }\n }\n\n if (hasRoleData) {\n entityIdentifiers.add(commit.entityIdentifier);\n }\n }\n\n return entityIdentifiers.size;\n};\n\n/**\n * Lists role identifiers for roles that still have capacity for additional participants.\n * A role is considered available if the number of distinct entities that have filled it\n * is less than the role's maximum slot count. If max is undefined, the role has unlimited capacity.\n *\n * @param {XOInvitation} invitation - The invitation object to check for available roles.\n * @param {XOTemplateAction} action - The template action being analyzed to determine which roles are expected.\n * @returns {XOTemplateRoleIdentifier[]} - Role identifiers for roles that can still accept participants.\n * Returns an empty array if no roles are defined in the action.\n */\nexport const listAvailableRolesForInvitation = (invitation: XOInvitation, action: XOTemplateAction): XOTemplateRoleIdentifier[] => {\n const actionRoleSpecs = action.requirements?.participants ?? [];\n if (actionRoleSpecs.length === 0) return [];\n\n const availableRoleIdentifiers: XOTemplateRoleIdentifier[] = [];\n\n for (const roleSpec of actionRoleSpecs) {\n const roleIdentifier = roleSpec.role;\n const filledSlots = countFilledSlotsForRole(invitation, roleIdentifier);\n const maxSlots = roleSpec.slots?.max;\n\n // A role is available if it hasn't reached its maximum capacity (undefined max = unlimited).\n if (maxSlots === undefined || filledSlots < maxSlots) {\n availableRoleIdentifiers.push(roleIdentifier);\n }\n }\n\n return availableRoleIdentifiers;\n};\n\n/**\n * Lists the roles of an action that fewer entities have taken than the action requires.\n *\n * Each role in the action's participants needs at least its minimum number of entities before the action can\n * complete, so a role below its minimum is waiting for someone to join the invitation with it.\n *\n * @param {XOInvitation} invitation - The invitation whose participants are counted.\n * @param {XOTemplateAction} action - The template action that declares the participants.\n * @returns {InvitationMissingParticipant[]} - Every role below its minimum, in the order the action lists them.\n */\nexport const listMissingParticipants = (invitation: XOInvitation, action: XOTemplateAction): InvitationMissingParticipant[] => {\n const missingParticipants: InvitationMissingParticipant[] = [];\n\n for (const roleSlot of action.requirements?.participants ?? []) {\n const filledSlots = countFilledSlotsForRole(invitation, roleSlot.role);\n\n // A role at or above its minimum needs no one else to join.\n if (filledSlots < roleSlot.slots.min) {\n missingParticipants.push({\n roleIdentifier: roleSlot.role,\n filledSlots,\n minimumSlots: roleSlot.slots.min,\n maximumSlots: roleSlot.slots.max,\n });\n }\n }\n\n return missingParticipants;\n};\n","import type { StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitationIdentifier, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport { InvitationRoleUnavailableError } from '../../errors/index.ts';\nimport { getTemplateActionOrThrow, listVariableIdentifiersToGenerate } from '../../template.ts';\nimport { generateTemplatePrivateKeysData } from '../../compilation/secrets.ts';\nimport type { AccountContext } from '../interfaces.ts';\nimport { applyInvitationAppend } from './apply-append.ts';\nimport { listAvailableRolesForInvitation } from '../requirements/roles.ts';\n\n/**\n * Joins an invitation this account already takes part in with another role.\n *\n * The role must still have a free slot. The keys the role asks for are generated and introduced with the commit that\n * names the role, the same way they are when an account first joins with a role.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation to join with the role.\n * @param {XOTemplateRoleIdentifier} roleIdentifier - Role to take.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit that names the role.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n * @throws {@link InvitationRoleUnavailableError} - If the role has no free slot left.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If the role would give this account more than one role with a follow up.\n */\nexport const joinInvitationRole = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n roleIdentifier: XOTemplateRoleIdentifier,\n): Promise<StoredInvitation> => {\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n const { invitation } = storedInvitation;\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n const action = getTemplateActionOrThrow(template, invitation.actionIdentifier);\n const availableRoleIdentifiers = listAvailableRolesForInvitation(invitation, action);\n\n // A role at its maximum takes no more entities.\n if (availableRoleIdentifiers.includes(roleIdentifier) === false) {\n throw new InvitationRoleUnavailableError(invitationIdentifier, roleIdentifier, availableRoleIdentifiers);\n }\n\n // The keys the role asks for are generated before the commit, so a role the action does not define fails first.\n const generatedVariableIdentifiers = listVariableIdentifiersToGenerate(template, invitation.actionIdentifier, roleIdentifier, undefined);\n const commitSecrets = await generateTemplatePrivateKeysData(context.state, invitation.templateIdentifier, generatedVariableIdentifiers);\n\n // The commit names the role, and the generated keys are recorded as introduced by it.\n return applyInvitationAppend(context, storedInvitation, { roleIdentifier }, commitSecrets);\n};\n","import {\n createCompilerBch,\n type CompilationContextBch,\n type CompilationResultError,\n type CompilerBch,\n type CompilerConfiguration,\n type TransactionGenerationError,\n type WalletTemplateVariable,\n} from '@bitauth/libauth';\nimport { getTemplateLockingScriptOrThrow } from '../template.ts';\nimport {\n type XOTemplate,\n type XOTemplateLockingScriptIdentifier,\n type XOTemplateLockingType,\n type XOTemplateRoleIdentifier,\n type XOTemplateVariable,\n type XOTemplateVariableIdentifier,\n XOTemplatePrimitiveTypes,\n} from '@xo-cash/types';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport { TemplateLockingScriptBytecodeNotFoundError, TemplateLockingScriptTypeNotFoundError } from '../errors/index.ts';\n\n/**\n * Collapses a failed libauth compilation or transaction generation result into one string for typed engine errors.\n *\n * A compilation failure lists its compiler errors directly. A transaction generation failure lists one entry for each\n * failed input or output script, and each entry holds the compiler errors of that script, so those messages are\n * prefixed with the script type and index.\n *\n * @param {CompilationResultError<ProgramState> | TransactionGenerationError<ProgramState>} libauthResult - Failed libauth result.\n * @returns {string} - Every compiler error message, one per line.\n */\nexport const formatLibauthFailureReason = <ProgramState>(\n libauthResult: CompilationResultError<ProgramState> | TransactionGenerationError<ProgramState>,\n): string => {\n const errorMessages: string[] = [];\n\n for (const libauthError of libauthResult.errors) {\n // A transaction generation entry names the failed locking or unlocking script and holds its compiler errors.\n if ('type' in libauthError) {\n for (const compilationError of libauthError.errors) {\n errorMessages.push(`${libauthError.type} bytecode at index ${String(libauthError.index)}: ${compilationError.error}`);\n }\n\n continue;\n }\n\n // A compilation result entry is already a compiler error.\n errorMessages.push(libauthError.error);\n }\n\n return errorMessages.join('\\n');\n};\n\n/**\n * Creates a map of variable identifiers to role identifiers for the libauth compiler configuration.\n *\n * @param {XOTemplate} template - The template used to gather the variable identifiers.\n * @param {XOTemplateRoleIdentifier} roleIdentifier - The role identifier to assign to the variables.\n * @returns {Record<XOTemplateVariableIdentifier, XOTemplateRoleIdentifier>} - A map of variable identifiers to role identifiers.\n */\nconst buildEntityOwnershipForLibauthCompiler = (\n template: XOTemplate,\n roleIdentifier: XOTemplateRoleIdentifier,\n): Record<XOTemplateVariableIdentifier, XOTemplateRoleIdentifier> => {\n // Create a map of variable identifiers to role identifiers.\n const entityOwnershipMap: Record<XOTemplateVariableIdentifier, XOTemplateRoleIdentifier> = {};\n\n // Get the variable identifiers from the template.\n const variableIdentifiers = template.variables === undefined ? [] : Object.keys(template.variables);\n\n for (const variableIdentifier of variableIdentifiers) {\n entityOwnershipMap[variableIdentifier] = roleIdentifier;\n }\n\n return entityOwnershipMap;\n};\n\n/**\n * Collects every secret identifier declared on locking scripts and their roles.\n *\n * Template variable `type` is optional. Secrets listed under locking script state still identify\n * Key material for Libauth even when `private_key` was never stored on the variable.\n *\n * @param {XOTemplate} template - Template whose locking script secrets are read.\n * @returns {Set<string>} - Deduplicated secret identifiers from locking script state.\n */\nexport const listTemplateSecretIdentifiers = (template: XOTemplate): Set<string> => {\n const secretIdentifiers = new Set<string>();\n\n for (const lockingScriptDefinition of Object.values(template.lockingScripts ?? {})) {\n // Script level state may list secrets shared across roles on this lock.\n for (const secretIdentifier of lockingScriptDefinition.state?.secrets ?? []) {\n secretIdentifiers.add(secretIdentifier);\n }\n\n // Role state lists the Key identifiers each participant tracks for this lock.\n for (const roleDefinition of Object.values(lockingScriptDefinition.roles ?? {})) {\n for (const secretIdentifier of roleDefinition.state?.secrets ?? []) {\n secretIdentifiers.add(secretIdentifier);\n }\n }\n }\n\n return secretIdentifiers;\n};\n\n/**\n * Returns whether a template variable should compile as a Libauth Key.\n *\n * Prefers an explicit `private_key` type. Also treats locking script secrets as Key so older\n * stored templates without a type still unlock with `data.keys` instead of WalletData bytecode.\n *\n * @param {string} variableIdentifier - Variable or secret identifier.\n * @param {Set<string>} templateSecretIdentifiers - Secrets from {@link listTemplateSecretIdentifiers}.\n * @param {XOTemplateVariable} [variableDefinition] - Template variable when present.\n * @returns {boolean} - True when Libauth must resolve this identifier through private keys.\n */\nexport const isLibauthKeyTemplateVariable = (\n variableIdentifier: string,\n templateSecretIdentifiers: Set<string>,\n variableDefinition?: XOTemplateVariable,\n): boolean => {\n if (variableDefinition?.type === XOTemplatePrimitiveTypes.PRIVATE_KEY) {\n return true;\n }\n\n return templateSecretIdentifiers.has(variableIdentifier);\n};\n\n/**\n * Builds the Libauth compiler variable map for a template.\n *\n * Maps `private_key` variables and locking script secrets to Libauth Key. Other variables become\n * WalletData. Secrets missing from `variables` are still registered as Key so unlock compilation\n * can use derived private keys.\n *\n * @param {XOTemplate} template - Template whose variables and locking script secrets are mapped.\n * @returns {CompilerConfiguration['variables']} - Compiler variables keyed by identifier.\n */\nexport const buildLibauthCompilerVariables = (template: XOTemplate): CompilerConfiguration['variables'] => {\n // Initialize the variables with types.\n const variablesWithTypes: CompilerConfiguration['variables'] = {};\n const templateSecretIdentifiers = listTemplateSecretIdentifiers(template);\n\n // Get the variable entries from the template.\n const variableEntries: [XOTemplateVariableIdentifier, XOTemplateVariable][] =\n template.variables === undefined ? [] : Object.entries(template.variables);\n\n // Iterate over the variable entries and assign types to the variables.\n for (const [ variableIdentifier, variableDefinition ] of variableEntries) {\n // Prefer private_key type, then locking script secrets, otherwise WalletData.\n const variableType: 'Key' | 'WalletData' = isLibauthKeyTemplateVariable(variableIdentifier, templateSecretIdentifiers, variableDefinition) ? 'Key' : 'WalletData';\n\n // Create a typed variable definition with the type set.\n const typedVariableDefinition: WalletTemplateVariable = {\n ...variableDefinition,\n type: variableType,\n };\n variablesWithTypes[variableIdentifier] = typedVariableDefinition;\n }\n\n // Register secrets that never appeared under variables so Key compiles still resolve.\n for (const secretIdentifier of templateSecretIdentifiers) {\n if (variablesWithTypes[secretIdentifier] !== undefined) {\n continue;\n }\n\n variablesWithTypes[secretIdentifier] = {\n name: secretIdentifier,\n type: 'Key',\n };\n }\n\n return variablesWithTypes;\n};\n\n/**\n * Maps supported XO template locking types to the corresponding libauth compiler locking script type.\n */\nconst XO_LOCKING_TYPE_TO_LIBAUTH_MAP: Record<XOTemplateLockingType, 'p2sh20' | 'p2sh32' | 'standard'> = {\n p2s: 'standard',\n p2pkh: 'standard',\n p2sh: 'p2sh32',\n};\n\n/**\n * Builds the Libauth compiler for one template locking script.\n *\n * Locking and unlocking compiles share this configuration. The locking script identifier is the key Libauth uses for the locking type.\n * An unlocking script identifier is included when one is given or the locking script names one. A role adds entity ownership.\n *\n * @param {XOTemplate} template - Template that owns the locking script and its scripts.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script to compile or unlock.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role that owns the variables for this compile.\n * @param {string} [unlockingScriptIdentifier] - Unlocking script to use instead of the one the locking script names, such as the one a\n * template input names.\n * @returns {{\n * compiler: CompilerBch,\n * compilerConfiguration: CompilerConfiguration<CompilationContextBch>,\n * lockingScriptId: string,\n * lockingScriptType: XOTemplateLockingType,\n * unlockingScriptId?: string,\n * }} - Compiler, the configuration it was built from, the script identifiers, and the locking type. The configuration is\n * what {@link Crypto#compileScript} receives, and the crypto package builds its own compiler from it.\n * @throws {@link TemplateLockingScriptBytecodeNotFoundError} - When the locking script has no locking bytecode.\n * @throws {@link TemplateLockingScriptTypeNotFoundError} - When the locking script has no locking type.\n */\nexport const createLibauthCompilerForLockingScript = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n unlockingScriptIdentifier?: string,\n): {\n compiler: CompilerBch;\n compilerConfiguration: CompilerConfiguration<CompilationContextBch>;\n lockingScriptId: string;\n lockingScriptType: XOTemplateLockingType;\n unlockingScriptId?: string;\n} => {\n // Get the locking script from the template.\n const lockingScript = getTemplateLockingScriptOrThrow(template, lockingScriptIdentifier);\n\n // Get the locking script identifier from the locking script.\n const lockingScriptId = lockingScript.lockingBytecode;\n const lockingType = lockingScript.lockingType;\n let unlockingScriptId = lockingScript.unlockingBytecode;\n\n // A template input can name the unlocking script for the output it spends.\n if (unlockingScriptIdentifier !== undefined) {\n unlockingScriptId = unlockingScriptIdentifier;\n }\n\n // Libauth looks up the locking type by this script identifier, so an empty identifier cannot be a map key.\n if (lockingScriptId === undefined) {\n throw new TemplateLockingScriptBytecodeNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier);\n }\n\n if (lockingType === undefined) {\n throw new TemplateLockingScriptTypeNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier);\n }\n\n // Create the locking script types map.\n const lockingScriptTypes: CompilerConfiguration['lockingScriptTypes'] = {\n [lockingScriptId]: XO_LOCKING_TYPE_TO_LIBAUTH_MAP[lockingType],\n };\n\n const compilerContext: CompilerConfiguration<CompilationContextBch> = {\n scripts: template.scripts,\n variables: buildLibauthCompilerVariables(template),\n lockingScriptTypes,\n };\n\n if (unlockingScriptId !== undefined) {\n // Create the unlocking scripts map.\n const unlockingScripts: CompilerConfiguration['unlockingScripts'] = {\n [unlockingScriptId]: lockingScriptId,\n };\n\n compilerContext.unlockingScripts = unlockingScripts;\n }\n\n // Create the entity ownership map.\n let entityOwnership: CompilerConfiguration['entityOwnership'] | undefined;\n\n // A role tells Libauth which variables that participant owns.\n if (roleIdentifier !== undefined) {\n entityOwnership = buildEntityOwnershipForLibauthCompiler(template, roleIdentifier);\n compilerContext.entityOwnership = entityOwnership;\n }\n\n // One compiler configuration is shared by locking bytecode generation and unlocking bytecode generation.\n const compiler = createCompilerBch({ ...compilerContext });\n\n return {\n compiler,\n compilerConfiguration: compilerContext,\n lockingScriptId,\n lockingScriptType: lockingType,\n unlockingScriptId,\n };\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { IncompleteScriptCompilation, KeyReference } from '@xo-cash/crypto';\nimport { type State, type StoredCommitSecret, type StoredInvitation, SecretDataNotFoundError } from '@xo-cash/state';\nimport type {\n XOInvitationIdentifier,\n XOInvitationResolutionIdentifier,\n XOTemplate,\n XOTemplateIdentifier,\n XOTemplateSecretIdentifier,\n} from '@xo-cash/types';\nimport { InvitationResolutionIdentifierInvalidError } from '../errors/index.ts';\nimport type { InvitationResolutionRequirements } from '../invitation/interfaces.ts';\nimport { listInvitationResolutions } from '../resolutions/combine.ts';\nimport { buildLibauthCompilerVariables } from './libauth-utils.ts';\nimport { listInvitationSecrets } from '../invitation/helpers/secrets.ts';\n\n/**\n * Key references, the lookup keys of the stored secrets they come from, and the key operations other participants\n * resolved, which a script compiles with besides its variables.\n */\nexport type CompilationKeys = {\n\n /**\n * Template and derivation index of each key, keyed by the template variable it belongs to.\n */\n keyReferences: Record<XOTemplateSecretIdentifier, KeyReference>;\n\n /**\n * Lookup key of the stored secret each key reference was read from, keyed by the same template variable.\n */\n secretLookupKeys: Record<XOTemplateSecretIdentifier, string>;\n\n /**\n * Key operations other participants resolved, such as their public keys, keyed by the operation.\n */\n resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array>;\n};\n\n/**\n * Resolves references to the keys this account generated for an invitation under one template.\n *\n * Locking and unlocking scripts of the invitation compile with these keys, the same way they compile with the invitation\n * variables. The keys themselves are derived only inside the crypto package, so this returns where each key sits in the\n * key tree instead of the key. A key is derived under the template it was generated for, so secrets generated under\n * another template are left out. Only a secret whose value is entropy holds a derivation index, so a secret whose value\n * is not entropy names no key and is left out. When the invitation holds more than one secret for a variable, the first\n * one recorded is the key the invitation uses.\n *\n * @param {State} state - State that stores the secrets.\n * @param {XOTemplateIdentifier} templateIdentifier - Template whose scripts are compiled.\n * @param {StoredCommitSecret[]} invitationSecrets - Secrets this account recorded for the invitation, in the order they were recorded.\n * @returns {Promise<Omit<CompilationKeys, 'resolutions'>>} - The key references and the lookup keys they came from.\n * @throws {@link SecretDataNotFoundError} - When a recorded secret is not in the secret store.\n */\nconst listSecretKeyReferences = async (\n state: State,\n templateIdentifier: XOTemplateIdentifier,\n invitationSecrets: StoredCommitSecret[],\n): Promise<Omit<CompilationKeys, 'resolutions'>> => {\n const keyReferenceSet: Omit<CompilationKeys, 'resolutions'> = { keyReferences: {}, secretLookupKeys: {} };\n\n for (const invitationSecret of invitationSecrets) {\n // A key derived under another template is a different key, so it cannot stand in for this template's variable.\n if (invitationSecret.templateIdentifier !== templateIdentifier) {\n continue;\n }\n\n // The first secret recorded for a variable is the key the invitation already uses for it.\n if (keyReferenceSet.keyReferences[invitationSecret.secretIdentifier] !== undefined) {\n continue;\n }\n\n const secretData = await state.getSecretData(invitationSecret.secretLookupKey);\n\n // The invitation records this secret, so a missing secret means the account storage is incomplete.\n if (secretData === undefined) {\n throw new SecretDataNotFoundError(invitationSecret.secretLookupKey);\n }\n\n // A value that is not entropy names no key to derive.\n if (secretData.isEntropy === false) {\n continue;\n }\n\n // The stored value is the derivation index the key was generated at under this template.\n keyReferenceSet.keyReferences[invitationSecret.secretIdentifier] = {\n templateIdentifier,\n derivationIndex: Number(secretData.value),\n };\n keyReferenceSet.secretLookupKeys[invitationSecret.secretIdentifier] = invitationSecret.secretLookupKey;\n }\n\n return keyReferenceSet;\n};\n\n/**\n * Adds entries to a map only where the map has no entry yet, so the first source of a value keeps it.\n *\n * @param {Record<string, Value>} targetEntries - Map that receives the entries.\n * @param {Record<string, Value>} sourceEntries - Entries to add where the target has none.\n * @returns {void}\n */\nconst addMissingEntries = <Value>(targetEntries: Record<string, Value>, sourceEntries: Record<string, Value>): void => {\n for (const [ entryKey, entryValue ] of Object.entries(sourceEntries)) {\n if (targetEntries[entryKey] === undefined) {\n targetEntries[entryKey] = entryValue;\n }\n }\n};\n\n/**\n * Resolves the keys and the resolved key operations an invitation's scripts compile with under one template.\n *\n * The invitation supplies the keys this account generated for it and the operations its participants resolved. An\n * invitation that spends outputs this account tracks also compiles with the context of the invitation each of those\n * outputs was built in, since a spend holds none of those keys itself. The invitation's own keys and resolutions come\n * first and keep their values.\n *\n * @param {State} state - State that stores invitations, script hashes, unspent outputs, and secrets.\n * @param {StoredInvitation} storedInvitation - Invitation whose scripts are compiled.\n * @param {XOTemplateIdentifier} templateIdentifier - Template whose scripts are compiled.\n * @returns {Promise<CompilationKeys>} - The key references, their lookup keys, and the resolved key operations.\n * @throws {@link SecretDataNotFoundError} - When a recorded secret is not in the secret store.\n * @throws {@link InvitationNotFoundInStoreError} - When a tracked output names an invitation that is not stored.\n */\nexport const listInvitationCompilationKeys = async (\n state: State,\n storedInvitation: StoredInvitation,\n templateIdentifier: XOTemplateIdentifier,\n): Promise<CompilationKeys> => {\n // Get the invitation from the stored invitation\n const { invitation } = storedInvitation;\n\n // Resolve the invitation key references\n const invitationSecrets = listInvitationSecrets(storedInvitation);\n const keyReferenceSet = await listSecretKeyReferences(state, templateIdentifier, invitationSecrets);\n const compilationKeys: CompilationKeys = { ...keyReferenceSet, resolutions: {} };\n\n // Resolutions name operations on this invitation's template keys, so they only apply to scripts of that template.\n if (invitation.templateIdentifier === templateIdentifier) {\n compilationKeys.resolutions = listInvitationResolutions(invitation.commits);\n }\n\n const includedInvitationIdentifiers = new Set<XOInvitationIdentifier>([ invitation.invitationIdentifier ]);\n\n for (const commit of invitation.commits) {\n for (const input of commit.data.inputs ?? []) {\n // An extension only adds fields to an input listed earlier, and an input without an outpoint spends nothing yet.\n if (input.mergesWith !== undefined || input.outpointTransactionHash === undefined || input.outpointIndex === undefined) {\n continue;\n }\n\n const unspentOutput = await state.getUnspentOutputData(binToHex(input.outpointTransactionHash), input.outpointIndex);\n\n // Only an output this account tracks has a script hash that can name the invitation it was built in.\n if (unspentOutput === undefined) {\n continue;\n }\n\n const scriptHashData = await state.getScriptHashData(unspentOutput.scriptHash);\n const originInvitationIdentifier = scriptHashData?.invitationIdentifier;\n\n // A script built outside any invitation, or one already included, adds nothing.\n if (originInvitationIdentifier === undefined || includedInvitationIdentifiers.has(originInvitationIdentifier)) {\n continue;\n }\n\n includedInvitationIdentifiers.add(originInvitationIdentifier);\n\n const originInvitation = await state.getInvitationOrThrow(originInvitationIdentifier);\n\n // Keys and resolutions of another template name other variables, so only an invitation of this template adds them.\n if (originInvitation.invitation.templateIdentifier !== templateIdentifier) {\n continue;\n }\n\n const originInvitationSecrets = listInvitationSecrets(originInvitation);\n const originKeyReferences = await listSecretKeyReferences(state, templateIdentifier, originInvitationSecrets);\n const originResolutions = listInvitationResolutions(originInvitation.invitation.commits);\n\n addMissingEntries(compilationKeys.keyReferences, originKeyReferences.keyReferences);\n addMissingEntries(compilationKeys.secretLookupKeys, originKeyReferences.secretLookupKeys);\n addMissingEntries(compilationKeys.resolutions, originResolutions);\n }\n }\n\n return compilationKeys;\n};\n\n/**\n * Builds the compilation data bytecode for resolved key operations.\n *\n * The compiler uses a bytecode entry for an operation instead of deriving it from a key, which is how a script uses\n * another participant's public key or signature. An operation on a key this account holds is left out so the account's\n * own key is always the one used, whatever another participant resolved for it.\n *\n * @param {XOTemplate} template - Template whose scripts are compiled.\n * @param {Record<XOInvitationResolutionIdentifier, Uint8Array>} resolutions - Resolved key operations.\n * @param {ReadonlySet<string>} heldKeyVariableIdentifiers - Key variables this account holds for the compile.\n * @returns {Record<XOInvitationResolutionIdentifier, Uint8Array>} - Compilation data bytecode keyed by the operation.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n */\nexport const buildResolutionCompilationBytecode = (\n template: XOTemplate,\n resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array>,\n heldKeyVariableIdentifiers: ReadonlySet<string>,\n): Record<XOInvitationResolutionIdentifier, Uint8Array> => {\n const compilerVariables = buildLibauthCompilerVariables(template) ?? {};\n const resolutionBytecode: Record<XOInvitationResolutionIdentifier, Uint8Array> = {};\n const invalidResolutionIdentifiers: XOInvitationResolutionIdentifier[] = [];\n\n for (const [ resolutionIdentifier, resolvedValue ] of Object.entries(resolutions)) {\n const keyVariableIdentifier = resolutionIdentifier.split('.')[0];\n\n // Without a dot the entry would replace a plain variable, which participants provide as invitation variables instead.\n const isKeyOperation = resolutionIdentifier.includes('.') && compilerVariables[keyVariableIdentifier]?.type === 'Key';\n\n if (isKeyOperation === false) {\n invalidResolutionIdentifiers.push(resolutionIdentifier);\n\n continue;\n }\n\n // The account's own key is used for its own operations.\n if (heldKeyVariableIdentifiers.has(keyVariableIdentifier)) {\n continue;\n }\n\n resolutionBytecode[resolutionIdentifier] = resolvedValue;\n }\n\n // Every invalid identifier is reported together so all offending commits can be fixed at once.\n if (invalidResolutionIdentifiers.length > 0) {\n throw new InvitationResolutionIdentifierInvalidError(invalidResolutionIdentifiers);\n }\n\n return resolutionBytecode;\n};\n\n/**\n * Groups the identifiers an incomplete compile with this account's keys reported, by who still has to provide them.\n *\n * The compile reports the operations on this account's keys as resolved, and the identifiers it could not resolve as\n * missing. Each identifier counts as provided when the given resolutions already hold a value for it.\n *\n * @param {IncompleteScriptCompilation} incompleteCompilation - What a compile with this account's keys reported when it stopped.\n * @param {Record<XOInvitationResolutionIdentifier, Uint8Array>} resolutions - Values participants already provided.\n * @returns {InvitationResolutionRequirements} - Provided identifiers, values this account can add, and identifiers others still owe.\n */\nexport const groupResolutionRequirements = (\n incompleteCompilation: IncompleteScriptCompilation,\n resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array>,\n): InvitationResolutionRequirements => {\n const resolutionRequirements: InvitationResolutionRequirements = { providedIdentifiers: [], ownResolutions: [], missingIdentifiers: [] };\n\n // Operations on this account's keys are its own part until the invitation holds them.\n for (const [ resolutionIdentifier, resolvedValue ] of Object.entries(incompleteCompilation.resolvedKeyOperations)) {\n if (resolutions[resolutionIdentifier] === undefined) {\n resolutionRequirements.ownResolutions.push({ resolutionIdentifier, value: resolvedValue });\n\n continue;\n }\n\n resolutionRequirements.providedIdentifiers.push(resolutionIdentifier);\n }\n\n // Every other identifier the script uses is held by another participant, who still owes it until the invitation holds it.\n for (const missingIdentifier of incompleteCompilation.missingIdentifiers) {\n if (resolutions[missingIdentifier] === undefined) {\n resolutionRequirements.missingIdentifiers.push(missingIdentifier);\n\n continue;\n }\n\n resolutionRequirements.providedIdentifiers.push(missingIdentifier);\n }\n\n return resolutionRequirements;\n};\n","import { bigIntToVmNumber, hexToBin, isHex, utf8ToBin } from '@bitauth/libauth';\nimport type {\n XOInvitationCommit,\n XOInvitationVariable,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateConstantIdentifier,\n XOTemplateLockingScriptIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateVariable,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport {\n CashAssemblyVariableNotIntegerError,\n LockingScriptCompilationFailedError,\n TemplateOutputLockingScriptReferenceInvalidError,\n} from '../errors/index.ts';\nimport { compileCashAssemblyString, generateTemplateIdentifier, isCashAssemblyExpression } from '@xo-cash/utils';\nimport { createLibauthCompilerForLockingScript, listTemplateSecretIdentifiers, isLibauthKeyTemplateVariable } from './libauth-utils.ts';\nimport { getTemplateLockingScriptIdentifierOrThrow, getTemplateLockingScriptOrThrow } from '../template.ts';\n\n/**\n * Builds the variable map used to evaluate template CashAssembly and compile locking bytecode.\n *\n * Template constant defaults are applied first. Invitation commit variables overwrite constants when identifiers collide.\n * A constant whose value is not a string, number, bigint, or boolean is left out of the map.\n *\n * @param {XOTemplate} template - Imported template definition.\n * @param {XOInvitationVariable[]} invitationVariables - Variables collected from invitation commits.\n * @returns {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} - Map from identifier to value for\n * compilation.\n */\nexport const mergeTemplateConstantsWithInvitationVariables = (\n template: XOTemplate,\n invitationVariables: XOInvitationVariable[],\n): Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue> => {\n const compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue> = {};\n const templateConstants = template.constants ?? {};\n\n for (const [ constantIdentifier, constantDefinition ] of Object.entries(templateConstants)) {\n const rawConstantValue: unknown = constantDefinition.value;\n\n // The template types a constant value as unknown, so only values a variable can hold enter the map.\n const isVariableValue =\n typeof rawConstantValue === 'string'\n || typeof rawConstantValue === 'number'\n || typeof rawConstantValue === 'bigint'\n || typeof rawConstantValue === 'boolean';\n\n if (isVariableValue) {\n compilationVariables[constantIdentifier] = rawConstantValue;\n }\n }\n\n // Invitation variables are written last so they overwrite a constant with the same identifier.\n for (const invitationVariable of invitationVariables) {\n compilationVariables[invitationVariable.variableIdentifier] = invitationVariable.value;\n }\n\n return compilationVariables;\n};\n\n/**\n * Collects invitation variables from stored commits and optional append parameters.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits to read variables from.\n * @param {XOInvitationVariable[]} [additionalVariables] - Extra variables mixed with variables already on commits.\n * @returns {XOInvitationVariable[]} - Flat list of variables in commit order.\n */\nexport const listInvitationVariablesFromCommits = (\n commits: readonly XOInvitationCommit[],\n additionalVariables?: XOInvitationVariable[],\n): XOInvitationVariable[] => {\n const invitationVariables: XOInvitationVariable[] = [];\n\n for (const commit of commits) {\n if (commit.data.variables !== undefined) {\n invitationVariables.push(...commit.data.variables);\n }\n }\n\n if (additionalVariables !== undefined) {\n invitationVariables.push(...additionalVariables);\n }\n\n return invitationVariables;\n};\n\n/**\n * Converts one invitation variable value into bytes for the libauth compiler bytecode map.\n *\n * @param {XOTemplateVariableIdentifier} variableIdentifier - Template variable or constant identifier.\n * @param {XOInvitationVariableValue} variableValue - Value from the invitation or template constant defaults.\n * @param {XOTemplateVariable} [templateVariable] - Optional template variable metadata for type based encoding.\n * @returns {Uint8Array} - Byte representation for `data.bytecode` in libauth compilation.\n */\nconst convertInvitationVariableValueForCompiler = (\n variableIdentifier: XOTemplateVariableIdentifier,\n variableValue: XOInvitationVariableValue,\n templateVariable?: XOTemplateVariable,\n): Uint8Array => {\n if (typeof variableValue === 'bigint') {\n return bigIntToVmNumber(variableValue);\n }\n\n if (typeof variableValue === 'number') {\n if (Number.isInteger(variableValue) === false) {\n throw new CashAssemblyVariableNotIntegerError(variableIdentifier, variableValue);\n }\n\n return bigIntToVmNumber(BigInt(variableValue));\n }\n\n if (typeof variableValue === 'boolean') {\n return new Uint8Array(variableValue === true ? [ 1 ] : []);\n }\n\n const stringValue = String(variableValue);\n const variableText = stringValue.startsWith('0x') === true ? stringValue.slice(2) : stringValue;\n const variableType = templateVariable?.type;\n\n if (variableType === 'bytes') {\n return hexToBin(variableText);\n }\n\n // Prefer hex when the string is valid hex so constants like category ids stay binary.\n if (isHex(variableText) === true) {\n return hexToBin(variableText);\n }\n\n return utf8ToBin(stringValue);\n};\n\n/**\n * Builds the libauth `data.bytecode` map from invitation and template constant values.\n *\n * @param {XOTemplate} template - Imported template definition.\n * @param {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} compilationVariables - Map built by\n * {@link mergeTemplateConstantsWithInvitationVariables}.\n * @returns {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, Uint8Array>} - Bytecode map keyed by template variable identifiers.\n */\nexport const buildCompilerBytecodeDataFromCompilationVariables = (\n template: XOTemplate,\n compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>,\n): Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, Uint8Array> => {\n const compilerBytecodeData: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, Uint8Array> = {};\n const templateVariables = template.variables ?? {};\n\n for (const [ variableIdentifier, variableValue ] of Object.entries(compilationVariables)) {\n const templateVariable: XOTemplateVariable | undefined = templateVariables[variableIdentifier];\n\n compilerBytecodeData[variableIdentifier] = convertInvitationVariableValueForCompiler(variableIdentifier, variableValue, templateVariable);\n }\n\n return compilerBytecodeData;\n};\n\n/**\n * Removes Key secret identifiers from a compilation variable map.\n *\n * Those values belong in Libauth `data.keys`, not `data.bytecode`. Matches both explicit\n * `private_key` types and locking script secrets so older templates without a type stay correct.\n *\n * @param {XOTemplate} template - Imported template definition.\n * @param {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} compilationVariables - Map built by\n * {@link mergeTemplateConstantsWithInvitationVariables}.\n * @returns {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} - Variable map without Key typed\n * identifiers.\n */\nexport const omitPrivateKeyVariablesFromCompilationVariables = (\n template: XOTemplate,\n compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>,\n): Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue> => {\n const filteredCompilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue> = {};\n const templateVariables = template.variables ?? {};\n const templateSecretIdentifiers = listTemplateSecretIdentifiers(template);\n\n for (const [ variableIdentifier, variableValue ] of Object.entries(compilationVariables)) {\n const templateVariable: XOTemplateVariable | undefined = templateVariables[variableIdentifier];\n\n if (isLibauthKeyTemplateVariable(variableIdentifier, templateSecretIdentifiers, templateVariable) === true) {\n continue;\n }\n\n filteredCompilationVariables[variableIdentifier] = variableValue;\n }\n\n return filteredCompilationVariables;\n};\n\n/**\n * Picks the template variable values a locking bytecode was compiled with, as the strings script hash storage keeps.\n *\n * Template constants are left out because the template already holds them. Key variables are left out because\n * they hold private keys.\n *\n * Variables the locking script lists in its own state are kept for every participant. Variables a role lists in its\n * state are kept only for the account that took that role, so a variable listed only by other roles is left out.\n * Variables no state lists are kept, since the script may still need them when it is spent.\n *\n * @param {XOTemplate} template - Template the locking script belongs to.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script the bytecode was compiled from.\n * @param {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} compilationVariables - Values used for\n * compilation, built by {@link mergeTemplateConstantsWithInvitationVariables}.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role this account took on the locking script, when one is known.\n * @returns {Record<XOTemplateVariableIdentifier, string>} - Variable values keyed by variable identifier.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is absent from the template.\n */\nexport const buildScriptHashVariablesFromCompilationVariables = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): Record<XOTemplateVariableIdentifier, string> => {\n const scriptHashVariables: Record<XOTemplateVariableIdentifier, string> = {};\n const templateVariables = template.variables ?? {};\n const lockingScript = getTemplateLockingScriptOrThrow(template, lockingScriptIdentifier);\n\n // Variables kept for this account, from the locking script state and the state of the role it took.\n const keptVariableIdentifiers = new Set<XOTemplateVariableIdentifier>(lockingScript.state?.variables ?? []);\n\n // Variables the state of a role lists, which belong only to the accounts that took that role.\n const roleStateVariableIdentifiers = new Set<XOTemplateVariableIdentifier>();\n\n for (const [ lockingScriptRoleIdentifier, lockingScriptRole ] of Object.entries(lockingScript.roles ?? {})) {\n for (const roleStateVariableIdentifier of lockingScriptRole.state?.variables ?? []) {\n roleStateVariableIdentifiers.add(roleStateVariableIdentifier);\n\n if (lockingScriptRoleIdentifier === roleIdentifier) {\n keptVariableIdentifiers.add(roleStateVariableIdentifier);\n }\n }\n }\n\n const nonKeyCompilationVariables = omitPrivateKeyVariablesFromCompilationVariables(template, compilationVariables);\n\n for (const [ variableIdentifier, variableValue ] of Object.entries(nonKeyCompilationVariables)) {\n // Constants share the map with variables but are not declared as template variables.\n if (templateVariables[variableIdentifier] === undefined) {\n continue;\n }\n\n // A variable only other roles keep in their state is not this account's to store.\n const isOtherRoleVariable = roleStateVariableIdentifiers.has(variableIdentifier) && keptVariableIdentifiers.has(variableIdentifier) === false;\n\n if (isOtherRoleVariable) {\n continue;\n }\n\n scriptHashVariables[variableIdentifier] = String(variableValue);\n }\n\n return scriptHashVariables;\n};\n\n/**\n * Compiles locking bytecode from a template locking script definition and invitation variable context.\n *\n * Used when an output references a locking script by identifier rather than a CashAssembly expression on the output\n * itself.\n *\n * @param {XOTemplate} template - Template whose locking scripts are compiled.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script identifier from the template output definition.\n * @param {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} compilationVariables - Variable map\n * including template constants and commit variables.\n * @returns {Uint8Array} - Compiled locking bytecode bytes for the merged output.\n * @throws {@link LockingScriptCompilationFailedError} - When Libauth compilation of the locking script fails.\n */\nexport const compileLockingBytecodeFromTemplateLockingScriptIdentifier = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>,\n): Uint8Array => {\n // Reuse the shared compiler so the locking type is keyed by the same script identifier as other compiles.\n const { compiler, lockingScriptId } = createLibauthCompilerForLockingScript(template, lockingScriptIdentifier);\n\n const compilerBytecodeData = buildCompilerBytecodeDataFromCompilationVariables(template, compilationVariables);\n\n const compilationResult = compiler.generateBytecode({\n data: { bytecode: compilerBytecodeData },\n scriptId: lockingScriptId,\n });\n\n if (compilationResult.success === false) {\n const compilationErrorMessages: string[] = [];\n\n // Every compiler error is carried so the template author can fix them all at once.\n for (const compilationError of compilationResult.errors) {\n compilationErrorMessages.push(compilationError.error);\n }\n\n throw new LockingScriptCompilationFailedError(generateTemplateIdentifier(template), lockingScriptIdentifier, compilationErrorMessages);\n }\n\n return compilationResult.bytecode;\n};\n\n/**\n * Resolves locking bytecode for a template output from invitation variables and template constants.\n *\n * @param {XOTemplate} template - Template for the invitation.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output identifier.\n * @param {XOInvitationVariable[]} invitationVariables - Variables from merged commits and the current append.\n * @returns {Uint8Array} - Locking bytecode bytes for the output.\n * @throws {@link TemplateOutputNotFoundError} - When the output is absent from the template.\n * @throws {@link TemplateOutputLockingScriptNotFoundError} - When the template output has no locking script reference.\n * @throws {@link CashAssemblyCompilationFailedError} - When a CashAssembly expression fails to compile.\n * @throws {@link LockingScriptCompilationFailedError} - When the template locking script fails to compile.\n * @throws {@link TemplateLockingScriptTypeNotFoundError} - When the locking script definition is incomplete.\n * @throws {@link TemplateOutputLockingScriptReferenceInvalidError} - When a locking script or script the output references is not in the template.\n */\nexport const resolveTemplateOutputLockingBytecode = (\n template: XOTemplate,\n outputIdentifier: XOTemplateOutputIdentifier,\n invitationVariables: XOInvitationVariable[],\n): Uint8Array => {\n // Read the locking script the output declares, which throws when the output or its locking script is missing from the template.\n const lockingScriptIdentifier = getTemplateLockingScriptIdentifierOrThrow(template, outputIdentifier);\n const compilationVariables = mergeTemplateConstantsWithInvitationVariables(template, invitationVariables);\n\n // First trying with the cash assembly evaluation if the locking script is a cash assembly evaluation.\n if (isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n const compiledLockingBytecode = compileCashAssemblyString({\n cashAssemblyText: lockingScriptIdentifier,\n variables: compilationVariables,\n evaluationDecodeMode: 'utf8',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n\n return hexToBin(compiledLockingBytecode);\n }\n\n const templateLockingScriptReference = template.lockingScripts?.[lockingScriptIdentifier];\n\n if (templateLockingScriptReference === undefined) {\n throw new TemplateOutputLockingScriptReferenceInvalidError(generateTemplateIdentifier(template), outputIdentifier, lockingScriptIdentifier);\n }\n\n const lockingBytecode = templateLockingScriptReference.lockingBytecode;\n\n if (isCashAssemblyExpression(lockingBytecode) === true) {\n // If the lockingscript is a reference to the template defined lockingscripts.\n const compiledLockingBytecode = compileCashAssemblyString({\n cashAssemblyText: lockingBytecode,\n variables: compilationVariables,\n evaluationDecodeMode: 'utf8',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n\n return hexToBin(compiledLockingBytecode);\n }\n\n const lockingBytecodeScriptReference = template.scripts?.[lockingBytecode];\n\n if (lockingBytecodeScriptReference === undefined) {\n throw new TemplateOutputLockingScriptReferenceInvalidError(generateTemplateIdentifier(template), outputIdentifier, lockingBytecode);\n }\n\n return compileLockingBytecodeFromTemplateLockingScriptIdentifier(template, lockingScriptIdentifier, compilationVariables);\n};\n","import type { XOTemplate, XOTemplateLockingScriptIdentifier, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport { generateTemplateIdentifier, isCashAssemblyExpression } from '@xo-cash/utils';\nimport { TemplateLockingScriptNotFoundError, TemplateRoleRelevantCashAssemblyUnsupportedError } from '../errors/index.ts';\n\n/**\n * XO template roles and Libauth compatible compilation.\n *\n * XO defines its own template standard. When the engine compiles locking or unlocking bytecode it\n * supplies Libauth with the compilation shape Libauth requires so XO templates stay compatible.\n *\n * Active action roles (`actions.*.roles` and `requirements.participants`) describe optional\n * invitation participation. Role specific requirements apply only when that role is chosen.\n *\n * Locking script role actions (`lockingScripts.*.roles.*.actions`) describe follow up invitations\n * after locking bytecode already exists.\n *\n * Minting locking bytecode compiles `lockingBytecode` with Libauth compilation data. That path\n * does not require an invitation role. Libauth `Key` variables need `data.keys.privateKeys[id]`.\n * Libauth `WalletData` variables need `data.bytecode[id]`. Libauth `HdKey` variables need\n * `entityOwnership` and `data.hdKeys`. XO derives hierarchical key material outside Libauth and\n * passes raw private keys into the `Key` compilation path.\n *\n * Optional `output.roleIdentifier` is invitation metadata. When set it must exist on the locking\n * script. When unset mint still proceeds. `entityOwnership` may mirror a validated role when\n * present. It must not invent a role to satisfy `Key` compiles.\n *\n * Secret identifiers for mint come from mint context when available, otherwise from locking script\n * role definitions. Missing Key or WalletData material fails at compile time.\n */\n\n/**\n * Parameters for deciding whether a generated locking output should be stored and Electrum tracked.\n */\nexport type IsLockingOutputRelevantForRoleParameters = {\n\n /** Template whose output and locking script roles are read. */\n template: XOTemplate;\n\n /** Template locking script whose role relevance is evaluated. */\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /** Role bound to generation or registration when known. */\n roleIdentifier?: XOTemplateRoleIdentifier;\n};\n\n/**\n * Returns whether locking bytecode for an output should be stored and subscribed for a role.\n *\n * Compiling bytecode for a transaction is independent of this check. Callers still compile when the\n * transaction needs the lock. Persistence and Electrum tracking run only when this returns true.\n *\n * Boolean `false` on the output role or the locking script role skips store and subscribe. Either\n * location is enough. Omitted `relevant` and a missing role both mean track.\n *\n * @param {IsLockingOutputRelevantForRoleParameters} parameters - Template, output, and optional role.\n * @returns {boolean} - True when the engine should store and subscribe the script hash.\n * @throws {@link TemplateLockingScriptNotFoundError} - When a non CashAssembly locking script identifier is missing.\n * @throws {@link TemplateRoleRelevantCashAssemblyUnsupportedError} - When `relevant` is a CashASM string.\n */\nexport const isLockingOutputRelevantForRole = (parameters: IsLockingOutputRelevantForRoleParameters): boolean => {\n const { template, lockingScriptIdentifier, roleIdentifier } = parameters;\n\n const isCashAssemblyLockingScript = isCashAssemblyExpression(lockingScriptIdentifier);\n const lockingScriptDefinition = template.lockingScripts[lockingScriptIdentifier];\n\n // A CashAssembly lockingScript string is not a locking script identifier. A missing identifier is a template error.\n if (isCashAssemblyLockingScript === false && lockingScriptDefinition === undefined) {\n throw new TemplateLockingScriptNotFoundError(generateTemplateIdentifier(template), lockingScriptIdentifier);\n }\n\n const hasBoundRoleIdentifier = roleIdentifier !== undefined;\n\n // Without a role there is no role scoped relevance flag so receive and change keep tracking.\n if (hasBoundRoleIdentifier === false || roleIdentifier === undefined) {\n return true;\n }\n\n const relevantFromLockingScript = lockingScriptDefinition?.roles?.[roleIdentifier]?.relevant;\n\n // CashASM relevance is typed on the template but evaluation is not implemented yet.\n if (typeof relevantFromLockingScript === 'string') {\n throw new TemplateRoleRelevantCashAssemblyUnsupportedError(\n generateTemplateIdentifier(template),\n lockingScriptIdentifier,\n roleIdentifier,\n relevantFromLockingScript,\n );\n }\n\n // Explicit false on the locking script skips store and Electrum subscribe.\n if (relevantFromLockingScript === false) {\n return false;\n }\n\n return true;\n};\n","import { assertSuccess, decodeTransaction, hexToBin, type Output } from '@bitauth/libauth';\nimport { electrumClients, getUsableElectrumClient, getTransaction } from '@electrum-cash/application';\nimport { ConnectionStatus } from '@electrum-cash/network';\nimport {\n type ScriptHashListUnspentEntry,\n type TransactionHash,\n type ScriptHashListUnspentResponse,\n fetchScriptHashUnspentTransactionOutputs,\n} from '@electrum-cash/protocol';\nimport { type UnspentOutputData, UnspentOutputStatus } from '@xo-cash/state';\nimport type { ValueOf, XOTemplateIdentifier } from '@xo-cash/types';\nimport { TransactionOutputNotFoundError } from '../errors/index.ts';\nimport { scriptToScriptHash } from '@xo-cash/utils';\n\n/**\n * Names of the states an Electrum connection can be in.\n */\nexport const ELECTRUM_CONNECTION_STATUSES = {\n disconnected: 'disconnected',\n connected: 'connected',\n disconnecting: 'disconnecting',\n connecting: 'connecting',\n reconnecting: 'reconnecting',\n unrecoverable: 'unrecoverable',\n} as const;\n\n/**\n * State of one Electrum connection.\n */\nexport type ElectrumConnectionStatus = ValueOf<typeof ELECTRUM_CONNECTION_STATUSES>;\n\n/**\n * Status name for each {@link ConnectionStatus} an Electrum client reports.\n */\nconst ELECTRUM_CONNECTION_STATUS_BY_CLIENT_STATUS: Record<ConnectionStatus, ElectrumConnectionStatus> = {\n [ConnectionStatus.DISCONNECTED]: ELECTRUM_CONNECTION_STATUSES.disconnected,\n [ConnectionStatus.CONNECTED]: ELECTRUM_CONNECTION_STATUSES.connected,\n [ConnectionStatus.DISCONNECTING]: ELECTRUM_CONNECTION_STATUSES.disconnecting,\n [ConnectionStatus.CONNECTING]: ELECTRUM_CONNECTION_STATUSES.connecting,\n [ConnectionStatus.RECONNECTING]: ELECTRUM_CONNECTION_STATUSES.reconnecting,\n [ConnectionStatus.UNRECOVERABLE]: ELECTRUM_CONNECTION_STATUSES.unrecoverable,\n};\n\n/**\n * One Electrum server the engine connects to and the state of that connection.\n */\nexport type ElectrumConnection = {\n\n /**\n * Host and port of the server, such as `electrum.imaginary.cash:50004`.\n */\n hostIdentifier: string;\n\n /**\n * Whether the connection uses TLS.\n */\n isEncrypted: boolean;\n\n /**\n * State of the connection.\n */\n status: ElectrumConnectionStatus;\n\n /**\n * Name and version of the server software.\n */\n software?: string;\n\n /**\n * Chain height the server reports.\n */\n chainHeight?: number;\n};\n\n/**\n * Decodes one output from a transaction loaded through Electrum.\n *\n * @param {TransactionHash} transactionHash - Parent transaction id in Electrum hex form.\n * @param {number} outputIndex - Output index in the decoded transaction.\n * @returns {Promise<Output>} - Decoded libauth output.\n * @throws {@link TransactionOutputNotFoundError} - When the output index is missing.\n */\nexport const fetchDecodedTransactionOutput = async (transactionHash: TransactionHash, outputIndex: number): Promise<Output> => {\n // Get the transaction from Electrum.\n const serializedTransaction = await getTransaction(transactionHash);\n\n // Decode the transaction.\n const decodedTransaction = assertSuccess(decodeTransaction(hexToBin(serializedTransaction)));\n\n // Get the output from the transaction.\n const output = decodedTransaction.outputs[outputIndex];\n\n // If the output is not found, throw an error.\n if (output === undefined) {\n throw new TransactionOutputNotFoundError(transactionHash, outputIndex);\n }\n\n // Return the output.\n return output;\n};\n\n/**\n * Converts an Electrum `blockchain.scripthash.list_unspent` entry to UnspentOutputData.\n *\n * @param {ScriptHashListUnspentEntry} entry - Electrum listunspent entry for a single outpoint.\n * @param {string} scriptHash - Script hash of the output.\n * @param {XOTemplateIdentifier} templateIdentifier - Template that produced the locking bytecode for this script hash.\n * @returns {UnspentOutputData} - Normalized unspent output including flattened CashTokens fields when present.\n */\nexport const toUnspentOutputData = (\n entry: ScriptHashListUnspentEntry,\n scriptHash: string,\n templateIdentifier: XOTemplateIdentifier,\n): UnspentOutputData => {\n // Create the unspent output data.\n const unspentOutputData: UnspentOutputData = {\n status: entry.height === 0 ? UnspentOutputStatus.PENDING : UnspentOutputStatus.CONFIRMED,\n reservedBy: undefined,\n scriptHash,\n templateIdentifier,\n selectable: true,\n privacy: false,\n outpointIndex: entry.tx_pos,\n outpointTransactionHash: entry.tx_hash,\n minedAtHeight: entry.height,\n valueSatoshis: entry.value,\n };\n\n // Get the token data from the entry.\n const listUnspentEntryTokenData = entry.token_data;\n\n if (listUnspentEntryTokenData === undefined) {\n return unspentOutputData;\n }\n\n // Set the token category.\n unspentOutputData.tokenCategory = listUnspentEntryTokenData.category;\n\n // Set the token amount.\n unspentOutputData.tokenAmount = listUnspentEntryTokenData.amount;\n\n // Set the token NFT capability and commitment.\n if (listUnspentEntryTokenData.nft !== undefined) {\n unspentOutputData.tokenNftCapability = listUnspentEntryTokenData.nft.capability;\n unspentOutputData.tokenNftCommitment = listUnspentEntryTokenData.nft.commitment;\n }\n\n // Return the unspent output data.\n return unspentOutputData;\n};\n\n/**\n * Fetches unspent outputs for a script hash, including CashToken unspent outputs.\n *\n * @param {string} scriptHash - Script hash to query.\n * @returns {Promise<ScriptHashListUnspentResponse>} - Unspent outputs for the script hash.\n */\nexport const fetchScriptHashUnspentOutputs = async (scriptHash: string): Promise<ScriptHashListUnspentResponse> => {\n // Get a usable Electrum client.\n const usableElectrumClient = await getUsableElectrumClient();\n\n // Fetch the unspent outputs.\n return fetchScriptHashUnspentTransactionOutputs(usableElectrumClient, scriptHash, true, true);\n};\n\n/**\n * Fetches unspent outputs for a locking bytecode from Electrum.\n *\n * Results are not stored. Tracking a locking script still goes through registration with a real template output identifier.\n *\n * @param {string} lockingBytecode - Locking bytecode as hexadecimal.\n * @param {XOTemplateIdentifier} templateIdentifier - Template that produced the locking bytecode.\n * @returns {Promise<UnspentOutputData[]>} - Unspent outputs for the locking bytecode.\n */\nexport const fetchUnspentOutputsForLockingBytecode = async (\n lockingBytecode: string,\n templateIdentifier: XOTemplateIdentifier,\n): Promise<UnspentOutputData[]> => {\n // Convert the locking bytecode to a script hash.\n const scriptHash = scriptToScriptHash(hexToBin(lockingBytecode));\n\n // Fetch the unspent outputs.\n const unspentOutputsFromBlockchain = await fetchScriptHashUnspentOutputs(scriptHash);\n\n // Create the unspent outputs.\n const unspentOutputs: UnspentOutputData[] = [];\n\n // Map the unspent outputs.\n for (const unspentOutputFromBlockchain of unspentOutputsFromBlockchain) {\n // Convert the unspent output to UnspentOutputData.\n unspentOutputs.push(toUnspentOutputData(unspentOutputFromBlockchain, scriptHash, templateIdentifier));\n }\n\n // Return the unspent outputs.\n return unspentOutputs;\n};\n\n/**\n * Lists every Electrum server the engine connects to, with the state of each connection.\n *\n * @returns {ElectrumConnection[]} - One entry per Electrum client, empty before Electrum is initialized.\n */\nexport const listElectrumConnections = (): ElectrumConnection[] => {\n const electrumConnections: ElectrumConnection[] = [];\n\n for (const electrumClient of electrumClients.values()) {\n electrumConnections.push({\n hostIdentifier: electrumClient.hostIdentifier,\n isEncrypted: electrumClient.encrypted,\n status: ELECTRUM_CONNECTION_STATUS_BY_CLIENT_STATUS[electrumClient.status],\n software: electrumClient.software,\n chainHeight: electrumClient.chainHeight,\n });\n }\n\n return electrumConnections;\n};\n","import { electrumEvents, stopElectrumNetwork, type SystemFailure, type ScriptHashUpdate } from '@electrum-cash/application';\nimport type { State } from '@xo-cash/state';\nimport { updateUnspentOutputsForScriptHash } from '../state/index.ts';\nimport { fetchScriptHashUnspentOutputs } from './electrum.ts';\n\n/**\n * BlockchainMonitor class that provides blockchain monitoring operations.\n */\nexport class BlockchainMonitor {\n /**\n * The state instance for data persistence.\n */\n #state: State;\n\n /**\n * Flag indicating whether event listeners have been initialized.\n */\n #eventListenersInitialized: boolean = false;\n\n /**\n * Creates a new instance of BlockchainMonitor.\n *\n * @param {State} state - The State instance for data persistence.\n */\n constructor(state: State) {\n this.#state = state;\n }\n\n /**\n * Registers the Electrum application event listeners this monitor acts on.\n * A system failure stops this monitor, and a script hash update refreshes the stored unspent outputs of that script hash.\n * Calling it again before {@link BlockchainMonitor.stop} registers nothing.\n *\n * @returns {void}\n * @todo Handle a system failure for every resource that depends on Electrum, not only this monitor.\n * @todo Log system failures.\n */\n initializeEventListeners(): void {\n if (this.#eventListenersInitialized) {\n return;\n }\n\n electrumEvents.on('SystemFailure', (_error: SystemFailure) => {\n // Stop the blockchain monitor on system failure\n this.stop().catch(() => {});\n });\n\n electrumEvents.on('ScriptHashUpdate', async (data: ScriptHashUpdate) => {\n await this.onScriptHashUpdate(data);\n });\n\n this.#eventListenersInitialized = true;\n }\n\n /**\n * Stops the blockchain monitor and releases resources.\n * @returns {Promise<void>} - Resolves when the blockchain monitor is stopped.\n */\n async stop(): Promise<void> {\n // Stop the electrum network\n await stopElectrumNetwork();\n\n // Reset the event listeners initialized flag\n this.#eventListenersInitialized = false;\n }\n\n /**\n * Handles script hash update notifications from the electrum protocol.\n * When a script hash update is received, this method finds the scriptHash and updates the unspent outputs for it.\n *\n * @param {ScriptHashUpdate} data - The script hash update data.\n * @returns {Promise<void>} - Resolves when the unspent outputs are updated.\n */\n async onScriptHashUpdate(data: ScriptHashUpdate): Promise<void> {\n const { scriptHash } = data;\n\n const scriptHashDataList = await this.#state.listScriptHashData({ scriptHash });\n\n for (const scriptHashData of scriptHashDataList) {\n const unspentOutputs = await fetchScriptHashUnspentOutputs(scriptHashData.scriptHash);\n\n await updateUnspentOutputsForScriptHash(this.#state, scriptHashData.scriptHash, unspentOutputs);\n }\n }\n}\n","import type { ScriptHashListUnspentResponse, TransactionHash } from '@electrum-cash/protocol';\nimport { UnspentOutputNotFoundInStoreError, type State, type UnspentOutputData, type UnspentOutputDataFilter } from '@xo-cash/state';\nimport { NFTCommitment, TemplateIdentifier, TokenCategory } from '@xo-cash/primitives';\nimport type { ListSpendableUnspentOutputsParameters } from '../interfaces.ts';\nimport { getTemplateLockingScriptIdentifierOrThrow, getTemplateOutputOrThrow } from '../template.ts';\nimport { toUnspentOutputData } from '../network/index.ts';\n\n/**\n * Gets the outpoint key for a given transaction hash and outpoint index.\n *\n * @param {TransactionHash} outpointTransactionHash - The transaction hash of the outpoint.\n * @param {number} outpointIndex - The index of the outpoint in the transaction.\n * @returns {string} - The outpoint key.\n */\nconst getOutpointKey = (outpointTransactionHash: TransactionHash, outpointIndex: number): string => `${outpointTransactionHash}:${outpointIndex}`;\n\n/**\n * Stores one unspent output Electrum reports, or updates its stored status when Electrum reports a different one.\n *\n * @param {State} state - The State instance to use for data operations.\n * @param {Map<string, UnspentOutputData>} unspentOutputsByOutpointKey - Existing unspent outputs for this script hash keyed by outpoint.\n * @param {UnspentOutputData} unspentOutputFromBlockchain - One unspent output from Electrum listunspent, converted to unspent output data.\n * @returns {Promise<void>} - Resolves when a new output is stored or a changed status is updated.\n */\nconst storeBlockchainUnspentOutput = async (\n state: State,\n unspentOutputsByOutpointKey: Map<string, UnspentOutputData>,\n unspentOutputFromBlockchain: UnspentOutputData,\n): Promise<void> => {\n const outpointKey = getOutpointKey(unspentOutputFromBlockchain.outpointTransactionHash, unspentOutputFromBlockchain.outpointIndex);\n const storedUnspentOutput = unspentOutputsByOutpointKey.get(outpointKey);\n\n // An output seen for the first time is stored with the status Electrum reports.\n if (storedUnspentOutput === undefined) {\n await state.storeUnspentOutputData(unspentOutputFromBlockchain);\n\n return;\n }\n\n // The value and tokens of an outpoint never change, so only a status that differs from the stored one is written.\n if (storedUnspentOutput.status !== unspentOutputFromBlockchain.status) {\n await state.updateUnspentOutputDataStatus(\n unspentOutputFromBlockchain.outpointTransactionHash,\n unspentOutputFromBlockchain.outpointIndex,\n unspentOutputFromBlockchain.status,\n );\n }\n};\n\n/**\n * Synchronizes the store of unspent outputs for a given script hash with the current state of the blockchain.\n *\n * This method performs the following.\n * 1. Reads the stored script hash data and the unspent outputs stored for the script hash.\n * 2. Stores each unspent output in the blockchain list passed in, or updates its stored status when Electrum reports a different one.\n * 3. Removes each stored unspent output that is no longer in that list.\n *\n * @param {State} state - The State instance to use for data operations.\n * @param {string} scriptHash - The script hash for which to update the stored unspent outputs.\n * @param {ScriptHashListUnspentResponse} unspentOutputsFromBlockchain - Unspent outputs Electrum lists for the script hash.\n * @returns {Promise<void>} - Resolves when the stored unspent outputs match the blockchain list.\n * @throws {@link ScriptHashDataNotFoundError} - If the script hash is not found in the state.\n */\nexport const updateUnspentOutputsForScriptHash = async (\n state: State,\n scriptHash: string,\n unspentOutputsFromBlockchain: ScriptHashListUnspentResponse,\n): Promise<void> => {\n const { templateIdentifier, unspentOutputs, unspentOutputsByOutpointKey } = await state.listUnspentOutputsForScriptHash(scriptHash);\n\n const blockchainOutpointKeys = new Set<string>();\n\n for (const unspentOutputFromBlockchain of unspentOutputsFromBlockchain) {\n const outpointKey = getOutpointKey(unspentOutputFromBlockchain.tx_hash, Number(unspentOutputFromBlockchain.tx_pos));\n blockchainOutpointKeys.add(outpointKey);\n\n await storeBlockchainUnspentOutput(\n state,\n unspentOutputsByOutpointKey,\n toUnspentOutputData(unspentOutputFromBlockchain, scriptHash, templateIdentifier),\n );\n }\n\n for (const unspentOutput of unspentOutputs) {\n const outpointKey = getOutpointKey(unspentOutput.outpointTransactionHash, unspentOutput.outpointIndex);\n\n if (blockchainOutpointKeys.has(outpointKey) === false) {\n try {\n await state.deleteUnspentOutputData(unspentOutput.outpointTransactionHash, unspentOutput.outpointIndex);\n } catch (error: unknown) {\n if (error instanceof UnspentOutputNotFoundInStoreError === false) {\n throw error;\n }\n }\n }\n }\n};\n\n/**\n * Lists the unspent outputs that are free to spend.\n *\n * @param {State} state - State that stores the templates, script hashes, and unspent outputs for this account.\n * @param {ListSpendableUnspentOutputsParameters} [options] - Template output and token fields that every returned output must match.\n * @returns {Promise<UnspentOutputData[]>} - The unreserved and selectable unspent outputs that match the provided options.\n * @throws {@link TemplateNotFoundInStoreError} - When the template in the options is not stored.\n * @throws {@link TemplateOutputNotFoundError} - When the output in the options is not defined by that template.\n */\nexport const listSpendableUnspentOutputs = async (state: State, options?: ListSpendableUnspentOutputsParameters): Promise<UnspentOutputData[]> => {\n // Reserved outputs already belong to an invitation, so only unreserved outputs are spendable.\n const unspentOutputDataFilter: UnspentOutputDataFilter = { reserved: false };\n\n // Without options every unreserved and selectable output is spendable.\n if (options === undefined) {\n const unreservedUnspentOutputs = await state.listUnspentOutputsData(undefined, unspentOutputDataFilter);\n\n return unreservedUnspentOutputs.filter((unspentOutput) => unspentOutput.selectable);\n }\n\n // Stored token categories are hex, so the provided category is validated and normalized before matching.\n if (options.tokenCategory !== undefined) {\n unspentOutputDataFilter.tokenCategory = new TokenCategory(options.tokenCategory).toHex();\n }\n\n if (options.tokenAmount !== undefined) {\n unspentOutputDataFilter.tokenAmount = options.tokenAmount;\n }\n\n if (options.tokenNftCapability !== undefined) {\n unspentOutputDataFilter.tokenNftCapability = options.tokenNftCapability;\n }\n\n // Stored NFT commitments are hex, so the provided commitment is validated and normalized before matching.\n if (options.tokenNftCommitment !== undefined) {\n unspentOutputDataFilter.tokenNftCommitment = new NFTCommitment(options.tokenNftCommitment).toHex();\n }\n\n // Validate and normalize the template identifier.\n const templateIdentifier = new TemplateIdentifier(options.templateIdentifier).toHex();\n\n // Get the stored template.\n const storedTemplate = await state.getTemplateOrThrow(templateIdentifier);\n\n // Get the template.\n const template = storedTemplate.template;\n\n // Validate the output identifier.\n if (options.outputIdentifier !== undefined) {\n getTemplateOutputOrThrow(template, options.outputIdentifier);\n }\n\n // Validate the locking script identifier.\n if (options.lockingScriptIdentifier !== undefined) {\n getTemplateLockingScriptIdentifierOrThrow(template, options.lockingScriptIdentifier);\n }\n\n // List the script hashes for the template.\n const scriptHashDataList = await state.listScriptHashData({ templateIdentifier });\n\n // Create a list of unspent outputs.\n const unspentOutputs: UnspentOutputData[] = [];\n\n // Loop through the script hashes.\n for (const scriptHashData of scriptHashDataList) {\n // If the output identifier does not match, skip the script hash.\n if (options.outputIdentifier && scriptHashData.outputIdentifier !== options.outputIdentifier) {\n continue;\n }\n\n // If the locking script identifier does not match, skip the script hash.\n if (options.lockingScriptIdentifier && scriptHashData.lockingScriptIdentifier !== options.lockingScriptIdentifier) {\n continue;\n }\n\n // List the unspent outputs for the script hash.\n const unspentOutputsForScriptHash = await state.listUnspentOutputsData({ scriptHash: scriptHashData.scriptHash }, unspentOutputDataFilter);\n\n // Add the unspent outputs to the list.\n unspentOutputs.push(...unspentOutputsForScriptHash);\n }\n\n // Return the unspent outputs that are selectable.\n return unspentOutputs.filter((unspentOutput) => unspentOutput.selectable);\n};\n","import { binToHex, hexToBin } from '@bitauth/libauth';\nimport type { Crypto, IncompleteScriptCompilation, KeyReference } from '@xo-cash/crypto';\nimport type { SecretData } from '@xo-cash/state';\nimport type {\n XOInvitationIdentifier,\n XOInvitationOutput,\n XOInvitationResolutionIdentifier,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateConstantIdentifier,\n XOTemplateIdentifier,\n XOTemplateLockingScriptIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport {\n LockingBytecodeGenerationFailedError,\n LockingScriptResolutionsMissingError,\n LockingScriptSecretsNotFoundError,\n SecretIdentifierTypeInvalidError,\n TemplateUnlockingScriptNotFoundError,\n} from '../errors/index.ts';\nimport type { AccountContext, InvitationParameters, InvitationResolutionRequirements } from '../invitation/index.ts';\nimport { createLibauthCompilerForLockingScript } from './libauth-utils.ts';\nimport {\n buildResolutionCompilationBytecode,\n groupResolutionRequirements,\n listInvitationCompilationKeys,\n type CompilationKeys,\n} from './compilation-keys.ts';\nimport {\n buildCompilerBytecodeDataFromCompilationVariables,\n buildScriptHashVariablesFromCompilationVariables,\n listInvitationVariablesFromCommits,\n mergeTemplateConstantsWithInvitationVariables,\n omitPrivateKeyVariablesFromCompilationVariables,\n resolveTemplateOutputLockingBytecode,\n} from './template-locking-bytecode.ts';\nimport { getTemplateLockingScriptOrThrow, getTemplateOutputOrThrow, listTemplateSecrets } from '../template.ts';\nimport { generateTemplateIdentifier, isCashAssemblyExpression, scriptToScriptHash } from '@xo-cash/utils';\nimport { isLockingOutputRelevantForRole } from './locking-script-role.ts';\nimport { monitorScriptHash } from '@electrum-cash/application';\nimport { updateUnspentOutputsForScriptHash } from '../state/unspent-outputs.ts';\nimport { fetchScriptHashUnspentOutputs } from '../network/electrum.ts';\nimport { findEntityLockingScriptRole } from '../invitation/helpers/roles.ts';\n\n/**\n * What this account generates a locking bytecode from, with the invitation it is built for in place of that invitation's secrets.\n */\nexport type AccountLockingBytecodeGenerationParameters = Omit<LockingBytecodeGenerationParameters, 'invitationSecrets'> & {\n\n /**\n * Invitation the script is built for, whose already generated keys are used again.\n */\n invitationIdentifier?: XOInvitationIdentifier;\n\n /**\n * Template output the script is built for, when it is built from an output rather than directly from a locking script.\n */\n outputIdentifier?: XOTemplateOutputIdentifier;\n};\n\n/**\n * Constants and invitation variables merged into a locking bytecode compilation.\n */\ntype CompilationVariables = Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>;\n\n/**\n * What a locking script is compiled from when its keys are named by reference.\n */\nexport type LockingBytecodeKeyCompilationParameters = {\n\n /**\n * Template that defines the locking script.\n */\n template: XOTemplate;\n\n /**\n * Locking script to compile.\n */\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Role the script is compiled for, when one is known.\n */\n roleIdentifier?: XOTemplateRoleIdentifier;\n\n /**\n * Constants and invitation variables for WalletData pushes.\n */\n compilationVariables: CompilationVariables;\n\n /**\n * Key reference for each Key variable the script may use.\n */\n keyReferences: Record<string, KeyReference>;\n\n /**\n * Key operations other participants resolved, such as their public keys, for the keys this account does not hold.\n */\n resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array>;\n};\n\n/**\n * What a locking bytecode is generated from.\n */\nexport type LockingBytecodeGenerationParameters = {\n\n /**\n * Template that defines the locking script.\n */\n templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Locking script to compile.\n */\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n /**\n * Role the script is compiled for, when one is known.\n */\n roleIdentifier?: XOTemplateRoleIdentifier;\n\n /**\n * Private key variables to generate, from a generate list. Each one is a new key, even when the invitation already\n * holds a key under the same name.\n */\n secretIdentifiers?: string[];\n\n /**\n * Private key variables the script uses that must already exist among the invitation secrets. They are never generated.\n */\n existingSecretIdentifiers?: string[];\n\n /**\n * Constants and invitation variables for WalletData pushes.\n */\n compilationVariables?: CompilationVariables;\n\n /**\n * Keys and resolved key operations of the invitation the script is built for.\n */\n compilationKeys?: CompilationKeys;\n};\n\n/**\n * Tells whether an incomplete compile only misses identifiers more compilation data could provide.\n *\n * @param {IncompleteScriptCompilation} incompleteCompilation - What the compiler reported when it stopped.\n * @returns {boolean} - True when every compiler error names a missing identifier.\n */\nexport const isOnlyMissingIdentifiers = (incompleteCompilation: IncompleteScriptCompilation): boolean => {\n return (\n incompleteCompilation.missingIdentifiers.length > 0\n && incompleteCompilation.missingIdentifiers.length === incompleteCompilation.compilationErrors.length\n );\n};\n\n/**\n * Compiles the locking bytecode of a template locking script with the given variables and key references.\n *\n * The keys are derived and used only inside the crypto package, which compiles the script and returns the bytecode.\n * Nothing is generated or stored, so the result depends only on the inputs.\n *\n * The script is first compiled with this account's keys alone. When that succeeds, the script uses no other entity's\n * keys. When the compiler reports identifiers missing, the script is shared with entities holding other keys, and those\n * entities can only build or check it with the operations it uses on this account's keys. Those operations must then\n * be among the resolutions before the script is built, so they are reported as missing until they are provided. The\n * script is then compiled with this account's keys and every resolution.\n *\n * @param {Crypto} crypto - Crypto instance that derives the keys and compiles with them.\n * @param {LockingBytecodeKeyCompilationParameters} parameters - Template, locking script, role, variables, and key references.\n * @returns {string} - The locking bytecode as a hexadecimal string.\n * @throws {@link LockingScriptResolutionsMissingError} - When an identifier is missing, including operations on this account's keys that are\n * not provided yet, carrying what the compiler resolved from the keys.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When a supplied role is not on the locking script.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n */\nexport const compileLockingScript = (crypto: Crypto, parameters: LockingBytecodeKeyCompilationParameters): string => {\n const { template, lockingScriptIdentifier, roleIdentifier, compilationVariables, keyReferences, resolutions } = parameters;\n\n // The configuration carries the template scripts and variables, and the script identifier the locking script compiles as.\n const { compilerConfiguration, lockingScriptId } = createLibauthCompilerForLockingScript(template, lockingScriptIdentifier, roleIdentifier);\n\n // Since private keys are not part of the wallet data passed to the compiler, removing those from the resolved compilation variables.\n const walletDataVariables = omitPrivateKeyVariablesFromCompilationVariables(template, compilationVariables);\n const walletDataBytecode = buildCompilerBytecodeDataFromCompilationVariables(template, walletDataVariables);\n\n // A script that compiles with this account's keys alone uses no other entity's keys, so it is built here.\n const ownCompilation = crypto.compileScript({\n compilerConfiguration,\n scriptId: lockingScriptId,\n data: { bytecode: walletDataBytecode },\n keyReferences,\n });\n\n if (ownCompilation instanceof Uint8Array) {\n return binToHex(ownCompilation);\n }\n\n // Any other compile failure becomes the engine's locking bytecode error, carrying the compiler messages.\n if (isOnlyMissingIdentifiers(ownCompilation) === false) {\n throw new LockingBytecodeGenerationFailedError(generateTemplateIdentifier(template), lockingScriptIdentifier, ownCompilation);\n }\n\n const unprovidedIdentifiers: XOInvitationResolutionIdentifier[] = [];\n\n // Entities sharing the script need this account's operations on its keys to build or check it, so they must be provided first.\n for (const resolvedIdentifier of Object.keys(ownCompilation.resolvedKeyOperations)) {\n if (resolutions[resolvedIdentifier] === undefined) {\n unprovidedIdentifiers.push(resolvedIdentifier);\n }\n }\n\n if (unprovidedIdentifiers.length > 0) {\n const missingIdentifiers = [ ...unprovidedIdentifiers ];\n\n // The identifiers other entities have not provided yet are reported with them, so every missing value is named at once.\n for (const missingIdentifier of ownCompilation.missingIdentifiers) {\n if (resolutions[missingIdentifier] === undefined) {\n missingIdentifiers.push(missingIdentifier);\n }\n }\n\n throw new LockingScriptResolutionsMissingError(\n lockingScriptIdentifier,\n missingIdentifiers,\n ownCompilation.resolvedKeyOperations,\n ownCompilation.compilationErrors,\n );\n }\n\n // Operations other entities resolved stand in for the keys this account does not hold.\n const resolutionBytecode = buildResolutionCompilationBytecode(template, resolutions, new Set(Object.keys(keyReferences)));\n\n // The crypto package derives the referenced keys and compiles with them, so only the bytecode comes back.\n const compilation = crypto.compileScript({\n compilerConfiguration,\n scriptId: lockingScriptId,\n data: { bytecode: { ...walletDataBytecode, ...resolutionBytecode } },\n keyReferences,\n });\n\n if (compilation instanceof Uint8Array) {\n return binToHex(compilation);\n }\n\n // When every failure is an identifier missing from the compilation data, another entity can still provide it.\n if (isOnlyMissingIdentifiers(compilation)) {\n throw new LockingScriptResolutionsMissingError(\n lockingScriptIdentifier,\n compilation.missingIdentifiers,\n compilation.resolvedKeyOperations,\n compilation.compilationErrors,\n );\n }\n\n // Any other compile failure becomes the engine's locking bytecode error, carrying the compiler messages.\n throw new LockingBytecodeGenerationFailedError(generateTemplateIdentifier(template), lockingScriptIdentifier, compilation);\n};\n\n/**\n * Lists the key operations a locking script needs from participants, without building it.\n *\n * The script is compiled with this account's keys alone, so every operation on another participant's key is reported\n * as missing whether or not it was provided. Each identifier is then grouped by whether the resolutions already hold it.\n * A script that compiles with this account's keys alone needs nothing from anyone.\n *\n * @param {Crypto} crypto - Crypto instance that derives the keys and compiles with them.\n * @param {LockingBytecodeKeyCompilationParameters} parameters - Template, locking script, role, variables, key references, and resolutions.\n * @returns {InvitationResolutionRequirements} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails for a reason other than a missing identifier.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When a supplied role is not on the locking script.\n */\nexport const listLockingScriptResolutions = (\n crypto: Crypto,\n parameters: LockingBytecodeKeyCompilationParameters,\n): InvitationResolutionRequirements => {\n const { template, lockingScriptIdentifier, roleIdentifier, compilationVariables, keyReferences, resolutions } = parameters;\n\n // The configuration carries the template scripts and variables, and the script identifier the locking script compiles as.\n const { compilerConfiguration, lockingScriptId } = createLibauthCompilerForLockingScript(template, lockingScriptIdentifier, roleIdentifier);\n\n // Private keys are not WalletData, so only the other variables are pushed as bytecode.\n const walletDataBytecode = buildCompilerBytecodeDataFromCompilationVariables(\n template,\n omitPrivateKeyVariablesFromCompilationVariables(template, compilationVariables),\n );\n\n // No resolution is passed, so the compiler reports every operation on a key this account does not hold.\n const compilation = crypto.compileScript({\n compilerConfiguration,\n scriptId: lockingScriptId,\n data: { bytecode: walletDataBytecode },\n keyReferences,\n });\n\n // The script uses no key another participant holds.\n if (compilation instanceof Uint8Array) {\n return { providedIdentifiers: [], ownResolutions: [], missingIdentifiers: [] };\n }\n\n if (isOnlyMissingIdentifiers(compilation)) {\n return groupResolutionRequirements(compilation, resolutions);\n }\n\n // Any other compile failure becomes the engine's locking bytecode error, carrying the compiler messages.\n throw new LockingBytecodeGenerationFailedError(generateTemplateIdentifier(template), lockingScriptIdentifier, compilation);\n};\n\n/**\n * Generates locking bytecode for a template output using Libauth compilation data.\n *\n * Builds `data.keys.privateKeys` for Key variables from locking script role definitions\n * (and optional role scoped secrets when a role was supplied). Merges WalletData from\n * compilationVariables into `data.bytecode`. An invitation role is optional metadata. When\n * present it must exist on the locking script and may populate Libauth `entityOwnership`.\n * Missing Key or WalletData material fails at compile time.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {LockingBytecodeGenerationParameters} parameters - Template, locking script, role, secrets, variables, and invitation keys.\n * All invitation keys and resolved key operations are passed to the compiler. A key named in the generate list is always new and\n * takes the place of an invitation key with the same name.\n * @returns {Promise<{ lockingBytecode: string; secretsData: Array<SecretData>; reusedSecretLookupKeys: string[] }>} - The locking\n * bytecode as a hexadecimal string, the secrets to store, and the lookup keys of the invitation secrets the locking script declares.\n * @throws {@link LockingScriptSecretsNotFoundError} - When an existing secret the script uses is not among the invitation secrets.\n * @throws {@link LockingScriptResolutionsMissingError} - When the script uses key operations no key or resolution provides yet.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When the template defines no way to unlock the locking script.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When a supplied role is not on the locking script.\n * @throws {@link TemplateRoleRelevantCashAssemblyUnsupportedError} - When `relevant` is a CashASM string.\n * @throws {@link SecretIdentifierTypeInvalidError} - When a secret to generate is not declared as a private_key variable.\n */\nexport const generateLockingBytecode = async (\n context: Required<AccountContext>,\n parameters: LockingBytecodeGenerationParameters,\n): Promise<{ lockingBytecode: string; secretsData: Array<SecretData>; reusedSecretLookupKeys: string[] }> => {\n const { templateIdentifier, lockingScriptIdentifier, roleIdentifier, compilationVariables } = parameters;\n const secretIdentifiers = parameters.secretIdentifiers ?? [];\n const compilationKeys = parameters.compilationKeys ?? { keyReferences: {}, secretLookupKeys: {}, resolutions: {} };\n\n // Get the template from the store.\n const storedTemplate = await context.state.getTemplateOrThrow(templateIdentifier);\n const template = storedTemplate.template;\n\n // Create the compiler for the locking script. This checks the role before any derivation index is allocated.\n const { unlockingScriptId } = createLibauthCompilerForLockingScript(template, lockingScriptIdentifier, roleIdentifier);\n\n // A template input can name the unlocking script instead of the locking script.\n let hasTemplateInputUnlockingScript = false;\n\n for (const templateInput of Object.values(template.inputs ?? {})) {\n if (templateInput.unlockingScript !== undefined) {\n hasTemplateInputUnlockingScript = true;\n }\n }\n\n // A locking script the template gives no way to unlock cannot be spent later.\n if (unlockingScriptId === undefined && hasTemplateInputUnlockingScript === false) {\n throw new TemplateUnlockingScriptNotFoundError(templateIdentifier, lockingScriptIdentifier);\n }\n\n const lockingScriptDefinition = getTemplateLockingScriptOrThrow(template, lockingScriptIdentifier);\n\n // Store the secret data to be passed and later stored to the state.\n const secretsData: Array<SecretData> = [];\n\n // Keys this account generated for the invitation are part of the compilation, like the invitation variables.\n const keyReferences: Record<string, KeyReference> = { ...compilationKeys.keyReferences };\n\n const missingExistingSecretIdentifiers: string[] = [];\n\n // Secrets the script expects to exist are only taken from the invitation, since only a generate list creates a secret.\n for (const existingSecretIdentifier of parameters.existingSecretIdentifiers ?? []) {\n if (keyReferences[existingSecretIdentifier] === undefined) {\n missingExistingSecretIdentifiers.push(existingSecretIdentifier);\n }\n }\n\n if (missingExistingSecretIdentifiers.length > 0) {\n throw new LockingScriptSecretsNotFoundError(templateIdentifier, lockingScriptIdentifier, missingExistingSecretIdentifiers, roleIdentifier);\n }\n\n // Variables whose key is generated here, so an invitation key under the same name is not the one the script uses.\n const generatedSecretIdentifiers = new Set<string>();\n\n // If the secret has a type of 'private_key', then we need to generate a new private key and pick\n // a derivative index for it, else throw an error.\n for (const secretIdentifier of secretIdentifiers) {\n if (template.variables?.[secretIdentifier]?.type === 'private_key') {\n // A generate list always asks for a new key, even when the invitation already holds one under this name.\n generatedSecretIdentifiers.add(secretIdentifier);\n\n // Derive a new derivative index for each needed private key type\n const derivativeIndex = await context.state.generateNextDerivativeIndex(templateIdentifier);\n\n // The new key is named by its place in this template's key tree, and the crypto package derives it for the compile.\n keyReferences[secretIdentifier] = { templateIdentifier, derivationIndex: derivativeIndex };\n\n // Constructing this object to be used to store in the state later on.\n secretsData.push({\n secretIdentifier,\n isPrivate: true,\n isEntropy: true,\n value: derivativeIndex.toString(),\n templateIdentifier,\n });\n } else {\n throw new SecretIdentifierTypeInvalidError(templateIdentifier, secretIdentifier, template.variables?.[secretIdentifier]?.type);\n }\n }\n\n // Merge the constants and variables together to be used in the compilation.\n const resolvedCompilationVariables = compilationVariables ?? mergeTemplateConstantsWithInvitationVariables(template, []);\n\n const lockingBytecode = compileLockingScript(context.crypto, {\n template,\n lockingScriptIdentifier,\n roleIdentifier,\n compilationVariables: resolvedCompilationVariables,\n keyReferences,\n resolutions: compilationKeys.resolutions,\n });\n\n // The secrets the locking script declares, for any role, are the ones needed to unlock it later.\n const declaredSecretIdentifiers = new Set<string>(lockingScriptDefinition.state?.secrets ?? []);\n\n if (lockingScriptDefinition.roles !== undefined) {\n for (const lockingScriptRole of Object.values(lockingScriptDefinition.roles)) {\n for (const roleSecretIdentifier of lockingScriptRole.state?.secrets ?? []) {\n declaredSecretIdentifiers.add(roleSecretIdentifier);\n }\n }\n }\n\n // Lookup keys of invitation secrets the script declares, which the caller lists with the script without storing them twice.\n const reusedSecretLookupKeys: string[] = [];\n\n for (const [ secretIdentifier, secretLookupKey ] of Object.entries(compilationKeys.secretLookupKeys)) {\n // A newly generated key replaced the invitation key of the same name, so that invitation key is not part of the script.\n if (declaredSecretIdentifiers.has(secretIdentifier) && generatedSecretIdentifiers.has(secretIdentifier) === false) {\n reusedSecretLookupKeys.push(secretLookupKey);\n }\n }\n\n // Return the lockingbytecode that is generated and secrets data that should be stored in the state.\n return { lockingBytecode, secretsData, reusedSecretLookupKeys };\n};\n\n/**\n * Generates locking bytecode for a template output using Libauth compilation data.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {AccountLockingBytecodeGenerationParameters} parameters - Template, locking script, role, secrets, variables, and the invitation\n * the script is built for.\n * @returns {Promise<string>} - The generated locking bytecode as a hexadecimal string.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - When a supplied role is not on the locking script.\n * @throws {@link TemplateRoleRelevantCashAssemblyUnsupportedError} - When `relevant` is a CashASM string.\n * @throws {@link InvitationNotFoundInStoreError} - When an invitation is given and it is not stored.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for that invitation is not in the secret store.\n * @throws {@link LockingScriptResolutionsMissingError} - When the script uses key operations no key or resolution provides yet.\n * @todo Encrypt the new information and update the encrypted state servers.\n */\nexport const generateAccountLockingBytecode = async (\n context: Required<AccountContext>,\n parameters: AccountLockingBytecodeGenerationParameters,\n): Promise<string> => {\n const {\n templateIdentifier,\n lockingScriptIdentifier,\n roleIdentifier,\n compilationVariables,\n secretIdentifiers,\n existingSecretIdentifiers,\n invitationIdentifier,\n outputIdentifier,\n } = parameters;\n\n // Get the template data from the state.\n const storedTemplate = await context.state.getTemplateOrThrow(templateIdentifier);\n const template = storedTemplate.template;\n\n let compilationKeys: CompilationKeys | undefined;\n\n // A script built for an invitation uses the keys this account already generated for it, and the key operations its participants resolved.\n if (invitationIdentifier !== undefined) {\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n\n compilationKeys = await listInvitationCompilationKeys(context.state, storedInvitation, templateIdentifier);\n }\n\n // Generate the locking bytecode for the template output.\n const { lockingBytecode, secretsData, reusedSecretLookupKeys } = await generateLockingBytecode(context, {\n templateIdentifier,\n lockingScriptIdentifier,\n roleIdentifier,\n secretIdentifiers,\n existingSecretIdentifiers,\n compilationVariables,\n compilationKeys,\n });\n\n // Convert the locking bytecode to a script hash.\n const scriptHash = scriptToScriptHash(hexToBin(lockingBytecode));\n\n // Compile for the transaction even when irrelevant. Skip store and Electrum for irrelevant roles.\n const shouldTrackLockingBytecode = isLockingOutputRelevantForRole({ template, lockingScriptIdentifier, roleIdentifier });\n\n // If the locking output is not relevant for the role, return the locking bytecode.\n if (shouldTrackLockingBytecode === false) {\n return lockingBytecode;\n }\n\n // Try to get the script hash from the state\n const existingScriptHashData = await context.state.getScriptHashData(scriptHash);\n\n // If the script has exists then it's already monitored by the network, return the locking bytecode.\n if (existingScriptHashData !== undefined) {\n return existingScriptHashData.lockingBytecode;\n }\n\n // If the script hash does not exist, subscribe to the script hash updates\n await monitorScriptHash(scriptHash);\n\n let variables: Record<XOTemplateVariableIdentifier, string> | undefined;\n\n // Keep the variable values the script was compiled with so the same script can be rebuilt when it is spent.\n if (compilationVariables !== undefined) {\n variables = buildScriptHashVariablesFromCompilationVariables(template, lockingScriptIdentifier, compilationVariables, roleIdentifier);\n }\n\n // Reused invitation secrets are already stored, so the script lists their existing lookup keys.\n const secretsLoopKeys: Array<string> = [ ...reusedSecretLookupKeys ];\n\n for (const secretData of secretsData) {\n // Store the secrets in the state\n const secretLookupKey = await context.state.storeSecretData({\n secretIdentifier: secretData.secretIdentifier,\n isPrivate: secretData.isPrivate,\n isEntropy: secretData.isEntropy,\n value: secretData.value,\n templateIdentifier: secretData.templateIdentifier,\n });\n\n secretsLoopKeys.push(secretLookupKey);\n }\n\n // Store the script hash data in the state\n // A script built for an invitation records it, so only that invitation counts the script's secrets as its own.\n await context.state.storeScriptHashData({\n lockingBytecode,\n secrets: secretsLoopKeys,\n scriptHash,\n templateIdentifier,\n lockingScriptIdentifier,\n roleIdentifier,\n variables,\n invitationIdentifier,\n outputIdentifier,\n });\n\n // Fetch the unspent outputs from the blockchain\n const unspentOutputsFromBlockchain = await fetchScriptHashUnspentOutputs(scriptHash);\n\n // update the unspent output in the state\n await updateUnspentOutputsForScriptHash(context.state, scriptHash, unspentOutputsFromBlockchain);\n\n return lockingBytecode;\n};\n\n/**\n * Builds the locking bytecode of every output that names a template output but carries no locking bytecode.\n *\n * The script is compiled for the role on the output with the template constants and the variables of the invitation,\n * including the variables appended with the outputs. Keys this account already generated for the invitation are used\n * again, so the output locks to the key the account took with its role instead of a new one.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the outputs are appended to.\n * @param {XOInvitationOutput[]} outputs - Outputs to append.\n * @param {InvitationParameters['variables']} appendedVariables - Variables appended together with the outputs.\n * @returns {Promise<XOInvitationOutput[]>} - The outputs in the same order, each with locking bytecode where it was built.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If an output names a template output the template does not define.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If an output names a role its locking script does not define.\n * @throws {@link LockingBytecodeGenerationFailedError} - If a locking bytecode cannot be compiled.\n * @throws {@link LockingScriptSecretsNotFoundError} - If a locking script uses secrets this account has not generated for the invitation.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n * @throws {@link CashAssemblyCompilationFailedError} - If an output locking script is a CashAssembly expression that cannot be compiled.\n * @throws {@link LockingScriptCompilationFailedError} - If a template locking script an output names cannot be compiled.\n * @throws {@link LockingScriptResolutionsMissingError} - When the script uses key operations no key or resolution provides yet.\n */\nexport const completeTemplateOutputLockingBytecodes = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n outputs: XOInvitationOutput[],\n appendedVariables: InvitationParameters['variables'],\n): Promise<XOInvitationOutput[]> => {\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n const { invitation } = storedInvitation;\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n // Scripts compile with the variables every participant committed so far and the ones appended now.\n const invitationVariables = listInvitationVariablesFromCommits(invitation.commits, appendedVariables);\n const compilationVariables = mergeTemplateConstantsWithInvitationVariables(template, invitationVariables);\n\n const completedOutputs: XOInvitationOutput[] = [];\n\n for (const output of outputs) {\n // An output with its own locking bytecode, or one that names no template output, is appended as given.\n if (output.outputIdentifier === undefined || output.lockingBytecode !== undefined) {\n completedOutputs.push(output);\n\n continue;\n }\n\n const lockingScriptIdentifier = getTemplateOutputOrThrow(template, output.outputIdentifier).lockingScript;\n\n // A CashAssembly expression is compiled from the invitation variables the same way every participant resolves it, without keys.\n if (isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n const expressionLockingBytecode = resolveTemplateOutputLockingBytecode(template, output.outputIdentifier, invitationVariables);\n\n completedOutputs.push({ ...output, lockingBytecode: expressionLockingBytecode });\n\n continue;\n }\n\n let roleIdentifier = output.roleIdentifier;\n\n // An output without a role is built for the role this account holds in the invitation, when the locking script declares it.\n if (roleIdentifier === undefined) {\n roleIdentifier = findEntityLockingScriptRole(invitation, template, storedInvitation.entityIdentifier, lockingScriptIdentifier);\n }\n\n // The role names the existing secrets the script is built with. They are used, never generated.\n const existingSecretIdentifiers = listTemplateSecrets(template, lockingScriptIdentifier, roleIdentifier);\n\n const lockingBytecode = await generateAccountLockingBytecode(context, {\n templateIdentifier: invitation.templateIdentifier,\n lockingScriptIdentifier,\n roleIdentifier,\n existingSecretIdentifiers,\n compilationVariables,\n invitationIdentifier,\n outputIdentifier: output.outputIdentifier,\n });\n\n completedOutputs.push({ ...output, lockingBytecode: hexToBin(lockingBytecode) });\n }\n\n return completedOutputs;\n};\n","import type { StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitationIdentifier } from '@xo-cash/types';\nimport { completeTemplateOutputLockingBytecodes } from '../../compilation/generate-locking-bytecode.ts';\nimport type { AccountContext, InvitationParameters } from '../interfaces.ts';\nimport { applyInvitationAppend } from './apply-append.ts';\n\n/**\n * Appends the invitation with the new information.\n *\n * An output that names a template output without locking bytecode has its locking bytecode built with this account's keys\n * before the commit is appended.\n *\n * @param {Required<AccountContext>} context - State, signing, network, and locking bytecode generation for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to append. The invitation must already exist in the store.\n * @param {InvitationParameters} params - The parameters to append the invitation with.\n * @returns {Promise<StoredInvitation>} - The appended invitation as stored, including the local entity identifier.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link AppendInvitationParametersEmptyError} - When every appendable field is omitted.\n * @throws {@link UnspentOutputReservationExternalConflictError} - If a local outpoint is already reserved by another invitation.\n * @throws {@link UnspentOutputReservationInternalConflictError} - If this invitation already reserves or spends the outpoint.\n * @throws {@link TemplateOutputNotFoundError} - If an output names a template output the template does not define.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If an output names a role its locking script does not define.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking bytecode of an output that names only a template output cannot be compiled.\n * @throws {@link LockingScriptSecretsNotFoundError} - If such an output's locking script uses secrets this account has not generated for the\n * invitation.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n * @throws {@link LockingScriptResolutionsMissingError} - When the script uses key operations no key or resolution provides yet.\n */\nexport const appendInvitation = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n params: InvitationParameters,\n): Promise<StoredInvitation> => {\n let appendParameters = params;\n\n // Outputs that name a template output without locking bytecode have it built here, since only this account holds the keys.\n if (params.outputs !== undefined) {\n const outputs = await completeTemplateOutputLockingBytecodes(context, invitationIdentifier, params.outputs, params.variables);\n\n appendParameters = { ...params, outputs };\n }\n\n // Fetch the invitation from the store to confirm it exists.\n const invitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n\n return applyInvitationAppend(context, invitation, appendParameters);\n};\n","import { UNDEFINED_TRANSACTION_INDEX_SORT_VALUE } from '../../defaults.ts';\nimport { TransactionIndexDuplicatedError } from '../../errors/index.ts';\nimport type { MergeItemType, MergeableItem, MergedItemWithIntroductionOrder } from './types.ts';\n\n/**\n * Validates that no two resolved items claim the same transactionIndex.\n *\n * @param {readonly ResolvedItem[]} resolvedItems - Resolved inputs or outputs in introduction order.\n * @param {MergeItemType} itemType - Whether the items are inputs or outputs for the error message.\n * @throws {@link TransactionIndexDuplicatedError} - When two or more items share the same transactionIndex.\n */\nexport const validateTransactionIndices = <ResolvedItem extends MergeableItem>(\n resolvedItems: readonly ResolvedItem[],\n itemType: MergeItemType,\n): void => {\n // Collect every position that claims each transactionIndex.\n const itemPositionsByTransactionIndex = new Map<number, number[]>();\n\n for (const [ itemPosition, resolvedItem ] of resolvedItems.entries()) {\n const { transactionIndex } = resolvedItem;\n\n // Items without a transactionIndex are ordered later and cannot collide here.\n if (transactionIndex === undefined) {\n continue;\n }\n\n const itemPositions = itemPositionsByTransactionIndex.get(transactionIndex) ?? [];\n itemPositions.push(itemPosition);\n itemPositionsByTransactionIndex.set(transactionIndex, itemPositions);\n }\n\n const duplicateGroups: Array<{ transactionIndex: number; itemPositions: number[] }> = [];\n\n for (const [ transactionIndex, itemPositions ] of itemPositionsByTransactionIndex.entries()) {\n // Only indexes claimed by more than one merged item are reported.\n if (itemPositions.length > 1) {\n duplicateGroups.push({\n transactionIndex,\n itemPositions,\n });\n }\n }\n\n // Every duplicate is reported together so all conflicting commits can be fixed at once.\n if (duplicateGroups.length > 0) {\n throw new TransactionIndexDuplicatedError(itemType, duplicateGroups);\n }\n};\n\n/**\n * Lists merged items in the order their funding items were introduced.\n *\n * Items that share an introduction order, such as two outputs that extend the same funding output, keep the order\n * they arrived in.\n *\n * @param {Array<MergedItemWithIntroductionOrder<MergedItem>>} itemsWithIntroductionOrder - Merged inputs or outputs.\n * @returns {MergedItem[]} - Merged items in introduction order.\n */\nexport const orderByIntroduction = <MergedItem extends MergeableItem>(\n itemsWithIntroductionOrder: Array<MergedItemWithIntroductionOrder<MergedItem>>,\n): MergedItem[] => {\n const itemsInIntroductionOrder: Array<MergedItemWithIntroductionOrder<MergedItem>> = [];\n\n for (const candidateItem of itemsWithIntroductionOrder) {\n let insertionPosition = itemsInIntroductionOrder.length;\n\n // Move left only past items introduced later, so items that tie keep their arrival order.\n while (insertionPosition > 0) {\n const precedingItem = itemsInIntroductionOrder[insertionPosition - 1];\n\n if (candidateItem.introductionOrder >= precedingItem.introductionOrder) {\n break;\n }\n\n insertionPosition -= 1;\n }\n\n itemsInIntroductionOrder.splice(insertionPosition, 0, candidateItem);\n }\n\n const mergedItems: MergedItem[] = [];\n\n // The list is now in introduction order, so the order numbers are no longer needed.\n for (const itemWithIntroductionOrder of itemsInIntroductionOrder) {\n mergedItems.push(itemWithIntroductionOrder.mergedItem);\n }\n\n return mergedItems;\n};\n\n/**\n * Puts resolved items in final transaction order.\n *\n * Items with a transactionIndex come first in index order and items without one follow. The items arrive in\n * introduction order, and items that tie keep that order, so an item never moves because a later commit extended it.\n *\n * @param {readonly ResolvedItem[]} resolvedItems - Resolved inputs or outputs in introduction order.\n * @returns {ResolvedItem[]} - Resolved items in transaction order.\n */\nexport const orderByTransactionIndex = <ResolvedItem extends MergeableItem>(resolvedItems: readonly ResolvedItem[]): ResolvedItem[] => {\n const itemsInTransactionOrder: ResolvedItem[] = [];\n\n for (const candidateItem of resolvedItems) {\n // Items without a transactionIndex sort after every indexed item.\n const candidateTransactionIndex = candidateItem.transactionIndex ?? UNDEFINED_TRANSACTION_INDEX_SORT_VALUE;\n let insertionPosition = itemsInTransactionOrder.length;\n\n // Move left only past items with a higher index, so items that tie keep their introduction order.\n while (insertionPosition > 0) {\n const precedingItem = itemsInTransactionOrder[insertionPosition - 1];\n const precedingTransactionIndex = precedingItem.transactionIndex ?? UNDEFINED_TRANSACTION_INDEX_SORT_VALUE;\n\n if (candidateTransactionIndex >= precedingTransactionIndex) {\n break;\n }\n\n insertionPosition -= 1;\n }\n\n itemsInTransactionOrder.splice(insertionPosition, 0, candidateItem);\n }\n\n return itemsInTransactionOrder;\n};\n","import type {\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateConstantIdentifier,\n XOTemplateIntent,\n XOTemplateLockingScriptIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport { listTemplateSecretIdentifiers, createLibauthCompilerForLockingScript, isLibauthKeyTemplateVariable } from './libauth-utils.ts';\nimport {\n buildCompilerBytecodeDataFromCompilationVariables,\n mergeTemplateConstantsWithInvitationVariables,\n omitPrivateKeyVariablesFromCompilationVariables,\n} from './template-locking-bytecode.ts';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport { IntentVariablesMissingError } from '../errors/index.ts';\n\n/**\n * Variable values an intent sets itself and the variables it leaves for the caller to provide.\n */\nexport type IntentVariableRequirements = {\n\n /**\n * Values the intent fixes for its variables.\n */\n presetVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>;\n\n /**\n * Variables the intent lists with a null value, which the caller must provide.\n */\n requiredVariableIdentifiers: XOTemplateVariableIdentifier[];\n};\n\n/**\n * Reads the variables an intent declares.\n *\n * An intent lists variables as single entry objects. A null value marks a variable the caller must provide\n * when something is created from the intent. Any other value is a preset used as is.\n *\n * @param {XOTemplateIntent} intent - Intent from the template defaults.\n * @returns {IntentVariableRequirements} - Preset values and the identifiers the caller must provide.\n */\nexport const readIntentVariableRequirements = (intent: XOTemplateIntent): IntentVariableRequirements => {\n const presetVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue> = {};\n const requiredVariableIdentifiers: XOTemplateVariableIdentifier[] = [];\n\n for (const variableEntry of intent.variables ?? []) {\n for (const [ variableIdentifier, variableValue ] of Object.entries(variableEntry)) {\n // A null value leaves the variable for the caller to provide.\n if (variableValue === null) {\n requiredVariableIdentifiers.push(variableIdentifier);\n\n continue;\n }\n\n // @ts-expect-error Variable values are typed as unknown.\n presetVariableValues[variableIdentifier] = variableValue;\n }\n }\n\n return {\n presetVariableValues,\n requiredVariableIdentifiers,\n };\n};\n\n/**\n * Lists the variables a locking script still needs after the given values are applied.\n *\n * The script is compiled once without any keys. Libauth reports every variable it could not resolve as a recoverable error\n * naming the missing identifier. Key variables are left out because they are derived when the locking bytecode is generated,\n * so only the values a caller must provide remain. No derivation index is used.\n *\n * @param {XOTemplate} template - Template that defines the locking script.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script that will be generated.\n * @param {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} compilationVariables - Values already\n * known, such as template constants and intent presets.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role the locking bytecode is generated for, when the intent names one.\n * @returns {XOTemplateVariableIdentifier[]} - Variables the locking script needs that the known values do not supply.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is not defined by the template.\n */\nconst listLockingScriptMissingVariableIdentifiers = (\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n compilationVariables: Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): XOTemplateVariableIdentifier[] => {\n const { compiler, lockingScriptId } = createLibauthCompilerForLockingScript(template, lockingScriptIdentifier, roleIdentifier);\n\n // Keys belong in data.keys, so only the WalletData values are passed to the dry compile.\n const walletDataVariables = omitPrivateKeyVariablesFromCompilationVariables(template, compilationVariables);\n\n // Compile with the known WalletData only, so every other value the script references is reported as missing.\n const compilationResult = compiler.generateBytecode({\n data: {\n bytecode: buildCompilerBytecodeDataFromCompilationVariables(template, walletDataVariables),\n },\n scriptId: lockingScriptId,\n });\n\n if (compilationResult.success === true) {\n return [];\n }\n\n const templateVariables = template.variables ?? {};\n const templateSecretIdentifiers = listTemplateSecretIdentifiers(template);\n const missingVariableIdentifiers: XOTemplateVariableIdentifier[] = [];\n\n for (const compilationError of compilationResult.errors) {\n // Only recoverable errors name a value that could be provided. Other failures surface when the bytecode is generated.\n if ('missingIdentifier' in compilationError === false) {\n continue;\n }\n\n // Operations such as public_key follow a dot, and the variable is the part before it.\n const [ variableIdentifier ] = compilationError.missingIdentifier.split('.');\n\n // Keys are derived during generation, so the caller never provides them.\n if (isLibauthKeyTemplateVariable(variableIdentifier, templateSecretIdentifiers, templateVariables[variableIdentifier]) === true) {\n continue;\n }\n\n if (missingVariableIdentifiers.includes(variableIdentifier) === false) {\n missingVariableIdentifiers.push(variableIdentifier);\n }\n }\n\n return missingVariableIdentifiers;\n};\n\n/**\n * Lists every variable a caller must provide to create a locking bytecode from an intent.\n *\n * These are the variables the intent marks with a null value, plus any the target locking script needs\n * that neither the template constants nor the intent presets supply.\n *\n * @param {XOTemplate} template - Template that defines the intent target.\n * @param {XOTemplateIntent} intent - Intent from the template defaults.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script the intent generates.\n * @returns {XOTemplateVariableIdentifier[]} - Required variable identifiers, intent variables first.\n * @throws {@link TemplateLockingScriptNotFoundError} - When the locking script is not defined by the template.\n */\nexport const listIntentRequiredVariableIdentifiers = (\n template: XOTemplate,\n intent: XOTemplateIntent,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n): XOTemplateVariableIdentifier[] => {\n const { presetVariableValues, requiredVariableIdentifiers } = readIntentVariableRequirements(intent);\n\n const knownVariableValues = {\n ...mergeTemplateConstantsWithInvitationVariables(template, []),\n ...presetVariableValues,\n };\n\n const requiredIdentifiers = [ ...requiredVariableIdentifiers ];\n\n const lockingScriptMissingVariableIdentifiers = listLockingScriptMissingVariableIdentifiers(\n template,\n lockingScriptIdentifier,\n knownVariableValues,\n intent.role,\n );\n\n // Add what the locking script needs beyond the intent list, so an intent that lists nothing still asks for its script values.\n for (const missingVariableIdentifier of lockingScriptMissingVariableIdentifiers) {\n if (requiredIdentifiers.includes(missingVariableIdentifier) === false) {\n requiredIdentifiers.push(missingVariableIdentifier);\n }\n }\n\n return requiredIdentifiers;\n};\n\n/**\n * Builds the compilation variables for creating a locking bytecode from an intent.\n *\n * Template constants come first, then the intent presets, then the provided values. Every variable from\n * {@link listIntentRequiredVariableIdentifiers} must be provided, so a missing value fails here with the full list\n * instead of later inside the compiler.\n *\n * @param {XOTemplate} template - Template that defines the intent target.\n * @param {XOTemplateIntent} intent - Intent from the template defaults.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script the intent generates.\n * @param {Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>} providedVariableValues - Values supplied by the caller.\n * @returns {Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue>} - Variables for compilation.\n * @throws {@link IntentVariablesMissingError} - When a required variable has no provided value.\n */\nexport const resolveIntentCompilationVariables = (\n template: XOTemplate,\n intent: XOTemplateIntent,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n providedVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>,\n): Record<XOTemplateVariableIdentifier | XOTemplateConstantIdentifier, XOInvitationVariableValue> => {\n const { presetVariableValues } = readIntentVariableRequirements(intent);\n const requiredVariableIdentifiers = listIntentRequiredVariableIdentifiers(template, intent, lockingScriptIdentifier);\n\n const missingVariableIdentifiers: XOTemplateVariableIdentifier[] = [];\n\n // Collect every missing value so the caller can supply them all at once.\n for (const requiredVariableIdentifier of requiredVariableIdentifiers) {\n if (providedVariableValues[requiredVariableIdentifier] === undefined) {\n missingVariableIdentifiers.push(requiredVariableIdentifier);\n }\n }\n\n if (missingVariableIdentifiers.length > 0) {\n throw new IntentVariablesMissingError(generateTemplateIdentifier(template), lockingScriptIdentifier, missingVariableIdentifiers);\n }\n\n // Provided values win over presets, and presets win over template constants with the same identifier.\n return {\n ...mergeTemplateConstantsWithInvitationVariables(template, []),\n ...presetVariableValues,\n ...providedVariableValues,\n };\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { StoredInvitation } from '@xo-cash/state';\nimport type {\n XOInvitationIdentifier,\n XOTemplate,\n XOTemplateLockingScriptIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n} from '@xo-cash/types';\nimport { isCashAssemblyExpression } from '@xo-cash/utils';\nimport { getTemplateOutputOrThrow, listTemplateSecrets } from '../../template.ts';\nimport {\n compileLockingScript,\n listInvitationVariablesFromCommits,\n listLockingScriptResolutions,\n mergeTemplateConstantsWithInvitationVariables,\n listInvitationCompilationKeys,\n resolveTemplateOutputLockingBytecode,\n type LockingBytecodeKeyCompilationParameters,\n} from '../../compilation/index.ts';\nimport { LockingScriptSecretsNotFoundError, OutputOwnResolutionsNotFoundError } from '../../errors/index.ts';\nimport type { AccountContext, InvitationResolutionRequirements } from '../interfaces.ts';\nimport { applyInvitationAppend } from '../participation/apply-append.ts';\n\n/**\n * Collects what an invitation output's keyed locking script compiles from, the same as when the output is added.\n *\n * @param {Pick<Required<AccountContext>, 'state' | 'crypto'>} context - State that stores the invitation and its secrets.\n * @param {StoredInvitation} storedInvitation - Invitation the output belongs to.\n * @param {XOTemplate} template - Template of the invitation.\n * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - Locking script of the output.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<LockingBytecodeKeyCompilationParameters>} - Variables, keys, and resolutions the locking script compiles with.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\nconst prepareOutputKeyCompilation = async (\n context: Pick<Required<AccountContext>, 'state' | 'crypto'>,\n storedInvitation: StoredInvitation,\n template: XOTemplate,\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): Promise<LockingBytecodeKeyCompilationParameters> => {\n const { invitation } = storedInvitation;\n\n // The same context the output compiles with when it is added.\n const invitationVariables = listInvitationVariablesFromCommits(invitation.commits);\n const compilationVariables = mergeTemplateConstantsWithInvitationVariables(template, invitationVariables);\n const compilationKeys = await listInvitationCompilationKeys(context.state, storedInvitation, invitation.templateIdentifier);\n\n // Secrets the locking script declares for this role must already be held by the invitation, since they are never generated for it.\n const secretsNotFound: string[] = [];\n\n for (const secretIdentifier of listTemplateSecrets(template, lockingScriptIdentifier, roleIdentifier)) {\n if (compilationKeys.keyReferences[secretIdentifier] === undefined) {\n secretsNotFound.push(secretIdentifier);\n }\n }\n\n if (secretsNotFound.length > 0) {\n throw new LockingScriptSecretsNotFoundError(\n invitation.templateIdentifier,\n lockingScriptIdentifier,\n secretsNotFound,\n roleIdentifier,\n invitation.invitationIdentifier,\n );\n }\n\n return {\n template,\n lockingScriptIdentifier,\n roleIdentifier,\n compilationVariables,\n keyReferences: compilationKeys.keyReferences,\n resolutions: compilationKeys.resolutions,\n };\n};\n\n/**\n * Resolves the locking bytecode an invitation output compiles to, without generating or storing anything.\n *\n * The locking script compiles with the template constants, the invitation variables, and the keys this account already\n * generated for the invitation, which is what appending the output uses. It is the keyed counterpart of resolving a\n * template output from variables alone. The script's secrets are existing secrets and are never generated for it, so a\n * secret the invitation does not hold fails the resolution the same way adding the output would.\n *\n * @param {Pick<Required<AccountContext>, 'state' | 'crypto'>} context - State that stores the invitation and crypto that compiles with its keys.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output to resolve.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<string>} - The locking bytecode as a hexadecimal string.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingScriptResolutionsMissingError} - If the script uses key operations other participants have not resolved yet.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking bytecode cannot be compiled.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n * @throws {@link CashAssemblyCompilationFailedError} - If the output locking script is a CashAssembly expression that cannot be compiled.\n * @throws {@link LockingScriptCompilationFailedError} - If the template locking script the output names cannot be compiled.\n */\nexport const resolveInvitationOutputLockingBytecode = async (\n context: Pick<Required<AccountContext>, 'state' | 'crypto'>,\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): Promise<string> => {\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n const { invitation } = storedInvitation;\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n const lockingScriptIdentifier = getTemplateOutputOrThrow(template, outputIdentifier).lockingScript;\n\n // An output whose locking script is a CashAssembly expression is compiled from the invitation variables and uses no keys.\n if (isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n const invitationVariables = listInvitationVariablesFromCommits(invitation.commits);\n const expressionLockingBytecode = resolveTemplateOutputLockingBytecode(template, outputIdentifier, invitationVariables);\n\n return binToHex(expressionLockingBytecode);\n }\n\n const compilationParameters = await prepareOutputKeyCompilation(context, storedInvitation, template, lockingScriptIdentifier, roleIdentifier);\n\n // The crypto package derives the invitation keys and compiles with them, so only the bytecode comes back.\n // Operations other participants resolved, such as their public keys, stand in for the keys this account does not hold.\n return compileLockingScript(context.crypto, compilationParameters);\n};\n\n/**\n * Lists the key operations an invitation output's locking script needs from participants, without adding anything.\n *\n * The output compiles with the same variables, keys, and resolutions as when it is added. Each operation is reported as\n * provided when the invitation holds it, as this account's own when only this account's keys resolve it, or as missing\n * when another participant holds the key. An output whose locking script is a CashAssembly expression uses no keys.\n *\n * @param {Pick<Required<AccountContext>, 'state' | 'crypto'>} context - State that stores the invitation and crypto that compiles with its keys.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output to check.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<InvitationResolutionRequirements>} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking script fails to compile for a reason other than a missing identifier.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\nexport const listOutputResolutions = async (\n context: Pick<Required<AccountContext>, 'state' | 'crypto'>,\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): Promise<InvitationResolutionRequirements> => {\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n const storedTemplate = await context.state.getTemplateOrThrow(storedInvitation.invitation.templateIdentifier);\n const template = storedTemplate.template;\n const lockingScriptIdentifier = getTemplateOutputOrThrow(template, outputIdentifier).lockingScript;\n\n // A CashAssembly expression is compiled from variables alone, so no participant provides anything for it.\n if (isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n return { providedIdentifiers: [], ownResolutions: [], missingIdentifiers: [] };\n }\n\n const compilationParameters = await prepareOutputKeyCompilation(context, storedInvitation, template, lockingScriptIdentifier, roleIdentifier);\n\n return listLockingScriptResolutions(context.crypto, compilationParameters);\n};\n\n/**\n * Adds the key operations this account resolved for an invitation output to the invitation, so other participants can\n * compile the same locking script.\n *\n * Only values the invitation does not hold yet are added, in one commit. Use {@link listOutputResolutions}\n * first to check that there is something to add.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output whose locking script the values are for.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit with the values.\n * @throws {@link OutputOwnResolutionsNotFoundError} - If this account resolved nothing the invitation does not already hold.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking script fails to compile for a reason other than a missing identifier.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\nexport const appendOwnOutputResolutions = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n): Promise<StoredInvitation> => {\n const { ownResolutions } = await listOutputResolutions(context, invitationIdentifier, outputIdentifier, roleIdentifier);\n\n // Nothing is committed when the invitation already holds every value this account can resolve.\n if (ownResolutions.length === 0) {\n throw new OutputOwnResolutionsNotFoundError(invitationIdentifier, outputIdentifier);\n }\n\n const storedInvitation = await context.state.getInvitationOrThrow(invitationIdentifier);\n\n // The values are commit resolutions, so every participant compiles the locking script with them.\n return applyInvitationAppend(context, storedInvitation, { resolutions: ownResolutions });\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { ScriptHashData, StoredInvitation } from '@xo-cash/state';\nimport { isCashAssemblyExpression, scriptToScriptHash } from '@xo-cash/utils';\nimport {\n buildScriptHashVariablesFromCompilationVariables,\n compileLockingScript,\n isLockingOutputRelevantForRole,\n listInvitationVariablesFromCommits,\n mergeTemplateConstantsWithInvitationVariables,\n listInvitationCompilationKeys,\n} from '../../compilation/index.ts';\nimport { LockingBytecodeGenerationFailedError, LockingScriptResolutionsMissingError } from '../../errors/index.ts';\nimport type { AccountContext } from '../interfaces.ts';\n\n/**\n * Lists the outputs of an invitation that are relevant to this account, but not stored yet.\n *\n * An output is relevant to this account when the account holds secrets the locking script declares for one of its roles,\n * and compiling the script for that role with those keys and the invitation's resolutions gives the output's locking bytecode.\n * Each such output is returned as the script hash data to store, so the account can track it and later unlock it with the same keys.\n *\n * @param {Pick<Required<AccountContext>, 'state' | 'crypto'>} context - State that stores the invitation and crypto that compiles with its keys.\n * @param {StoredInvitation} storedInvitation - Invitation whose outputs are checked.\n * @returns {Promise<ScriptHashData[]>} - Script hash data of every output relevant to this account that is not stored yet.\n * @throws {@link TemplateNotFoundInStoreError} - If the invitation template is not stored.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - If a resolution is not an operation on a template key.\n */\nexport const listRelevantInvitationOutputsMissingFromStore = async (\n context: Pick<Required<AccountContext>, 'state' | 'crypto'>,\n storedInvitation: StoredInvitation,\n): Promise<ScriptHashData[]> => {\n // Get the invitation from stored invitation\n const { invitation } = storedInvitation;\n\n // Get the template from the invitation\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n // Resolve the compilation keys for the invitation\n const compilationKeys = await listInvitationCompilationKeys(context.state, storedInvitation, invitation.templateIdentifier);\n\n // Merge the template constants with the invitation variables\n const compilationVariables = mergeTemplateConstantsWithInvitationVariables(template, listInvitationVariablesFromCommits(invitation.commits));\n const relevantOutputScripts: ScriptHashData[] = [];\n const listedScriptHashes = new Set<string>();\n\n for (const commit of invitation.commits) {\n for (const output of commit.data.outputs ?? []) {\n // Only an output that names a template output and carries its bytecode can be rebuilt and compared.\n if (output.outputIdentifier === undefined || output.lockingBytecode === undefined) {\n continue;\n }\n\n const lockingScriptIdentifier = template.outputs?.[output.outputIdentifier]?.lockingScript;\n\n // A CashAssembly expression is built from variables alone, so it is never locked to this account's keys.\n if (lockingScriptIdentifier === undefined || isCashAssemblyExpression(lockingScriptIdentifier) === true) {\n continue;\n }\n\n const scriptHash = scriptToScriptHash(output.lockingBytecode);\n\n // A script this account already stores, such as one it built itself, is already tracked.\n let isScriptListed = listedScriptHashes.has(scriptHash);\n\n // Storage is only read for a script this call has not already listed.\n if (isScriptListed === false) {\n const storedScriptHashData = await context.state.getScriptHashData(scriptHash);\n isScriptListed = storedScriptHashData !== undefined;\n }\n\n if (isScriptListed) {\n continue;\n }\n\n const lockingScriptRoles = template.lockingScripts?.[lockingScriptIdentifier]?.roles ?? {};\n\n for (const [ roleIdentifier, lockingScriptRole ] of Object.entries(lockingScriptRoles)) {\n const roleSecretIdentifiers = lockingScriptRole.state?.secrets ?? [];\n let holdsEveryRoleSecret = roleSecretIdentifiers.length > 0;\n\n // The account can only unlock the output later for a role whose every secret it holds.\n for (const roleSecretIdentifier of roleSecretIdentifiers) {\n if (compilationKeys.keyReferences[roleSecretIdentifier] === undefined) {\n holdsEveryRoleSecret = false;\n }\n }\n\n // Tracking is skipped for a role the template marks as not relevant, the same as for scripts this account builds.\n const isTrackedRole = holdsEveryRoleSecret && isLockingOutputRelevantForRole({ template, lockingScriptIdentifier, roleIdentifier });\n\n if (isTrackedRole === false) {\n continue;\n }\n\n let rebuiltLockingBytecode: string;\n\n try {\n // The account's own keys are used for its operations, and the resolutions for every other participant's.\n rebuiltLockingBytecode = compileLockingScript(context.crypto, {\n template,\n lockingScriptIdentifier,\n roleIdentifier,\n compilationVariables,\n keyReferences: compilationKeys.keyReferences,\n resolutions: compilationKeys.resolutions,\n });\n } catch (compilationIssue: unknown) {\n // An output this account cannot rebuild is not locked to it, so it is not tracked.\n const isMissingResolution = compilationIssue instanceof LockingScriptResolutionsMissingError;\n\n // An output this account cannot rebuild is not locked to it, so it is not tracked.\n const isLockingBytecodeIncomplete = isMissingResolution || compilationIssue instanceof LockingBytecodeGenerationFailedError;\n\n if (isLockingBytecodeIncomplete) {\n continue;\n }\n\n throw compilationIssue;\n }\n\n // Any other bytecode is locked to keys this account does not hold, even when the role matches.\n if (rebuiltLockingBytecode !== binToHex(output.lockingBytecode)) {\n continue;\n }\n\n const secretLookupKeys: string[] = [];\n\n // The role secrets are the keys that unlock the output later.\n for (const roleSecretIdentifier of roleSecretIdentifiers) {\n secretLookupKeys.push(compilationKeys.secretLookupKeys[roleSecretIdentifier]);\n }\n\n listedScriptHashes.add(scriptHash);\n relevantOutputScripts.push({\n scriptHash,\n lockingBytecode: rebuiltLockingBytecode,\n templateIdentifier: invitation.templateIdentifier,\n lockingScriptIdentifier,\n outputIdentifier: output.outputIdentifier,\n roleIdentifier,\n invitationIdentifier: invitation.invitationIdentifier,\n secrets: secretLookupKeys,\n variables: buildScriptHashVariablesFromCompilationVariables(\n template,\n lockingScriptIdentifier,\n compilationVariables,\n roleIdentifier,\n ),\n });\n\n break;\n }\n }\n }\n\n return relevantOutputScripts;\n};\n","import { verifyInvitationTransactionCreatedResultSignature } from '@xo-cash/crypto';\nimport type {\n XOInvitation,\n XOInvitationIdentifier,\n XOInvitationTransactionHash,\n XOInvitationTransactionResult,\n XOTemplate,\n XOTemplateTransactionIdentifier,\n} from '@xo-cash/types';\nimport { TransactionHash } from '@xo-cash/primitives';\nimport { getTemplateActionTransactionIdentifierOrThrow } from '../../template.ts';\nimport type { InvitationCommitHistoryComparison } from './commits.ts';\n\n/**\n * Reads the persisted transaction hash for one template transaction.\n *\n * Write paths construct {@link TransactionHash} before persist, so a stored hash is already valid.\n *\n * @param {XOInvitation} invitation - Invitation that may store the hash under `result.transactions`.\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier for the action.\n * @returns {XOInvitationTransactionHash | undefined} - Transaction hash when present, otherwise undefined.\n */\nexport const getInvitationTransactionHash = (\n invitation: XOInvitation,\n transactionIdentifier: XOTemplateTransactionIdentifier,\n): XOInvitationTransactionHash | undefined => {\n // A stored hash was already constructed as TransactionHash, so absence is the only gap to report.\n return invitation.result?.transactions?.[transactionIdentifier]?.transactionHash;\n};\n\n/**\n * Returns true when a stored transaction created result has a verifiable Schnorr signature.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation that owns the transaction result.\n * @param {XOInvitationTransactionResult} transactionResult - Transaction result to inspect.\n * @returns {boolean} - Whether the created result is complete enough to treat as persisted execution output.\n */\nexport const isInvitationTransactionCreatedResultComplete = (\n invitationIdentifier: XOInvitationIdentifier,\n transactionResult: XOInvitationTransactionResult,\n): boolean => {\n // Write paths construct SchnorrSignature before persist, so only absence means incomplete.\n if (transactionResult.createdBySignature === undefined) {\n return false;\n }\n\n try {\n return verifyInvitationTransactionCreatedResultSignature({\n invitationIdentifier,\n transactionResult,\n });\n } catch (verificationError: unknown) {\n if (verificationError instanceof Error === false) {\n throw verificationError;\n }\n\n // Leftover results that cannot decode an entity identifier are incomplete, not a hard write failure.\n return false;\n }\n};\n\n/**\n * Attaches one transaction result to an invitation under `result.transactions`.\n *\n * @param {XOInvitation} invitation - Invitation to update.\n * @param {XOTemplateTransactionIdentifier} transactionIdentifier - Template transaction identifier for the action.\n * @param {XOInvitationTransactionResult} transactionResult - Transaction result to store.\n * @returns {XOInvitation} - Invitation with the transaction result merged into `result`.\n */\nexport const applyInvitationTransactionResultToInvitation = (\n invitation: XOInvitation,\n transactionIdentifier: XOTemplateTransactionIdentifier,\n transactionResult: XOInvitationTransactionResult,\n): XOInvitation => {\n return {\n ...invitation,\n result: {\n ...invitation.result,\n transactions: {\n ...invitation.result?.transactions,\n [transactionIdentifier]: transactionResult,\n },\n },\n };\n};\n\n/**\n * Returns true when an update changes only the persisted transaction hash and leaves commit history unchanged.\n *\n * @param {XOInvitation} storedInvitation - Invitation currently in local storage.\n * @param {XOInvitation} incomingInvitation - Invitation from shared JSON or remote sync.\n * @param {XOTemplate} template - Template that defines the action transaction key.\n * @param {InvitationCommitHistoryComparison} invitationCommitHistoryComparison - Commit history diff from compareInvitationCommitHistories.\n * @returns {boolean} - Whether validation can be skipped for a hash only write.\n */\nexport const isInvitationTransactionHashOnlyUpdate = (\n storedInvitation: XOInvitation,\n incomingInvitation: XOInvitation,\n template: XOTemplate,\n invitationCommitHistoryComparison: InvitationCommitHistoryComparison,\n): boolean => {\n if (invitationCommitHistoryComparison.historyConflictCommitIdentifier !== null) {\n return false;\n }\n\n if (invitationCommitHistoryComparison.newCommitCount !== 0) {\n return false;\n }\n\n const transactionIdentifier = getTemplateActionTransactionIdentifierOrThrow(template, incomingInvitation.actionIdentifier);\n const storedTransactionResult = storedInvitation.result?.transactions?.[transactionIdentifier];\n const incomingTransactionResult = incomingInvitation.result?.transactions?.[transactionIdentifier];\n\n // A signed created result the stored invitation lacks is a new result, so it is validated and stored in full.\n const isNewCreatedResult =\n storedTransactionResult === undefined\n && incomingTransactionResult !== undefined\n && isInvitationTransactionCreatedResultComplete(incomingInvitation.invitationIdentifier, incomingTransactionResult);\n\n if (isNewCreatedResult === true) {\n return false;\n }\n\n const storedTransactionHash = getInvitationTransactionHash(storedInvitation, transactionIdentifier);\n const incomingTransactionHash = getInvitationTransactionHash(incomingInvitation, transactionIdentifier);\n\n // Presence is enough because a stored hash was validated at write time.\n return incomingTransactionHash !== undefined && incomingTransactionHash !== storedTransactionHash;\n};\n\n/**\n * Merges an incoming hash only update into the stored invitation result while preserving other result metadata.\n *\n * A hash is written only onto an existing created result. Incomplete entity or signature placeholders are never synthesized.\n *\n * @param {XOInvitation} storedInvitation - Shared invitation currently in local storage.\n * @param {XOInvitation} incomingInvitation - Shared invitation carrying the new hash.\n * @param {XOTemplate} template - Template that defines the action transaction key.\n * @returns {XOInvitation} - Shared invitation ready for persistence with the updated transaction hash.\n * @throws {Error} - When the incoming hash fails {@link TransactionHash} construction.\n */\nexport const mergeInvitationTransactionHashOnlyUpdate = (\n storedInvitation: XOInvitation,\n incomingInvitation: XOInvitation,\n template: XOTemplate,\n): XOInvitation => {\n const transactionIdentifier = getTemplateActionTransactionIdentifierOrThrow(template, incomingInvitation.actionIdentifier);\n const incomingTransactionHash = getInvitationTransactionHash(incomingInvitation, transactionIdentifier);\n\n if (incomingTransactionHash === undefined) {\n return incomingInvitation;\n }\n\n // Share payloads skip invitation validation on this path, so construct TransactionHash before persist.\n new TransactionHash(incomingTransactionHash);\n\n const storedTransactionResult = storedInvitation.result?.transactions?.[transactionIdentifier];\n\n if (storedTransactionResult === undefined) {\n // A hash cannot stand in for a created result. Entity and signature placeholders are never written.\n const invitationWithStoredResult: XOInvitation = { ...incomingInvitation };\n\n // The incoming result only carries the hash, so the stored result replaces it.\n delete invitationWithStoredResult.result;\n\n // The stored result is only set when present, because the invitation type rejects an optional field that holds undefined.\n if (storedInvitation.result !== undefined) {\n invitationWithStoredResult.result = storedInvitation.result;\n }\n\n return invitationWithStoredResult;\n }\n\n // Keep stored created metadata and replace only the hash from the incoming share.\n const mergedTransactionResult: XOInvitationTransactionResult = {\n ...storedTransactionResult,\n transactionHash: incomingTransactionHash,\n };\n\n const invitationWithStoredResult = {\n ...incomingInvitation,\n result: storedInvitation.result,\n };\n\n return applyInvitationTransactionResultToInvitation(invitationWithStoredResult, transactionIdentifier, mergedTransactionResult);\n};\n","import type { XOInvitation, XOTemplate, XOInvitationTransactionBroadcastDetails, XOInvitationTransactionResult } from '@xo-cash/types';\nimport {\n buildInvitationCommitSigningPayload,\n verifyInvitationCommitSignature,\n verifyInvitationDataResultSignature,\n verifyInvitationTransactionBroadcastedResultSignature,\n verifyInvitationTransactionCreatedResultSignature,\n} from '@xo-cash/crypto';\nimport {\n CommitIdentifier,\n ExtendedPublicKey,\n InvitationIdentifier,\n SchnorrSignature,\n TemplateIdentifier,\n Timestamp,\n TransactionHash,\n} from '@xo-cash/primitives';\nimport { generateTemplateIdentifier, normalizeError } from '@xo-cash/utils';\nimport {\n CommitSignatureInvalidError,\n DataResultSignatureInvalidError,\n InvitationFieldInvalidError,\n InvitationTemplateMismatchError,\n InvitationValidationFailedError,\n TransactionBroadcastMetadataIncompleteError,\n TransactionBroadcastSignatureInvalidError,\n TransactionCreatedSignatureInvalidError,\n} from '../../errors/index.ts';\nimport type { XONetwork } from '../../defaults.ts';\nimport { resolveHdKeyNetwork } from '../../network/helper.ts';\nimport { getTemplateActionOrThrow } from '../../template.ts';\n\n/**\n * A transaction result that includes broadcast metadata.\n */\ntype XOInvitationTransactionResultBroadcasted = XOInvitationTransactionResult & XOInvitationTransactionBroadcastDetails;\n\ntype BroadcastedTransactionResult = XOInvitationTransactionResultBroadcasted;\n\n/**\n * Collects errors for invitation and commit fields that fail primitive construction.\n *\n * @param {XOInvitation} invitation - The invitation whose identifiers, timestamps, and signatures are checked.\n * @returns {Error[]} - One {@link InvitationFieldInvalidError} for every field that is not a valid primitive.\n */\nconst listInvitationPrimitiveIssues = (invitation: XOInvitation): Error[] => {\n const issues: Error[] = [];\n\n try {\n new InvitationIdentifier(invitation.invitationIdentifier);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'invitationIdentifier' ], normalizeError(error)));\n }\n\n try {\n new TemplateIdentifier(invitation.templateIdentifier);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'templateIdentifier' ], normalizeError(error)));\n }\n\n try {\n new Timestamp(invitation.createdAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'createdAtTimestamp' ], normalizeError(error)));\n }\n\n // Use the commit index in each path so the error points at the commit that holds the field.\n for (const [ commitIndex, commit ] of invitation.commits.entries()) {\n try {\n new CommitIdentifier(commit.commitIdentifier);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'commitIdentifier' ], normalizeError(error)));\n }\n\n const previousCommitIdentifier = commit.previousCommitIdentifier;\n\n if (previousCommitIdentifier !== undefined) {\n try {\n new CommitIdentifier(previousCommitIdentifier);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'previousCommitIdentifier' ], normalizeError(error)));\n }\n }\n\n try {\n new SchnorrSignature(commit.signature);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'signature' ], normalizeError(error)));\n }\n\n try {\n new Timestamp(commit.createdAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'createdAtTimestamp' ], normalizeError(error)));\n }\n\n try {\n new Timestamp(commit.expiresAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'expiresAtTimestamp' ], normalizeError(error)));\n }\n }\n\n return issues;\n};\n\n/**\n * Collects errors for invitation result fields that fail primitive construction.\n *\n * @param {XOInvitation} invitation - The invitation whose transaction results are checked.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @returns {Error[]} - One {@link InvitationFieldInvalidError} for every result field that is not a valid primitive.\n */\nconst listInvitationResultPrimitiveIssues = (invitation: XOInvitation, network: XONetwork): Error[] => {\n const issues: Error[] = [];\n\n if (invitation.result === undefined) {\n return issues;\n }\n\n // Map the engine network once so every result entity identifier uses xpub or tpub for that network.\n const hdKeyNetwork = resolveHdKeyNetwork(network);\n\n const { result } = invitation;\n\n for (const [ transactionIdentifier, transactionResult ] of Object.entries(result.transactions ?? {})) {\n // Every path in this loop starts at the transaction result, keyed by its template transaction identifier.\n const transactionPath = [ 'result', 'transactions', transactionIdentifier ];\n\n try {\n new TransactionHash(transactionResult.transactionHash);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'transactionHash' ], normalizeError(error)));\n }\n\n try {\n new Timestamp(transactionResult.createdAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'createdAtTimestamp' ], normalizeError(error)));\n }\n\n try {\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(transactionResult.createdByEntityIdentifier, hdKeyNetwork);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'createdByEntityIdentifier' ], normalizeError(error)));\n }\n\n try {\n new SchnorrSignature(transactionResult.createdBySignature);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'createdBySignature' ], normalizeError(error)));\n }\n\n if ('broadcastedAtTimestamp' in transactionResult) {\n try {\n new Timestamp(transactionResult.broadcastedAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'broadcastedAtTimestamp' ], normalizeError(error)));\n }\n }\n\n if ('broadcastedByEntityIdentifier' in transactionResult) {\n try {\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(transactionResult.broadcastedByEntityIdentifier, hdKeyNetwork);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'broadcastedByEntityIdentifier' ], normalizeError(error)));\n }\n }\n\n if ('broadcastedBySignature' in transactionResult) {\n try {\n new SchnorrSignature(transactionResult.broadcastedBySignature);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...transactionPath, 'broadcastedBySignature' ], normalizeError(error)));\n }\n }\n }\n\n for (const [ dataIdentifier, dataResult ] of Object.entries(result.data ?? {})) {\n // Every path in this loop starts at the data result, keyed by its template data identifier.\n const dataPath = [ 'result', 'data', dataIdentifier ];\n\n try {\n new Timestamp(dataResult.createdAtTimestamp);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...dataPath, 'createdAtTimestamp' ], normalizeError(error)));\n }\n\n try {\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(dataResult.createdByEntityIdentifier, hdKeyNetwork);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...dataPath, 'createdByEntityIdentifier' ], normalizeError(error)));\n }\n\n try {\n new SchnorrSignature(dataResult.createdBySignature);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ ...dataPath, 'createdBySignature' ], normalizeError(error)));\n }\n }\n\n return issues;\n};\n\n/**\n * Collects errors for entity identifiers that are not valid extended public keys (xpub or tpub).\n *\n * @param {XOInvitation} invitation - The invitation whose commit entity identifiers are checked.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @returns {Error[]} - One {@link InvitationFieldInvalidError} for every invalid entity identifier.\n */\nconst listInvitationEntityIssues = (invitation: XOInvitation, network: XONetwork): Error[] => {\n const issues: Error[] = [];\n const checkedEntityIdentifiers = new Set<string>();\n\n // Map the engine network once so every commit entity identifier uses xpub or tpub for that network.\n const hdKeyNetwork = resolveHdKeyNetwork(network);\n\n for (const [ commitIndex, commit ] of invitation.commits.entries()) {\n // Check each entity identifier once and report it at the first commit that carries it.\n if (checkedEntityIdentifiers.has(commit.entityIdentifier) === true) {\n continue;\n }\n\n checkedEntityIdentifiers.add(commit.entityIdentifier);\n\n try {\n // Reject an entity identifier that is not an extended public key for this network.\n new ExtendedPublicKey(commit.entityIdentifier, hdKeyNetwork);\n } catch (error: unknown) {\n issues.push(new InvitationFieldInvalidError([ 'commits', commitIndex, 'entityIdentifier' ], normalizeError(error)));\n }\n }\n\n return issues;\n};\n\n/**\n * Collects errors for commits whose Schnorr signatures do not verify.\n *\n * @param {XOInvitation} invitation - The invitation whose commit signatures are checked.\n * @returns {Error[]} - One {@link CommitSignatureInvalidError} for every commit with an invalid signature.\n */\nconst listCommitSignatureIssues = (invitation: XOInvitation): Error[] => {\n const issues: Error[] = [];\n const { templateIdentifier, actionIdentifier, invitationIdentifier, commits } = invitation;\n\n for (const commit of commits) {\n const commitSigningPayload = buildInvitationCommitSigningPayload({\n data: commit.data,\n templateIdentifier,\n actionIdentifier,\n invitationIdentifier,\n commitIdentifier: commit.commitIdentifier,\n previousCommitIdentifier: commit.previousCommitIdentifier,\n });\n\n try {\n const isCommitSignatureValid = verifyInvitationCommitSignature({\n signature: commit.signature,\n entityIdentifier: commit.entityIdentifier,\n commitIdentifier: commit.commitIdentifier,\n message: commitSigningPayload,\n });\n\n if (isCommitSignatureValid === false) {\n issues.push(new CommitSignatureInvalidError(commit.commitIdentifier));\n }\n } catch (error: unknown) {\n // Keep the verification failure as the cause so the reason it threw is not lost.\n issues.push(new CommitSignatureInvalidError(commit.commitIdentifier, normalizeError(error)));\n }\n }\n\n return issues;\n};\n\n/**\n * Returns true when every broadcast field on a transaction result is populated.\n *\n * @param {XOInvitationTransactionResult} transactionResult - Transaction result from invitation.result.\n * @returns {transactionResult is BroadcastedTransactionResult} - True when broadcast metadata is complete. Narrows to the broadcasted result type.\n */\nconst isTransactionFullyBroadcasted = (transactionResult: XOInvitationTransactionResult): transactionResult is BroadcastedTransactionResult => {\n return (\n 'broadcastedAtTimestamp' in transactionResult\n && 'broadcastedByEntityIdentifier' in transactionResult\n && 'broadcastedBySignature' in transactionResult\n );\n};\n\n/**\n * Collects errors when a transaction result has partial broadcast metadata.\n *\n * Broadcast fields must be absent together or present together on the object. Mixed key presence is invalid.\n *\n * @param {string} transactionIdentifier - Template transaction identifier for the result.\n * @param {XOInvitationTransactionResult} transactionResult - Transaction result from invitation.result.\n * @returns {Error[]} - A {@link TransactionBroadcastMetadataIncompleteError} when broadcast metadata is incomplete.\n */\nconst listIncompleteTransactionBroadcastMetadataIssues = (\n transactionIdentifier: string,\n transactionResult: XOInvitationTransactionResult,\n): Error[] => {\n const hasBroadcastedAtTimestamp = 'broadcastedAtTimestamp' in transactionResult;\n const hasBroadcastedByEntityIdentifier = 'broadcastedByEntityIdentifier' in transactionResult;\n const hasBroadcastedBySignature = 'broadcastedBySignature' in transactionResult;\n\n const broadcastFieldPresenceFlags = [ hasBroadcastedAtTimestamp, hasBroadcastedByEntityIdentifier, hasBroadcastedBySignature ];\n const presentBroadcastFieldCount = broadcastFieldPresenceFlags.filter((isPresent) => isPresent === true).length;\n\n if (presentBroadcastFieldCount === 0 || presentBroadcastFieldCount === 3) {\n return [];\n }\n\n return [ new TransactionBroadcastMetadataIncompleteError(transactionIdentifier) ];\n};\n\n/**\n * Collects errors for invitation result signatures when result is present on the invitation.\n *\n * @param {XOInvitation} invitation - The invitation whose result signatures are checked.\n * @returns {Error[]} - One error for every invalid transaction or data result signature, and for incomplete broadcast metadata.\n */\nconst listResultSignatureIssues = (invitation: XOInvitation): Error[] => {\n const issues: Error[] = [];\n\n if (invitation.result === undefined) {\n return issues;\n }\n\n const { invitationIdentifier, result } = invitation;\n\n for (const [ transactionIdentifier, transactionResult ] of Object.entries(result.transactions ?? {})) {\n try {\n const isCreatedSignatureValid = verifyInvitationTransactionCreatedResultSignature({\n invitationIdentifier,\n transactionResult,\n });\n\n if (isCreatedSignatureValid === false) {\n issues.push(new TransactionCreatedSignatureInvalidError(transactionIdentifier));\n }\n } catch (error: unknown) {\n // Keep the verification failure as the cause so the reason it threw is not lost.\n issues.push(new TransactionCreatedSignatureInvalidError(transactionIdentifier, normalizeError(error)));\n }\n\n issues.push(...listIncompleteTransactionBroadcastMetadataIssues(transactionIdentifier, transactionResult));\n\n if (isTransactionFullyBroadcasted(transactionResult) === true) {\n try {\n const isBroadcastSignatureValid = verifyInvitationTransactionBroadcastedResultSignature({\n invitationIdentifier,\n transactionResult,\n });\n\n if (isBroadcastSignatureValid === false) {\n issues.push(new TransactionBroadcastSignatureInvalidError(transactionIdentifier));\n }\n } catch (error: unknown) {\n // Keep the verification failure as the cause so the reason it threw is not lost.\n issues.push(new TransactionBroadcastSignatureInvalidError(transactionIdentifier, normalizeError(error)));\n }\n }\n }\n\n for (const [ dataIdentifier, dataResult ] of Object.entries(result.data ?? {})) {\n try {\n const isDataSignatureValid = verifyInvitationDataResultSignature({\n invitationIdentifier,\n dataResult,\n });\n\n if (isDataSignatureValid === false) {\n issues.push(new DataResultSignatureInvalidError(dataIdentifier));\n }\n } catch (error: unknown) {\n // Keep the verification failure as the cause so the reason it threw is not lost.\n issues.push(new DataResultSignatureInvalidError(dataIdentifier, normalizeError(error)));\n }\n }\n\n return issues;\n};\n\n/**\n * Runs every invitation content validation and returns all discovered errors.\n *\n * @param {XOInvitation} invitation - The built invitation object to validate.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @returns {Error[]} - Every validation error found. An empty array means the invitation content is valid.\n */\nexport const listInvitationContentValidationIssues = (invitation: XOInvitation, network: XONetwork): Error[] => {\n const issues: Error[] = [];\n\n issues.push(...listInvitationPrimitiveIssues(invitation));\n issues.push(...listInvitationResultPrimitiveIssues(invitation, network));\n issues.push(...listInvitationEntityIssues(invitation, network));\n issues.push(...listCommitSignatureIssues(invitation));\n issues.push(...listResultSignatureIssues(invitation));\n\n return issues;\n};\n\n/**\n * Resolves the template action and collects every validation error for an invitation.\n *\n * @param {XOInvitation} invitation - The invitation to validate.\n * @param {XOTemplate} template - The template to validate against.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @returns {Error[]} - Every validation error found. An empty array means the invitation content is valid.\n */\nexport const listInvitationValidationIssues = (invitation: XOInvitation, template: XOTemplate, network: XONetwork): Error[] => {\n const issues: Error[] = [];\n const generatedTemplateIdentifier = generateTemplateIdentifier(template);\n\n try {\n const invitationTemplateIdentifier = new TemplateIdentifier(invitation.templateIdentifier);\n const expectedTemplateIdentifier = new TemplateIdentifier(generatedTemplateIdentifier);\n\n if (invitationTemplateIdentifier.equals(expectedTemplateIdentifier) === false) {\n issues.push(new InvitationTemplateMismatchError(invitation.templateIdentifier, generatedTemplateIdentifier));\n }\n } catch {\n // An invalid invitation.templateIdentifier is already reported by listInvitationPrimitiveIssues.\n // Skip the mismatch comparison here rather than duplicating that issue.\n }\n\n try {\n // Report an action the template does not declare. The content checks below do not depend on the action, so they still run.\n getTemplateActionOrThrow(template, invitation.actionIdentifier);\n } catch (error: unknown) {\n issues.push(normalizeError(error));\n }\n\n return [ ...issues, ...listInvitationContentValidationIssues(invitation, network) ];\n};\n\n/**\n * Validates an invitation against a template and throws when any check fails.\n *\n * @param {XOInvitation} invitation - The invitation to validate.\n * @param {XOTemplate} template - The template to validate against.\n * @param {XONetwork} network - Engine network that selects xpub or tpub for entity identifiers.\n * @throws {@link InvitationValidationFailedError} - If one or more validation checks fail.\n */\nexport const validateInvitation = (invitation: XOInvitation, template: XOTemplate, network: XONetwork): void => {\n const validationIssues = listInvitationValidationIssues(invitation, template, network);\n\n if (validationIssues.length > 0) {\n throw new InvitationValidationFailedError(invitation.invitationIdentifier, validationIssues);\n }\n};\n","import { monitorScriptHash } from '@electrum-cash/application';\nimport type { XOInvitation } from '@xo-cash/types';\nimport type { StoredInvitation } from '@xo-cash/state';\nimport { parseInvitation } from '@xo-cash/utils';\nimport { InvitationHistoryConflictError } from '../../errors/index.ts';\nimport { fetchScriptHashUnspentOutputs } from '../../network/electrum.ts';\nimport { updateUnspentOutputsForScriptHash } from '../../state/unspent-outputs.ts';\nimport { compareInvitationCommitHistories } from '../helpers/commits.ts';\nimport { listRelevantInvitationOutputsMissingFromStore } from '../helpers/outputs.ts';\nimport { isInvitationTransactionHashOnlyUpdate, mergeInvitationTransactionHashOnlyUpdate } from '../helpers/transaction-result.ts';\nimport type { AccountContext } from '../interfaces.ts';\nimport { assertCommitsDoNotChangeCommittedFields } from '../validation/committed-fields.ts';\nimport { assertEntityFollowUpRoles } from '../validation/follow-up-roles.ts';\nimport { validateInvitation } from '../validation/invitation.ts';\nimport { assertRoleVariablesProvidedByRoleEntities } from '../validation/role-variables.ts';\n\n/**\n * Updates the stored invitation with a newer version received from an external participant or through some subscription.\n * The updated invitation should have the shared history with the stored invitation.\n *\n * An output another participant added that locks to one of this account's scripts is stored and tracked like a script\n * this account built, so its funds are seen and it can be unlocked later.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} receivedInvitation - Shared invitation to store. The local entity identifier and archive fields keep their stored values.\n * @returns {Promise<StoredInvitation>} - The updated invitation as stored, including the local entity identifier when present.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not already in the store.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link InvitationInvalidError} - If the updated invitation does not match the XOInvitation type.\n * @throws {@link InvitationValidationFailedError} - If the updated invitation fails validation.\n * @throws {@link InvitationHistoryConflictError} - If a stored commit is missing, reordered, or differs at its expected position.\n * @throws {@link InvitationItemFieldConflictError} - If a commit changes a value an earlier commit set.\n * @throws {@link RoleVariableEntityMismatchError} - If a commit provides a variable of a role its entity does not hold.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If a commit gives an entity more than one role with a follow up.\n */\nexport const updateInvitation = async (context: Required<AccountContext>, receivedInvitation: XOInvitation): Promise<StoredInvitation> => {\n // The invitation is received from another participant, so every field is checked against its type before it is used.\n const updatedInvitation = parseInvitation(receivedInvitation);\n\n const storedInvitation = await context.state.getInvitationOrThrow(updatedInvitation.invitationIdentifier);\n const storedTemplate = await context.state.getTemplateOrThrow(updatedInvitation.templateIdentifier);\n const template = storedTemplate.template;\n const invitationCommitHistoryComparison = compareInvitationCommitHistories(storedInvitation.invitation, updatedInvitation);\n\n if (invitationCommitHistoryComparison.historyConflictCommitIdentifier !== null) {\n throw new InvitationHistoryConflictError(\n updatedInvitation.invitationIdentifier,\n invitationCommitHistoryComparison.historyConflictCommitIdentifier,\n );\n }\n\n const isTransactionHashOnlyUpdate = isInvitationTransactionHashOnlyUpdate(\n storedInvitation.invitation,\n updatedInvitation,\n template,\n invitationCommitHistoryComparison,\n );\n\n if (isTransactionHashOnlyUpdate === false) {\n validateInvitation(updatedInvitation, template, context.network);\n\n // A received commit that changes a value an earlier commit set is refused so the stored copy never holds it.\n assertCommitsDoNotChangeCommittedFields(updatedInvitation);\n\n // So is a variable provided for a role by an entity that does not hold it.\n assertRoleVariablesProvidedByRoleEntities(updatedInvitation, template);\n\n // So is a commit that gives an entity a second role with a follow up.\n assertEntityFollowUpRoles(updatedInvitation, template);\n }\n\n let invitationToStore = updatedInvitation;\n\n // A hash only update keeps the stored created result and replaces only its transaction hash.\n if (isTransactionHashOnlyUpdate === true) {\n invitationToStore = mergeInvitationTransactionHashOnlyUpdate(storedInvitation.invitation, updatedInvitation, template);\n }\n\n // Storage replaces only the shared invitation and keeps this account's participation identity and archive state.\n await context.state.updateInvitation(updatedInvitation.invitationIdentifier, invitationToStore);\n\n // Read the invitation back so the returned value carries the fields storage sets, such as the time of this update.\n const updatedStoredInvitation = await context.state.getInvitationOrThrow(updatedInvitation.invitationIdentifier);\n\n // Another participant may have added an output locked to this account.\n const relevantMissingOutputScripts = await listRelevantInvitationOutputsMissingFromStore(context, updatedStoredInvitation);\n\n for (const outputScript of relevantMissingOutputScripts) {\n // The account tracks the output like a script it built, so its funds are seen and it can be unlocked later.\n await monitorScriptHash(outputScript.scriptHash);\n await context.state.storeScriptHashData(outputScript);\n\n // Fetch the unspent outputs already paid to the script.\n const unspentOutputsFromBlockchain = await fetchScriptHashUnspentOutputs(outputScript.scriptHash);\n\n await updateUnspentOutputsForScriptHash(context.state, outputScript.scriptHash, unspentOutputsFromBlockchain);\n }\n\n return updatedStoredInvitation;\n};\n","import { TransactionHash } from '@xo-cash/primitives';\nimport type { XOInvitation, XOInvitationCommit, XOTemplate } from '@xo-cash/types';\nimport type { InvitationInputMissingSignature } from '../interfaces.ts';\nimport { isUnlockingBytecodeMissingOrPlaceholder, mergeInvitationCommits } from '../merge/merge-commits.ts';\n\n/**\n * Lists inputs that have a real UTXO outpoint committed to the invitation but no unlocking bytecode yet.\n * These inputs have been reserved by their committing entity but have not been signed.\n *\n * Detection uses the merged invitation state. An input is considered unsigned when its\n * unlocking bytecode in the merged result is absent or is the placeholder (an empty Uint8Array).\n * Attribution is taken directly from the sourceCommitIdentifier on each merged input.\n *\n * @param {XOInvitation} invitation - The invitation to examine.\n * @param {XOTemplate} template - The template for this invitation, required by the merger.\n * @returns {InvitationInputMissingSignature[]} - Descriptors for each unsigned input, including which entity committed it.\n */\nexport const listInputsMissingSignatures = (invitation: XOInvitation, template: XOTemplate): InvitationInputMissingSignature[] => {\n const mergedInvitation = mergeInvitationCommits(invitation, template);\n\n const commitsMap = new Map<string, XOInvitationCommit>();\n for (const commit of invitation.commits) {\n commitsMap.set(commit.commitIdentifier, commit);\n }\n\n const incompleteInputs: InvitationInputMissingSignature[] = [];\n\n for (const mergedInput of mergedInvitation.inputs) {\n const outpointTransactionHash = mergedInput.outpointTransactionHash;\n\n // Merger normalizes present outpoints to bytes. Skip template slots that have no outpoint yet.\n if (outpointTransactionHash === undefined || mergedInput.outpointIndex === undefined) {\n continue;\n }\n\n const isUnsigned = isUnlockingBytecodeMissingOrPlaceholder(mergedInput.unlockingBytecode);\n\n if (isUnsigned === false) {\n continue;\n }\n\n const sourceCommit = commitsMap.get(mergedInput.sourceCommitIdentifier);\n\n // Use the source commit entity when present. Do not invent an empty identifier.\n incompleteInputs.push({\n inputIdentifier: mergedInput.inputIdentifier,\n sourceCommitIdentifier: mergedInput.sourceCommitIdentifier,\n entityIdentifier: sourceCommit?.entityIdentifier,\n roleIdentifier: mergedInput.roleIdentifier,\n outpointTransactionHash: new TransactionHash(outpointTransactionHash).toHex(),\n outpointIndex: Number(mergedInput.outpointIndex),\n });\n }\n\n return incompleteInputs;\n};\n","import type {\n XOInvitation,\n XOTemplate,\n XOTemplateAction,\n XOTemplateRoleIdentifier,\n XOTemplateVariableIdentifier,\n XOTemplateInputIdentifier,\n XOTemplateOutputIdentifier,\n} from '@xo-cash/types';\nimport { INVITATION_REQUIREMENT_FIELD_NAME_LIST, INVITATION_REQUIREMENT_FIELD_NAMES, type InvitationRequirementFieldName } from '../../defaults.ts';\nimport { getTemplateTransactionOrThrow } from '../../template.ts';\nimport type { InvitationRequirementIdentifierLists, InvitationRoleRequirementIdentifierLists } from '../interfaces.ts';\n\ntype RoleRequirementIdentifierMap = Record<XOTemplateRoleIdentifier, InvitationRoleRequirementIdentifierLists>;\n\ntype InvitationRequirementIdentifier = XOTemplateVariableIdentifier | XOTemplateInputIdentifier | XOTemplateOutputIdentifier;\n\n/**\n * Filters role requirements to only include those with actual populated requirements.\n * Removes any roles that have no variables, inputs, or outputs defined.\n * @param {RoleRequirementIdentifierMap} roleRequirements - Record mapping role identifiers to their requirement objects.\n * @returns {RoleRequirementIdentifierMap} - Filtered record containing only roles that have at least one requirement field populated.\n */\nconst filterRolesWithRequirements = (roleRequirements: RoleRequirementIdentifierMap): RoleRequirementIdentifierMap => {\n const filteredRoleRequirements: RoleRequirementIdentifierMap = {};\n for (const [ roleIdentifier, roleRequirement ] of Object.entries(roleRequirements)) {\n const roleHasRequirements = INVITATION_REQUIREMENT_FIELD_NAME_LIST.some((requirementFieldName) => {\n const requirementIdentifiers = roleRequirement[requirementFieldName];\n\n return requirementIdentifiers && requirementIdentifiers.length > 0;\n });\n\n if (roleHasRequirements) {\n filteredRoleRequirements[roleIdentifier] = roleRequirement;\n }\n }\n\n return filteredRoleRequirements;\n};\n\n/**\n * Unions requirement identifiers from the top level and every role for one field kind.\n *\n * Template actions may list a requirement at the top level while commits store it under a role\n * bucket. Missing requirement checks and unexpected requirement checks both need the same union\n * so populated ids are recognized when they appear anywhere in the structure.\n *\n * @param {InvitationRequirementIdentifierLists} requirements - Requirement lists from the template or from populated commits.\n * @param {InvitationRequirementFieldName} requirementFieldName - Which requirement list to union (variables, inputs, or outputs).\n * @returns {InvitationRequirementIdentifier[]} - De duplicated identifiers from the top level list and every role list.\n */\nexport const listRequirementIdentifiersAcrossRoles = (\n requirements: InvitationRequirementIdentifierLists,\n requirementFieldName: InvitationRequirementFieldName,\n): InvitationRequirementIdentifier[] => {\n const requirementIdentifierSet = new Set<InvitationRequirementIdentifier>();\n\n for (const identifier of requirements[requirementFieldName] ?? []) {\n requirementIdentifierSet.add(identifier);\n }\n\n for (const roleRequirement of Object.values(requirements.roles ?? {})) {\n for (const identifier of roleRequirement[requirementFieldName] ?? []) {\n requirementIdentifierSet.add(identifier);\n }\n }\n\n return [ ...requirementIdentifierSet ];\n};\n\n/**\n * Processes and identifies missing requirements by comparing template requirements with populated requirements.\n * Analyzes both top-level requirements and role-specific requirements to determine what is still needed.\n * @param {InvitationRequirementIdentifierLists} requirementsFromTemplate - Requirements expected from the template definition.\n * @param {InvitationRequirementIdentifierLists} populatedRequirements - Requirements that have already been populated in the invitation.\n * @returns {{\n * missingRequirements: InvitationRequirementIdentifierLists,\n * missingRoleRequirements: Record<string, InvitationRoleRequirementIdentifierLists>,\n * }} - Missing top-level requirements and role-specific missing requirements keyed by role identifier.\n */\nconst processMissingRequirements = (\n requirementsFromTemplate: InvitationRequirementIdentifierLists,\n populatedRequirements: InvitationRequirementIdentifierLists,\n): {\n missingRequirements: InvitationRequirementIdentifierLists;\n missingRoleRequirements: Record<string, InvitationRoleRequirementIdentifierLists>;\n} => {\n // Initialize the missing requirements and roles objects.\n const missingRequirements: InvitationRequirementIdentifierLists = {};\n\n // Initialize the missing roles object.\n const missingRoleRequirements: Record<string, InvitationRoleRequirementIdentifierLists> = {};\n\n // Process top-level requirements\n INVITATION_REQUIREMENT_FIELD_NAME_LIST.forEach((requirementFieldName) => {\n const populatedIdentifiersAcrossRoles = listRequirementIdentifiersAcrossRoles(populatedRequirements, requirementFieldName);\n\n // Get the missing identifiers for the requirement field.\n const requirementIdentifiers = requirementsFromTemplate[requirementFieldName] ?? [];\n const missingIdentifiers = requirementIdentifiers.filter((identifier) => {\n return populatedIdentifiersAcrossRoles.includes(identifier) === false;\n });\n\n // If there are missing identifiers, add them to the missing requirements object.\n if (missingIdentifiers.length > 0) {\n missingRequirements[requirementFieldName] = missingIdentifiers;\n }\n });\n\n // Process role-level requirements\n for (const [ roleIdentifier, roleRequirement ] of Object.entries(requirementsFromTemplate.roles ?? {})) {\n INVITATION_REQUIREMENT_FIELD_NAME_LIST.forEach((requirementFieldName) => {\n const populatedIdentifiersAcrossRoles = listRequirementIdentifiersAcrossRoles(populatedRequirements, requirementFieldName);\n\n // Get the missing identifiers for the requirement field.\n const requirementIdentifiers = roleRequirement[requirementFieldName] ?? [];\n const missingIdentifiers = requirementIdentifiers.filter((identifier) => {\n return populatedIdentifiersAcrossRoles.includes(identifier) === false;\n });\n\n // If there are missing identifiers, add them to the missing roles object.\n if (missingIdentifiers.length > 0) {\n if (missingRoleRequirements[roleIdentifier] === undefined) missingRoleRequirements[roleIdentifier] = {};\n\n // Add the missing identifiers to the missing roles object.\n missingRoleRequirements[roleIdentifier][requirementFieldName] = missingIdentifiers;\n }\n });\n }\n\n return { missingRequirements, missingRoleRequirements };\n};\n\n/**\n * Extracts and lists all requirements from the template and action for an invitation.\n * Analyzes the template action to determine what variables, inputs, outputs, and role-specific\n * requirements are needed to fulfill the action.\n *\n * @param {XOTemplate} template - The template.\n * @param {XOTemplateAction} action - The action that has requirements.\n * @returns {InvitationRequirementIdentifierLists} - An object containing all the requirements.\n * @todo Support minimum and maximum role slots.\n */\nexport const listRequirementsFromTemplate = (template: XOTemplate, action: XOTemplateAction): InvitationRequirementIdentifierLists => {\n // Initialize the general requirements object.\n const generalRequirements: InvitationRequirementIdentifierLists = {};\n\n // Initialize the specific role requirements object.\n const roleRequirements: Record<string, InvitationRoleRequirementIdentifierLists> = {};\n\n // Variables the action requires without naming a role may be provided by any participant.\n if (action.requirements?.variables !== undefined && action.requirements.variables.length > 0) {\n generalRequirements.variables = [ ...action.requirements.variables ];\n }\n\n // This is expected to have requirements only specific to the roles.\n if (action.roles !== undefined) {\n for (const [ roleIdentifier, roleDefinition ] of Object.entries(action.roles)) {\n if (roleDefinition.requirements !== undefined) {\n if (roleRequirements[roleIdentifier] === undefined) {\n roleRequirements[roleIdentifier] = {};\n }\n\n if (roleDefinition.requirements.variables !== undefined) {\n roleRequirements[roleIdentifier].variables = roleDefinition.requirements.variables;\n }\n }\n }\n }\n\n // Cover role specific requirements in the action.\n if (action.requirements?.participants !== undefined) {\n for (const roleSlot of action.requirements.participants) {\n const roleIdentifier = roleSlot.role;\n\n // If the role requirements object does not have an entry for the role identifier, create one.\n if (roleRequirements[roleIdentifier] === undefined) {\n roleRequirements[roleIdentifier] = {};\n }\n\n // Variables for a role in an action are declared on the action's roles definition.\n const roleVariables = action.roles?.[roleIdentifier]?.requirements?.variables;\n if (roleVariables !== undefined) {\n roleRequirements[roleIdentifier].variables = roleVariables;\n }\n }\n }\n\n // Covering the transaction requirements for inputs, outputs and other expected information.\n if (action.transaction !== undefined) {\n // Get the transaction definition from the template.\n const transactionDefinition = getTemplateTransactionOrThrow(template, action.transaction);\n\n // Process the transaction roles.\n if (transactionDefinition.roles !== undefined) {\n // Process each transaction role.\n for (const [ roleIdentifier, transactionRoleRequirement ] of Object.entries(transactionDefinition.roles)) {\n // If the role requirements object does not have an entry for the role identifier, create one.\n if (roleRequirements[roleIdentifier] === undefined) {\n roleRequirements[roleIdentifier] = {};\n }\n\n // Add the inputs to the role requirements object, extracting just the identifier string from each entry.\n if (transactionRoleRequirement.inputs !== undefined) {\n const transactionInputRequirementIdentifiers = [];\n for (const transactionInputRequirement of transactionRoleRequirement.inputs) {\n transactionInputRequirementIdentifiers.push(transactionInputRequirement.input);\n }\n\n roleRequirements[roleIdentifier].inputs = transactionInputRequirementIdentifiers;\n }\n\n // Add the outputs to the role requirements object, extracting just the identifier string from each entry.\n if (transactionRoleRequirement.outputs !== undefined) {\n const transactionOutputRequirementIdentifiers = [];\n for (const transactionOutputRequirement of transactionRoleRequirement.outputs) {\n transactionOutputRequirementIdentifiers.push(transactionOutputRequirement.output);\n }\n\n roleRequirements[roleIdentifier].outputs = transactionOutputRequirementIdentifiers;\n }\n }\n }\n\n // Add the inputs to the general requirements object, extracting just the identifier string from each entry.\n if (transactionDefinition.inputs !== undefined && transactionDefinition.inputs.length > 0) {\n generalRequirements.inputs = transactionDefinition.inputs.map((transactionInput) => transactionInput.input);\n }\n\n // Add the outputs to the general requirements object, extracting just the identifier string from each entry.\n if (transactionDefinition.outputs !== undefined && transactionDefinition.outputs.length > 0) {\n generalRequirements.outputs = transactionDefinition.outputs.map((transactionOutput) => transactionOutput.output);\n }\n }\n\n // Filter out roles that have no actual requirements\n const roleRequirementsWithItems = filterRolesWithRequirements(roleRequirements);\n\n // Initialize the final requirements object.\n const finalRequirements: InvitationRequirementIdentifierLists = {};\n\n // Process each requirement type.\n for (const requirementFieldName of INVITATION_REQUIREMENT_FIELD_NAME_LIST) {\n // Get the requirement identifiers from the general requirements object.\n const requirementIdentifiers = generalRequirements[requirementFieldName];\n\n // If the requirement identifiers are not empty, add them to the final requirements object.\n if (requirementIdentifiers !== undefined && requirementIdentifiers.length > 0) {\n finalRequirements[requirementFieldName] = requirementIdentifiers;\n }\n }\n\n // If there are any roles with actual requirements, add them to the final requirements object.\n if (Object.keys(roleRequirementsWithItems).length > 0) {\n finalRequirements.roles = roleRequirementsWithItems;\n }\n\n // Return the final requirements object.\n return finalRequirements;\n};\n\n/**\n * Adds the identifiers of invitation variables, inputs, or outputs to the appropriate requirement collections.\n * Items are added to either top-level requirements or role-specific requirements based on\n * whether they have a role identifier.\n *\n * @param {Item[]} items - Invitation variables, inputs, or outputs to extract identifiers from.\n * @param {InvitationRequirementFieldName} requirementFieldName - Requirement list the identifiers are added to.\n * @param {(item: Item) => string | undefined} readItemIdentifier - Reads the variable, input, or output identifier of one item.\n * @param {InvitationRequirementIdentifierLists} generalRequirements - Requirements object to add top-level identifiers to.\n * @param {RoleRequirementIdentifierMap} roleRequirements - Role requirements map for role-specific identifiers.\n * @returns {{\n * generalRequirements: InvitationRequirementIdentifierLists,\n * roleRequirements: RoleRequirementIdentifierMap,\n * }} - Updated requirements objects.\n */\nconst addRequirementIdentifiers = <Item extends { roleIdentifier?: XOTemplateRoleIdentifier }>(\n items: Item[],\n requirementFieldName: InvitationRequirementFieldName,\n readItemIdentifier: (item: Item) => string | undefined,\n generalRequirements: InvitationRequirementIdentifierLists,\n roleRequirements: Record<string, InvitationRoleRequirementIdentifierLists>,\n): {\n generalRequirements: InvitationRequirementIdentifierLists;\n roleRequirements: Record<string, InvitationRoleRequirementIdentifierLists>;\n} => {\n const updatedGeneralRequirements = { ...generalRequirements };\n const updatedRoleRequirements = { ...roleRequirements };\n\n for (const item of items) {\n const itemIdentifier = readItemIdentifier(item);\n\n if (itemIdentifier === undefined) {\n continue;\n }\n\n // A role scoped item is listed under its role, otherwise under the top level requirements.\n let requirementLists: InvitationRoleRequirementIdentifierLists = updatedGeneralRequirements;\n\n if (item.roleIdentifier !== undefined) {\n if (updatedRoleRequirements[item.roleIdentifier] === undefined) {\n updatedRoleRequirements[item.roleIdentifier] = {};\n }\n\n requirementLists = updatedRoleRequirements[item.roleIdentifier];\n }\n\n let requirementIdentifiers = requirementLists[requirementFieldName];\n\n if (requirementIdentifiers === undefined) {\n requirementIdentifiers = [];\n requirementLists[requirementFieldName] = requirementIdentifiers;\n }\n\n requirementIdentifiers.push(itemIdentifier);\n }\n\n return {\n generalRequirements: updatedGeneralRequirements,\n roleRequirements: updatedRoleRequirements,\n };\n};\n\n/**\n * Lists all requirements that have been populated in the invitation by examining all commits.\n * Extracts variable, input, and output identifiers from all commits in the invitation and\n * organizes them into top-level and role-specific requirements.\n *\n * @param {XOInvitation} invitation - The invitation object to analyze for populated requirements.\n * @returns {InvitationRequirementIdentifierLists} - An object containing all populated requirements found in the invitation's commits,\n * including top-level requirements and role-specific requirements. Only includes roles\n * that have at least one requirement populated.\n */\nexport const listPopulatedRequirementsInInvitation = (invitation: XOInvitation): InvitationRequirementIdentifierLists => {\n let generalRequirements: InvitationRequirementIdentifierLists = {};\n let roleRequirements: Record<string, InvitationRoleRequirementIdentifierLists> = {};\n\n for (const commit of invitation.commits ?? []) {\n const { variables, inputs, outputs } = commit.data;\n\n if (variables) {\n const result = addRequirementIdentifiers(\n variables,\n INVITATION_REQUIREMENT_FIELD_NAMES.variables,\n (variable) => variable.variableIdentifier,\n generalRequirements,\n roleRequirements,\n );\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n\n if (inputs) {\n const result = addRequirementIdentifiers(\n inputs,\n INVITATION_REQUIREMENT_FIELD_NAMES.inputs,\n (input) => input.inputIdentifier,\n generalRequirements,\n roleRequirements,\n );\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n\n if (outputs) {\n const result = addRequirementIdentifiers(\n outputs,\n INVITATION_REQUIREMENT_FIELD_NAMES.outputs,\n (output) => output.outputIdentifier,\n generalRequirements,\n roleRequirements,\n );\n generalRequirements = result.generalRequirements;\n roleRequirements = result.roleRequirements;\n }\n }\n\n return {\n ...generalRequirements,\n ...(Object.keys(roleRequirements).length > 0 && { roles: roleRequirements }),\n };\n};\n\n/**\n * Lists all missing requirements for the invitation that have not yet been supplied.\n * Compares the requirements expected from the template with what has been populated in the invitation\n * to determine what is still needed.\n *\n * The missing requirements are the template requirements that the invitation has not populated.\n *\n * @param {XOInvitation} invitation - The invitation object to check for missing requirements.\n * @param {XOTemplate} template - The template defining what requirements are expected.\n * @param {XOTemplateAction} action - The template action being analyzed to determine required requirements.\n * @returns {InvitationRequirementIdentifierLists} - An object containing all missing requirements, including top-level missing requirements\n * and role-specific missing requirements. Only includes roles that have at least one missing requirement.\n */\nexport const listUnfilledRequirements = (\n invitation: XOInvitation,\n template: XOTemplate,\n action: XOTemplateAction,\n): InvitationRequirementIdentifierLists => {\n const requiredRequirementsFromTemplate: InvitationRequirementIdentifierLists = listRequirementsFromTemplate(template, action);\n const populatedRequirementsInInvitation: InvitationRequirementIdentifierLists = listPopulatedRequirementsInInvitation(invitation);\n\n const { missingRequirements, missingRoleRequirements } = processMissingRequirements(\n requiredRequirementsFromTemplate,\n populatedRequirementsInInvitation,\n );\n\n // Filter out roles that have no actual missing requirements (empty objects)\n const roleRequirementsWithMissingItems = filterRolesWithRequirements(missingRoleRequirements);\n\n const finalMissingRequirements: InvitationRequirementIdentifierLists = { ...missingRequirements };\n\n // Only include roles if there are any roles with missing requirements\n if (Object.keys(roleRequirementsWithMissingItems).length > 0) {\n finalMissingRequirements.roles = roleRequirementsWithMissingItems;\n }\n\n return finalMissingRequirements;\n};\n","import {\n binToHex,\n createVirtualMachineBch,\n hexToBin,\n type CompilationContextBch,\n type CompilationData,\n type CompilerConfiguration,\n type Input,\n type Output,\n} from '@bitauth/libauth';\nimport type { IncompleteScriptCompilation, KeyReference } from '@xo-cash/crypto';\nimport type {\n XOInvitation,\n XOInvitationIdentifier,\n XOInvitationResolutionIdentifier,\n XOInvitationVariable,\n XOTemplate,\n XOTemplateRoleIdentifier,\n} from '@xo-cash/types';\nimport {\n InputUnspentOutputUnavailableError,\n MergedInputNotFoundError,\n MergedInputOutpointMissingError,\n TemplateUnlockingScriptNotFoundError,\n UnlockingBytecodeGenerationFailedError,\n UnlockingBytecodeVerificationFailedError,\n UnlockingCompilationContextMissingError,\n UnlockingScriptResolutionsMissingError,\n} from '../errors/index.ts';\nimport { createLibauthCompilerForLockingScript } from './libauth-utils.ts';\nimport {\n listInvitationVariablesFromCommits,\n buildCompilerBytecodeDataFromCompilationVariables,\n omitPrivateKeyVariablesFromCompilationVariables,\n mergeTemplateConstantsWithInvitationVariables,\n} from './template-locking-bytecode.ts';\nimport type { AccountContext, InvitationResolutionRequirements } from '../invitation/interfaces.ts';\nimport { mergeInvitationCommits } from '../invitation/index.ts';\nimport { buildResolutionCompilationBytecode, groupResolutionRequirements, listInvitationCompilationKeys } from './compilation-keys.ts';\nimport { isOnlyMissingIdentifiers } from './generate-locking-bytecode.ts';\nimport { ScriptHashDataNotFoundError, SecretDataNotFoundError } from '@xo-cash/state';\n\n/**\n * Unlocking bytecode compiled for one reserved invitation input.\n */\nexport type GeneratedInputUnlockingBytecode = {\n\n /**\n * Parent transaction hash of the spent outpoint, lowercase hex.\n */\n outpointTransactionHash: string;\n\n /**\n * Output index of the spent outpoint.\n */\n outpointIndex: number;\n\n /**\n * Compiled unlocking bytecode for this input.\n */\n unlockingBytecode: Uint8Array;\n};\n\n/**\n * Everything one input's unlocking script is compiled from.\n */\ntype InputUnlockingCompilation = {\n\n /**\n * Parent transaction hash of the spent outpoint, lowercase hex.\n */\n outpointTransactionHash: string;\n\n /**\n * Output index of the spent outpoint.\n */\n outpointIndex: number;\n\n /**\n * Template that defines the spent output's locking script.\n */\n template: XOTemplate;\n\n /**\n * Role the spent output was locked for, when one is known.\n */\n roleIdentifier: XOTemplateRoleIdentifier | undefined;\n\n /**\n * Compiler configuration of the spent output's locking script.\n */\n compilerConfiguration: CompilerConfiguration<CompilationContextBch>;\n\n /**\n * Script identifier the locking script compiles as.\n */\n lockingScriptId: string;\n\n /**\n * Script identifier of the unlocking script.\n */\n unlockingScriptId: string;\n\n /**\n * Compilation data without keys. The bytecode leaves out operations on keys this account holds.\n */\n data: Omit<CompilationData<CompilationContextBch>, 'keys'>;\n\n /**\n * Identifiers of the key operations participants resolved on this input, such as their signatures.\n */\n inputResolutionIdentifiers: XOInvitationResolutionIdentifier[];\n\n /**\n * Key reference for each Key variable this account holds for the spent output.\n */\n keyReferences: Record<string, KeyReference>;\n\n /**\n * Every key operation participants resolved for the compile, including those on keys this account holds.\n */\n resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array>;\n\n /**\n * Whether the input carries signatures other participants resolved.\n */\n hasInputResolutions: boolean;\n};\n\n/**\n * Collects everything one merged input's unlocking script compiles from.\n *\n * The compiler signs against the merged transaction. Secrets come from the script hash derivative index.\n * Constants, invitation variables, and the spent output value and token are passed in the compilation data.\n * Key operations participants resolved, including those already on the input, are passed as bytecode for the keys\n * this account does not hold.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Shared invitation that owns the input.\n * @param {XOTemplate} template - Template of the invitation action.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<InputUnlockingCompilation>} - Compiler configuration, compilation data, and key references for that input.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for the invitation is not in the secret store.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n * @throws {@link MergedInputNotFoundError} - When the merged invitation has no input at the given index.\n * @todo Consider other templates used in the invitation when merging commits. This is a hard composition problem,\n * and it helps resolve issues that would otherwise occur later.\n * @todo Decide the order of precedence between stored variables and invitation variables, throw when they conflict,\n * and keep both from overriding template constants.\n */\nconst prepareInputUnlockingCompilation = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n inputIndex: number,\n): Promise<InputUnlockingCompilation> => {\n const mergedInvitation = mergeInvitationCommits(invitation, template);\n\n // Get the merged input at the given index.\n const mergedInput = mergedInvitation.inputs[inputIndex];\n\n if (mergedInput == null) {\n throw new MergedInputNotFoundError(invitation.invitationIdentifier, inputIndex);\n }\n\n const { outpointTransactionHash, outpointIndex } = mergedInput;\n\n if (outpointTransactionHash === undefined || outpointIndex === undefined) {\n throw new MergedInputOutpointMissingError(invitation.invitationIdentifier, inputIndex);\n }\n\n // Stored unspent outputs are keyed by the hex form of the outpoint hash.\n const outpointTransactionHashHex = binToHex(outpointTransactionHash);\n\n // Fetch the input to be signed from the state.\n const unspentOutput = await context.state.getUnspentOutputData(outpointTransactionHashHex, outpointIndex);\n\n // Only an output this account tracks can be unlocked with its keys. A tracked output no invitation reserved yet is reserved when it is signed.\n const isReservableHere = unspentOutput?.reservedBy === invitation.invitationIdentifier || unspentOutput?.reservedBy === undefined;\n const canBuildOutput = unspentOutput !== undefined && isReservableHere;\n\n if (canBuildOutput === false) {\n throw new InputUnspentOutputUnavailableError(\n invitation.invitationIdentifier,\n inputIndex,\n outpointTransactionHashHex,\n outpointIndex,\n unspentOutput?.reservedBy,\n );\n }\n\n // Fetch the script hash data from the state.\n const scriptHashData = await context.state.getScriptHashData(unspentOutput.scriptHash);\n\n // A reserved output is stored with the script hash that can unlock it.\n if (scriptHashData === undefined) {\n throw new ScriptHashDataNotFoundError(unspentOutput.scriptHash);\n }\n\n // The locking script may belong to a different template than the invitation action.\n const storedTemplate = await context.state.getTemplateOrThrow(scriptHashData.templateIdentifier);\n const templateDefinition = storedTemplate.template;\n\n // Create a list of relevant variables from the script hash data\n const storedVariables: XOInvitationVariable[] = [];\n\n // Script hash variables are stored as strings. The shared merge reads invitation variable entries.\n if (scriptHashData.variables !== undefined) {\n for (const [ variableIdentifier, value ] of Object.entries(scriptHashData.variables)) {\n storedVariables.push({\n variableIdentifier,\n value,\n });\n }\n }\n\n const storedSecrets = scriptHashData.secrets ?? [];\n\n // Keys this account generated for the invitation under the script's template are part of the compilation, like its variables.\n // So are the key operations participants resolved, including those of the invitation the spent output was built in.\n const storedInvitation = await context.state.getInvitationOrThrow(invitation.invitationIdentifier);\n const compilationKeys = await listInvitationCompilationKeys(context.state, storedInvitation, scriptHashData.templateIdentifier);\n\n // The spent output's own keys are added below and replace an invitation key of the same variable, since they locked the output.\n const keyReferences: Record<string, KeyReference> = { ...compilationKeys.keyReferences };\n\n for (const secretLookupKey of storedSecrets) {\n const secret = await context.state.getSecretData(secretLookupKey);\n\n if (secret === undefined) {\n // Throw an error because secret identifier's reference is not present. Possible data corruption.\n throw new SecretDataNotFoundError(secretLookupKey);\n }\n\n // A value that is not entropy names no key, so it is compiled as a variable with the other stored variables.\n if (secret.isEntropy === false) {\n storedVariables.push({\n variableIdentifier: secret.secretIdentifier,\n value: secret.value,\n });\n\n continue;\n }\n\n // The key is named by its place in the script template's key tree, and the crypto package derives it for the compile.\n keyReferences[secret.secretIdentifier] = {\n templateIdentifier: scriptHashData.templateIdentifier,\n derivationIndex: parseInt(secret.value),\n };\n }\n\n const variablesFromInvitationCommits = listInvitationVariablesFromCommits(invitation.commits);\n\n // Merge the relevant variables into the variables from the commits. The collected variables override the stored variables\n const allVariables = mergeTemplateConstantsWithInvitationVariables(templateDefinition, [ ...storedVariables, ...variablesFromInvitationCommits ]);\n\n // Private keys are not WalletData, so only the other variables are pushed as bytecode.\n const walletDataBytecode = buildCompilerBytecodeDataFromCompilationVariables(\n templateDefinition,\n omitPrivateKeyVariablesFromCompilationVariables(templateDefinition, allVariables),\n );\n\n // Signatures other participants resolved for this input are used together with the invitation resolutions.\n const resolutions: Record<XOInvitationResolutionIdentifier, Uint8Array> = { ...compilationKeys.resolutions };\n const inputResolutions = mergedInput.resolutions ?? [];\n\n for (const inputResolution of inputResolutions) {\n resolutions[inputResolution.resolutionIdentifier] = inputResolution.value;\n }\n\n // Operations on keys this account holds are derived from its own keys, never taken from another participant.\n const resolutionBytecode = buildResolutionCompilationBytecode(templateDefinition, resolutions, new Set(Object.keys(keyReferences)));\n\n let templateInputUnlockingScript: string | undefined;\n\n // A template input names the unlocking script for the output it spends, but only for outputs of the invitation's own template.\n if (mergedInput.inputIdentifier !== undefined && scriptHashData.templateIdentifier === invitation.templateIdentifier) {\n templateInputUnlockingScript = template.inputs?.[mergedInput.inputIdentifier]?.unlockingScript;\n }\n\n // Create the compiler configuration for the locking script.\n const { compilerConfiguration, lockingScriptId, unlockingScriptId } = createLibauthCompilerForLockingScript(\n templateDefinition,\n scriptHashData.lockingScriptIdentifier,\n scriptHashData.roleIdentifier,\n templateInputUnlockingScript,\n );\n\n // The compiler selects the unlocking script by this identifier.\n if (unlockingScriptId === undefined) {\n throw new TemplateUnlockingScriptNotFoundError(scriptHashData.templateIdentifier, scriptHashData.lockingScriptIdentifier);\n }\n\n const sourceOutputCompatibleWithCompiler: Output = {\n lockingBytecode: hexToBin(scriptHashData.lockingBytecode),\n valueSatoshis: BigInt(unspentOutput.valueSatoshis),\n };\n\n // If the source output is a cash token, then ensure that all the relevant fields are present.\n if (unspentOutput.tokenCategory !== undefined) {\n // If the token is present, then create an object that holds the category.\n // The stored output may omit the amount and NFT commitment that the libauth token type requires, so the token is untyped.\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const token: any = {\n category: hexToBin(unspentOutput.tokenCategory),\n };\n\n // If the token amount is defined then convert it into a big int and add it to the token object.\n if (unspentOutput.tokenAmount != undefined) {\n token.amount = BigInt(unspentOutput.tokenAmount);\n }\n\n // If the token nft capability is defined then create nft key to the token object and then add capability to it.\n if (unspentOutput.tokenNftCapability !== undefined) {\n token.nft = {};\n token.nft.capability = unspentOutput.tokenNftCapability;\n\n // If the token commitment is defined then convert it into a uint8array and add it to the token object.\n if (unspentOutput.tokenNftCommitment !== undefined) {\n token.nft.commitment = hexToBin(unspentOutput.tokenNftCommitment);\n }\n }\n\n // Add the token object to the source output.\n sourceOutputCompatibleWithCompiler.token = token;\n }\n\n const sourceOutputs: Output[] = [];\n sourceOutputs[inputIndex] = sourceOutputCompatibleWithCompiler;\n\n // Create the compilation context for the compiler.\n const compilationContext: CompilationContextBch = {\n inputIndex,\n sourceOutputs,\n transaction: {\n version: mergedInvitation.transactionVersion,\n locktime: mergedInvitation.transactionLocktime,\n inputs: mergedInvitation.inputs,\n outputs: mergedInvitation.outputs,\n } as CompilationContextBch['transaction'],\n };\n\n return {\n outpointTransactionHash: outpointTransactionHashHex,\n outpointIndex,\n template: templateDefinition,\n roleIdentifier: scriptHashData.roleIdentifier,\n compilerConfiguration,\n lockingScriptId,\n unlockingScriptId,\n data: {\n bytecode: { ...walletDataBytecode, ...resolutionBytecode },\n compilationContext,\n },\n inputResolutionIdentifiers: inputResolutions.map((inputResolution) => inputResolution.resolutionIdentifier),\n keyReferences,\n resolutions,\n hasInputResolutions: inputResolutions.length > 0,\n };\n};\n\n/**\n * Checks that an unlocking bytecode unlocks the output its input spends.\n *\n * Signatures other participants resolved are only bytes in the invitation, so the assembled unlocking bytecode is\n * evaluated before it is used.\n *\n * @param {InputUnlockingCompilation} unlockingCompilation - Compilation the unlocking bytecode was built from.\n * @param {Uint8Array} unlockingBytecode - Assembled unlocking bytecode.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation that owns the input.\n * @param {number} mergedInputIndex - Position of the input in the merged input list.\n * @returns {void}\n * @throws {@link UnlockingCompilationContextMissingError} - When the compilation carries no context to evaluate against.\n * @throws {@link UnlockingBytecodeVerificationFailedError} - When the virtual machine rejects the unlocking bytecode.\n */\nconst verifyInputUnlockingBytecode = (\n unlockingCompilation: InputUnlockingCompilation,\n unlockingBytecode: Uint8Array,\n invitationIdentifier: XOInvitationIdentifier,\n mergedInputIndex: number,\n): void => {\n const { data, outpointTransactionHash, outpointIndex } = unlockingCompilation;\n const { compilationContext } = data;\n\n // The compilation data always carries the context the signatures were made against.\n if (compilationContext === undefined) {\n throw new UnlockingCompilationContextMissingError(invitationIdentifier, mergedInputIndex);\n }\n\n const { inputIndex, sourceOutputs, transaction } = compilationContext;\n const inputsWithUnlockingBytecode: Input[] = [];\n\n for (const [ transactionInputIndex, transactionInput ] of transaction.inputs.entries()) {\n // Only the input being checked receives the assembled unlocking bytecode.\n if (transactionInputIndex === inputIndex) {\n inputsWithUnlockingBytecode.push({ ...transactionInput, unlockingBytecode });\n\n continue;\n }\n\n // Another input that is not signed yet is evaluated with an empty unlocking bytecode, which a signature does not cover.\n inputsWithUnlockingBytecode.push({ ...transactionInput, unlockingBytecode: transactionInput.unlockingBytecode ?? Uint8Array.of() });\n }\n\n const virtualMachine = createVirtualMachineBch();\n const programState = virtualMachine.evaluate({ inputIndex, sourceOutputs, transaction: { ...transaction, inputs: inputsWithUnlockingBytecode } });\n const verificationResult = virtualMachine.stateSuccess(programState);\n\n // Libauth reports a failed evaluation as an error string instead of throwing.\n if (typeof verificationResult === 'string') {\n throw new UnlockingBytecodeVerificationFailedError(mergedInputIndex, outpointTransactionHash, outpointIndex, verificationResult);\n }\n};\n\n/**\n * Prepares the unlocking compilation for one merged input and compiles its unlocking script.\n *\n * The crypto package derives the referenced keys and signs with them, so only the unlocking bytecode comes back, or the\n * incomplete compilation when the compiler stops before producing bytecode.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Shared invitation that owns the input.\n * @param {XOTemplate} template - Template of the invitation action.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<{ unlockingCompilation: InputUnlockingCompilation, compilation: Uint8Array | IncompleteScriptCompilation }>} - The\n * prepared compilation and the result of compiling its unlocking script.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for the invitation is not in the secret store.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n * @throws {@link MergedInputNotFoundError} - When the merged invitation has no input at the given index.\n */\nconst compileInputUnlockingScript = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n inputIndex: number,\n): Promise<{ unlockingCompilation: InputUnlockingCompilation; compilation: Uint8Array | IncompleteScriptCompilation }> => {\n const unlockingCompilation = await prepareInputUnlockingCompilation(context, invitation, template, inputIndex);\n\n // The prepared configuration, data, and key references are compiled by the crypto package, which holds the keys.\n const compilation = context.crypto.compileScript({\n compilerConfiguration: unlockingCompilation.compilerConfiguration,\n scriptId: unlockingCompilation.unlockingScriptId,\n data: unlockingCompilation.data,\n keyReferences: unlockingCompilation.keyReferences,\n });\n\n return { unlockingCompilation, compilation };\n};\n\n/**\n * Compiles unlocking bytecode for one merged input.\n *\n * The compiler signs against the merged transaction with the keys this account holds for the spent output. Operations\n * on keys other participants hold, such as their signatures, come from the resolutions in the invitation. When the input\n * carries such signatures, the result is evaluated before it is returned.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Shared invitation that owns the input.\n * @param {XOTemplate} template - Template of the invitation action.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<GeneratedInputUnlockingBytecode>} - Unlocking bytecode for that input.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for the invitation is not in the secret store.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n * @throws {@link UnlockingScriptResolutionsMissingError} - When the compiler reports identifiers missing, carrying what it resolved from the keys.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link UnlockingCompilationContextMissingError} - When the unlocking compilation carries no context to verify against.\n * @throws {@link UnlockingBytecodeVerificationFailedError} - When the unlocking bytecode built with other participants' signatures fails.\n */\nexport const generateInputUnlockingBytecode = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n inputIndex: number,\n): Promise<GeneratedInputUnlockingBytecode> => {\n // The crypto package derives the referenced keys and signs with them, so only the unlocking bytecode comes back.\n const { unlockingCompilation, compilation: unlockingScriptCompilation } = await compileInputUnlockingScript(\n context,\n invitation,\n template,\n inputIndex,\n );\n\n if (unlockingScriptCompilation instanceof Uint8Array === false) {\n // When every failure is an identifier missing from the compilation data, another entity can still provide it.\n if (isOnlyMissingIdentifiers(unlockingScriptCompilation)) {\n throw new UnlockingScriptResolutionsMissingError(\n inputIndex,\n unlockingScriptCompilation.missingIdentifiers,\n unlockingScriptCompilation.resolvedKeyOperations,\n unlockingScriptCompilation.compilationErrors,\n );\n }\n\n // Any other compile failure becomes the engine's unlocking bytecode error, carrying the compiler messages.\n throw new UnlockingBytecodeGenerationFailedError(inputIndex, unlockingScriptCompilation);\n }\n\n // Signatures from other participants are only trusted once the assembled bytecode unlocks the spent output.\n if (unlockingCompilation.hasInputResolutions) {\n verifyInputUnlockingBytecode(unlockingCompilation, unlockingScriptCompilation, invitation.invitationIdentifier, inputIndex);\n }\n\n return {\n outpointTransactionHash: unlockingCompilation.outpointTransactionHash,\n outpointIndex: unlockingCompilation.outpointIndex,\n unlockingBytecode: unlockingScriptCompilation,\n };\n};\n\n/**\n * Compiles unlocking bytecode for one merged input of a stored invitation without appending it to the invitation.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation that owns the input.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<GeneratedInputUnlockingBytecode>} - Unlocking bytecode for that input.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n */\nexport const generateUnlockingBytecode = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n): Promise<GeneratedInputUnlockingBytecode> => {\n // Get the invitation from the store.\n const { invitation } = await context.state.getInvitationOrThrow(invitationIdentifier);\n\n // Get the template for the invitation.\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n return generateInputUnlockingBytecode(context, invitation, template, inputIndex);\n};\n\n/**\n * Lists the key operations an input's unlocking script needs from participants, without signing it.\n *\n * The script compiles with the same keys and resolutions as when it is signed, so values other scripts need, such as\n * public keys inside a redeem script, come from the resolutions. What the compiler still misses is owed by other\n * participants, and the operations it resolved from this account's keys are this account's part. Values other\n * participants already put on the input, such as their signatures, are reported as provided. A script that compiles\n * needs nothing more from anyone.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Shared invitation that owns the input.\n * @param {XOTemplate} template - Template of the invitation action.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<InvitationResolutionRequirements>} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for the invitation is not in the secret store.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link InvitationResolutionIdentifierInvalidError} - When a resolution is not an operation on a template key.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When Libauth compilation fails for a reason other than a missing identifier.\n */\nexport const listUnlockingScriptResolutions = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n inputIndex: number,\n): Promise<InvitationResolutionRequirements> => {\n // The resolutions stand in for keys this account does not hold, so the compiler only misses what is still owed.\n const { unlockingCompilation, compilation } = await compileInputUnlockingScript(context, invitation, template, inputIndex);\n\n // The unlocking script uses no key another participant holds.\n if (compilation instanceof Uint8Array) {\n return { providedIdentifiers: [], ownResolutions: [], missingIdentifiers: [] };\n }\n\n // Any other compile failure becomes the engine's unlocking bytecode error, carrying the compiler messages.\n if (isOnlyMissingIdentifiers(compilation) === false) {\n throw new UnlockingBytecodeGenerationFailedError(inputIndex, compilation);\n }\n\n const resolutionRequirements = groupResolutionRequirements(compilation, unlockingCompilation.resolutions);\n const providedIdentifiers = new Set(resolutionRequirements.providedIdentifiers);\n\n // Values other participants put on the input, such as their signatures, are the parts of this input already provided.\n for (const inputResolutionIdentifier of unlockingCompilation.inputResolutionIdentifiers) {\n const isOwnKeyOperation = unlockingCompilation.keyReferences[inputResolutionIdentifier.split('.')[0]] !== undefined;\n\n if (isOwnKeyOperation === false && providedIdentifiers.has(inputResolutionIdentifier) === false) {\n providedIdentifiers.add(inputResolutionIdentifier);\n resolutionRequirements.providedIdentifiers.push(inputResolutionIdentifier);\n }\n }\n\n return resolutionRequirements;\n};\n","import { Satoshis } from '@xo-cash/primitives';\nimport type { XOInvitationVariableValue, XOTemplate, XOTemplateVariableIdentifier } from '@xo-cash/types';\nimport { compileCashAssemblyString, generateTemplateIdentifier, isCashAssemblyExpression } from '@xo-cash/utils';\nimport { TemplateValueSatoshisInvalidError } from '../errors/index.ts';\n\n/**\n * Parameters for resolving a template output.\n */\nexport type ResolveTemplateOutputValueSatoshisParameters = {\n\n /** Template output field value (string or bigint). */\n templateValueSatoshis: string | bigint;\n\n /** Merged invitation variables for CashAssembly evaluation. */\n variables: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>;\n\n /** Template that defines the output, whose variables and scripts an expression may refer to. */\n template: XOTemplate;\n\n /** Output identifier included in typed errors when resolution fails. */\n outputIdentifier: string;\n};\n\n/**\n * Resolves a template output satoshi amount from a bigint, decimal, or CashAssembly expression.\n *\n * @param {ResolveTemplateOutputValueSatoshisParameters} parameters - Template value, compilation context, and output identifier for errors.\n * @returns {bigint} - Satoshi amount as bigint.\n * @throws {@link TemplateValueSatoshisInvalidError} - When the value is not CashAssembly or fails {@link Satoshis} validation.\n */\nexport const resolveTemplateOutputValueSatoshis = (parameters: ResolveTemplateOutputValueSatoshisParameters): bigint => {\n const { templateValueSatoshis, variables, template, outputIdentifier } = parameters;\n\n let value: string | bigint = templateValueSatoshis;\n\n if (isCashAssemblyExpression(value)) {\n value = compileCashAssemblyString({\n cashAssemblyText: value.toString(),\n variables,\n evaluationDecodeMode: 'bigint',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n }\n\n try {\n return new Satoshis(value).toBigInt();\n } catch (error: unknown) {\n if (error instanceof Error === false) {\n throw error;\n }\n\n throw new TemplateValueSatoshisInvalidError(generateTemplateIdentifier(template), outputIdentifier, value.toString(), { cause: error });\n }\n};\n","import type {\n XOTemplate,\n XOTemplateActionIdentifier,\n XOTemplateInputIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateTransactionRoleData,\n} from '@xo-cash/types';\n\n/**\n * Finds the transaction index declared for one template input or output slot in one list of transaction entries.\n *\n * @param {Pick<XOTemplateTransactionRoleData, 'inputs' | 'outputs'>} transactionEntries - Inputs and outputs of the transaction or of one role.\n * @param {'input' | 'output'} itemType - Whether the slot is an input or an output.\n * @param {XOTemplateInputIdentifier | XOTemplateOutputIdentifier} itemIdentifier - Template input or output slot to look up.\n * @returns {number | undefined} - Transaction index of the slot, or undefined when the entries do not declare one.\n */\nconst findTransactionItemIndex = (\n transactionEntries: Pick<XOTemplateTransactionRoleData, 'inputs' | 'outputs'>,\n itemType: 'input' | 'output',\n itemIdentifier: XOTemplateInputIdentifier | XOTemplateOutputIdentifier,\n): number | undefined => {\n // Input entries name the slot and its index with input fields.\n if (itemType === 'input') {\n for (const transactionInputEntry of transactionEntries.inputs ?? []) {\n if (transactionInputEntry.input === itemIdentifier && transactionInputEntry.inputIndex !== undefined) {\n return transactionInputEntry.inputIndex;\n }\n }\n\n return undefined;\n }\n\n // Output entries name the slot and its index with output fields.\n for (const transactionOutputEntry of transactionEntries.outputs ?? []) {\n if (transactionOutputEntry.output === itemIdentifier && transactionOutputEntry.outputIndex !== undefined) {\n return transactionOutputEntry.outputIndex;\n }\n }\n\n return undefined;\n};\n\n/**\n * Resolves the transaction index declared for one template input or output slot on the active action transaction.\n *\n * @param {XOTemplate} template - Imported template for the invitation.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action on the invitation.\n * @param {'input' | 'output'} itemType - Whether the slot is an input or an output.\n * @param {XOTemplateInputIdentifier | XOTemplateOutputIdentifier} itemIdentifier - Template input or output slot being provided.\n * @returns {number | undefined} - Input or output index from the transaction definition when present.\n */\nexport const resolveTemplateTransactionItemIndex = (\n template: XOTemplate,\n actionIdentifier: XOTemplateActionIdentifier,\n itemType: 'input' | 'output',\n itemIdentifier: XOTemplateInputIdentifier | XOTemplateOutputIdentifier,\n): number | undefined => {\n const templateAction = template.actions[actionIdentifier];\n\n if (templateAction?.transaction === undefined) {\n return undefined;\n }\n\n const transactionDefinition = template.transactions?.[templateAction.transaction];\n\n if (transactionDefinition === undefined) {\n return undefined;\n }\n\n // The transaction entries are checked before the role overlays.\n const transactionItemIndex = findTransactionItemIndex(transactionDefinition, itemType, itemIdentifier);\n\n if (transactionItemIndex !== undefined) {\n return transactionItemIndex;\n }\n\n for (const transactionRoleData of Object.values(transactionDefinition.roles ?? {})) {\n const roleItemIndex = findTransactionItemIndex(transactionRoleData, itemType, itemIdentifier);\n\n if (roleItemIndex !== undefined) {\n return roleItemIndex;\n }\n }\n\n return undefined;\n};\n","import { FungibleTokenAmount, NFTCommitment, TokenCategory } from '@xo-cash/primitives';\nimport type {\n OutputNft,\n OutputToken,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateNonFungibleTokenDetails,\n XOTemplateToken,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport { compileCashAssemblyString, generateTemplateIdentifier, isCashAssemblyExpression, xoTemplateNftCapabilitySchema } from '@xo-cash/utils';\nimport { EMPTY_BYTECODE, ZERO_FUNGIBLE_TOKEN_AMOUNT } from '../defaults.ts';\nimport {\n TemplateTokenAmountInvalidError,\n TemplateTokenCategoryMissingError,\n TemplateTokenNftCapabilityInvalidError,\n TemplateTokenNftCapabilityMissingError,\n} from '../errors/index.ts';\n\ntype VariableValuesByIdentifier = Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>;\n\n/**\n * Resolves the token category from a template token definition.\n *\n * The template writes the category either as hex text or as a CashAssembly expression such as\n * `$(<requestedTokenCategory>)`.\n *\n * @param {string} outputIdentifier - Template output the token belongs to, named in errors.\n * @param {VariableValuesByIdentifier} variableValuesByIdentifier - Template constants and merged invitation variables.\n * @param {XOTemplate} template - Template whose variables and scripts an expression may refer to.\n * @param {string} [category] - Template category field.\n * @returns {Uint8Array} - Category bytes for libauth.\n * @throws {@link TemplateTokenCategoryMissingError} - When the template token has no category.\n */\nconst resolveTemplateTokenCategory = (\n outputIdentifier: string,\n variableValuesByIdentifier: VariableValuesByIdentifier,\n template: XOTemplate,\n category?: string,\n): Uint8Array => {\n // A token cannot be encoded without its category.\n if (category === undefined) {\n throw new TemplateTokenCategoryMissingError(generateTemplateIdentifier(template), outputIdentifier);\n }\n\n // A literal category is already the hex text of the category.\n if (isCashAssemblyExpression(category) === false) {\n return new TokenCategory(category).toBytes();\n }\n\n // Invitation variables hold category ids as hex text. CashAssembly pushes their UTF 8 bytes.\n // Decode those UTF 8 bytes as hex text through TokenCategory. Hex decoding the UTF 8 bytes would double the length.\n const compiledCategory = compileCashAssemblyString({\n cashAssemblyText: category,\n variables: variableValuesByIdentifier,\n evaluationDecodeMode: 'utf8',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n\n return new TokenCategory(compiledCategory).toBytes();\n};\n\n/**\n * Resolves the fungible token amount from a template token definition.\n *\n * The template writes the amount as a bigint, as decimal text, or as a CashAssembly expression. A null or omitted\n * amount means the output carries no fungible tokens. Every written amount is checked through\n * {@link FungibleTokenAmount} so its format and range follow the same rules as any other token amount.\n *\n * @param {XOTemplateToken['amount']} amount - Template amount field.\n * @param {string} outputIdentifier - Template output the amount belongs to, named in the error.\n * @param {VariableValuesByIdentifier} variableValuesByIdentifier - Template constants and merged invitation variables.\n * @param {XOTemplate} template - Template whose variables and scripts an expression may refer to.\n * @returns {bigint} - Fungible token amount.\n * @throws {@link TemplateTokenAmountInvalidError} - When the amount is not a non negative decimal integer within range.\n */\nconst resolveTemplateTokenAmount = (\n amount: XOTemplateToken['amount'],\n outputIdentifier: string,\n variableValuesByIdentifier: VariableValuesByIdentifier,\n template: XOTemplate,\n): bigint => {\n // An output that only carries an NFT has no fungible tokens.\n const hasNoFungibleTokens = amount === null || amount === undefined;\n\n if (hasNoFungibleTokens) {\n return ZERO_FUNGIBLE_TOKEN_AMOUNT;\n }\n\n let writtenAmount: bigint | string = amount;\n\n // An expression is evaluated first, and its result is checked the same way as a literal amount.\n const isAmountExpression = typeof amount === 'string' && isCashAssemblyExpression(amount);\n\n if (isAmountExpression) {\n writtenAmount = compileCashAssemblyString({\n cashAssemblyText: amount,\n variables: variableValuesByIdentifier,\n evaluationDecodeMode: 'bigint',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n }\n\n try {\n return new FungibleTokenAmount(writtenAmount).toBigInt();\n } catch (constructionError: unknown) {\n if (constructionError instanceof Error === false) {\n throw constructionError;\n }\n\n throw new TemplateTokenAmountInvalidError(generateTemplateIdentifier(template), outputIdentifier, String(writtenAmount));\n }\n};\n\n/**\n * Resolves the NFT capability and commitment of a template token.\n *\n * The capability is written as a capability name or as a CashAssembly expression that evaluates to one. The\n * commitment is written as hex text or as a CashAssembly expression, and an omitted commitment is empty.\n *\n * @param {XOTemplateNonFungibleTokenDetails} nftDetails - Template NFT definition.\n * @param {string} outputIdentifier - Template output the token belongs to, named in errors.\n * @param {VariableValuesByIdentifier} variableValuesByIdentifier - Template constants and merged invitation variables.\n * @param {XOTemplate} template - Template whose variables and scripts an expression may refer to.\n * @returns {OutputNft} - Libauth NFT fields for the merged output token.\n * @throws {@link TemplateTokenNftCapabilityMissingError} - When the template NFT has no capability.\n * @throws {@link TemplateTokenNftCapabilityInvalidError} - When the capability is not a known capability name.\n */\nconst resolveTemplateTokenNft = (\n nftDetails: XOTemplateNonFungibleTokenDetails,\n outputIdentifier: string,\n variableValuesByIdentifier: VariableValuesByIdentifier,\n template: XOTemplate,\n): OutputNft => {\n // An NFT cannot be encoded without its capability.\n if (nftDetails.capability === undefined) {\n throw new TemplateTokenNftCapabilityMissingError(generateTemplateIdentifier(template), outputIdentifier);\n }\n\n let capabilityText = nftDetails.capability;\n\n // Compile a CashAssembly capability so a variable can become none, mutable, or minting.\n if (isCashAssemblyExpression(nftDetails.capability)) {\n capabilityText = compileCashAssemblyString({\n cashAssemblyText: nftDetails.capability,\n variables: variableValuesByIdentifier,\n evaluationDecodeMode: 'utf8',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n }\n\n // The schema is the capability list, so an unknown string never reaches the token.\n const parsedCapability = xoTemplateNftCapabilitySchema.safeParse(capabilityText);\n\n if (parsedCapability.success === false) {\n throw new TemplateTokenNftCapabilityInvalidError(generateTemplateIdentifier(template), outputIdentifier, capabilityText);\n }\n\n // An omitted commitment is an NFT without commitment data.\n if (nftDetails.commitment === undefined) {\n return { capability: parsedCapability.data, commitment: EMPTY_BYTECODE };\n }\n\n // A literal commitment is already the hex text of the commitment.\n if (isCashAssemblyExpression(nftDetails.commitment) === false) {\n return { capability: parsedCapability.data, commitment: new NFTCommitment(nftDetails.commitment).toBytes() };\n }\n\n // Commitment hex is stored as text on invitation variables. Decode with utf8 so the hex characters are recovered.\n // Hex decode mode would stringify those UTF 8 bytes again.\n const compiledCommitment = compileCashAssemblyString({\n cashAssemblyText: nftDetails.commitment,\n variables: variableValuesByIdentifier,\n evaluationDecodeMode: 'utf8',\n templateVariables: template.variables,\n templateScripts: template.scripts,\n });\n\n return { capability: parsedCapability.data, commitment: new NFTCommitment(compiledCommitment).toBytes() };\n};\n\n/**\n * Builds the libauth {@link OutputToken} a template output defines.\n *\n * The template output defines the category, amount, and NFT fields of a token that no commit supplied.\n *\n * @param {string} outputIdentifier - Template output the token belongs to, named in errors.\n * @param {VariableValuesByIdentifier} variableValuesByIdentifier - Template constants and merged invitation variables.\n * @param {XOTemplate} template - Template whose variables and scripts an expression may refer to.\n * @param {XOTemplateToken | null} [templateToken] - Template output token. Null means the output carries no token.\n * @returns {OutputToken | undefined} - Token for the merged output, or undefined when the template defines none.\n * @throws {@link TemplateTokenCategoryMissingError} - When the template token has no category.\n * @throws {@link TemplateTokenAmountInvalidError} - When the amount is not a valid fungible token amount.\n * @throws {@link TemplateTokenNftCapabilityMissingError} - When the template NFT has no capability.\n * @throws {@link TemplateTokenNftCapabilityInvalidError} - When the capability is not a known capability name.\n */\nexport const resolveTemplateTokenForOutput = (\n outputIdentifier: string,\n variableValuesByIdentifier: VariableValuesByIdentifier,\n template: XOTemplate,\n templateToken?: XOTemplateToken | null,\n): OutputToken | undefined => {\n // An omitted or null template token means the output intentionally carries no token.\n if (templateToken === undefined || templateToken === null) {\n return undefined;\n }\n\n const resolvedToken: OutputToken = {\n category: resolveTemplateTokenCategory(outputIdentifier, variableValuesByIdentifier, template, templateToken.category),\n amount: resolveTemplateTokenAmount(templateToken.amount, outputIdentifier, variableValuesByIdentifier, template),\n };\n\n // An omitted or null NFT means the token is fungible only, so no nft field is attached.\n if (templateToken.nft !== null && templateToken.nft !== undefined) {\n resolvedToken.nft = resolveTemplateTokenNft(templateToken.nft, outputIdentifier, variableValuesByIdentifier, template);\n }\n\n return resolvedToken;\n};\n","import { DEFAULT_SEQUENCE_NUMBER, EMPTY_BYTECODE, PLACEHOLDER_UNLOCKING_BYTECODE, ZERO_FUNGIBLE_TOKEN_AMOUNT } from '../../defaults.ts';\nimport type {\n OutputToken,\n XOInvitationCommitIdentifier,\n XOInvitationToken,\n XOInvitationVariable,\n XOInvitationOutput,\n XOTemplate,\n} from '@xo-cash/types';\nimport {\n CommitTokenCategoryMissingError,\n CommitTokenNftCapabilityMissingError,\n MergedOutputLockingBytecodeMissingError,\n} from '../../errors/index.ts';\nimport { mergeTemplateConstantsWithInvitationVariables, resolveTemplateOutputLockingBytecode } from '../../compilation/index.ts';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport { getTemplateOutputOrThrow } from '../../template.ts';\nimport { resolveTemplateOutputValueSatoshis, resolveTemplateTokenForOutput, resolveTemplateTransactionItemIndex } from '../../resolutions/index.ts';\nimport type { InvitationInputWithSpentOutputFields, MergedInvitationInput, MergedInvitationOutput } from './types.ts';\n\n/**\n * Completes a commit-supplied token into the libauth {@link OutputToken} used on the merged output.\n *\n * A commit token may leave fields unset. The category and an NFT capability are required, an omitted fungible amount\n * counts as zero, and an omitted NFT commitment counts as empty.\n *\n * Commit token overrides template resolution in {@link completeMergedOutput}.\n *\n * @param {XOInvitationToken} token - Token object from an invitation commit output.\n * @param {XOInvitationCommitIdentifier} commitIdentifier - Commit that last wrote the output, named in errors.\n * @param {number} outputIndex - Position of the output in the merged output list, named in errors.\n * @returns {OutputToken} - Libauth token with every required field set.\n * @throws {@link CommitTokenCategoryMissingError} - When the token has no category.\n * @throws {@link CommitTokenNftCapabilityMissingError} - When the token has an NFT without a capability.\n */\nconst completeCommittedToken = (token: XOInvitationToken, commitIdentifier: XOInvitationCommitIdentifier, outputIndex: number): OutputToken => {\n if (token.category === undefined) {\n throw new CommitTokenCategoryMissingError(commitIdentifier, outputIndex);\n }\n\n const completedToken: OutputToken = {\n category: token.category,\n // An omitted fungible amount counts as zero.\n amount: token.amount === undefined ? ZERO_FUNGIBLE_TOKEN_AMOUNT : token.amount,\n };\n\n if (token.nft !== undefined) {\n if (token.nft.capability === undefined) {\n throw new CommitTokenNftCapabilityMissingError(commitIdentifier, outputIndex);\n }\n\n // An omitted commitment is an NFT without commitment data.\n const nftCommitment = token.nft.commitment === undefined ? EMPTY_BYTECODE : token.nft.commitment;\n\n completedToken.nft = {\n capability: token.nft.capability,\n commitment: nftCommitment,\n };\n }\n\n return completedToken;\n};\n\n/**\n * Completes one merged input with the values its commits left unset.\n *\n * The transaction index comes from the template when the input fills a template input. Libauth reads the sequence\n * number and the unlocking script length of every input, so a missing sequence number becomes\n * {@link DEFAULT_SEQUENCE_NUMBER}, meaning no relative locktime, and a missing unlocking script becomes\n * {@link PLACEHOLDER_UNLOCKING_BYTECODE}, so the transaction can be built before that signature exists.\n *\n * @param {InvitationInputWithSpentOutputFields} input - Merged input.\n * @param {XOTemplate} [template] - Template used to resolve the transaction index from inputIndex.\n * @param {string} [actionIdentifier] - Invitation action whose transaction definition supplies inputIndex.\n * @returns {InvitationInputWithSpentOutputFields} - Input with the template transaction index and the defaults applied.\n */\nexport const completeMergedInput = (\n input: InvitationInputWithSpentOutputFields,\n template?: XOTemplate,\n actionIdentifier?: string,\n): InvitationInputWithSpentOutputFields => {\n const processedInput: InvitationInputWithSpentOutputFields = { ...input };\n\n if (\n processedInput.transactionIndex === undefined\n && processedInput.inputIdentifier !== undefined\n && template !== undefined\n && actionIdentifier !== undefined\n ) {\n const templateTransactionInputIndex = resolveTemplateTransactionItemIndex(\n template,\n actionIdentifier,\n 'input',\n processedInput.inputIdentifier,\n );\n\n if (templateTransactionInputIndex !== undefined) {\n processedInput.transactionIndex = templateTransactionInputIndex;\n }\n }\n\n // Libauth encodes sequenceNumber as 4 bytes. 0 means this input has no relative locktime.\n if (processedInput.sequenceNumber === undefined) {\n processedInput.sequenceNumber = DEFAULT_SEQUENCE_NUMBER;\n }\n\n // Libauth encodes unlockingBytecode.length. An empty script is valid encoding for an input that is not signed yet.\n if (processedInput.unlockingBytecode === undefined) {\n processedInput.unlockingBytecode = PLACEHOLDER_UNLOCKING_BYTECODE;\n }\n\n return processedInput;\n};\n\n/**\n * Resolves every merged input with the values its commits left unset.\n *\n * @param {readonly MergedInvitationInput[]} mergedInputs - Merged inputs in introduction order.\n * @param {XOTemplate} template - Template used to resolve the transaction index from inputIndex.\n * @param {string} actionIdentifier - Invitation action for the template transaction lookup.\n * @returns {MergedInvitationInput[]} - Resolved inputs in introduction order.\n */\nexport const resolveMergedInputs = (\n mergedInputs: readonly MergedInvitationInput[],\n template: XOTemplate,\n actionIdentifier: string,\n): MergedInvitationInput[] => {\n const resolvedInputs: MergedInvitationInput[] = [];\n\n for (const mergedInput of mergedInputs) {\n const completedInput = completeMergedInput(mergedInput, template, actionIdentifier);\n\n // Completion returns the input fields only, so the source commit is carried over explicitly.\n resolvedInputs.push({ ...completedInput, sourceCommitIdentifier: mergedInput.sourceCommitIdentifier });\n }\n\n return resolvedInputs;\n};\n\n/**\n * Completes one merged output with the values its commits left unset.\n *\n * Outputs without an output identifier keep the fields already on the commit, and only their token is completed.\n * When an identifier is present, the locking bytecode, value, token, and transaction index the commits left unset are\n * taken from the template and the merged variables.\n *\n * @param {MergedInvitationOutput} output - Merged output, including an output that only names a template slot.\n * @param {number} outputIndex - Position of the output in the merged output list.\n * @param {XOInvitationVariable[]} variables - Merged invitation variables used to evaluate CashAssembly.\n * @param {XOTemplate} template - Template that defines output locking scripts.\n * @param {string} actionIdentifier - Invitation action whose transaction definition supplies the output index.\n * @returns {XOInvitationOutput} - Output with the template values and a complete token applied.\n * @throws {@link MergedOutputLockingBytecodeMissingError} - When neither the template output nor its commit provides locking bytecode.\n * @throws {@link CommitTokenCategoryMissingError} - When a token the commit supplies has no category.\n * @throws {@link CommitTokenNftCapabilityMissingError} - When an NFT the commit supplies has no capability.\n */\nexport const completeMergedOutput = (\n output: MergedInvitationOutput,\n outputIndex: number,\n variables: XOInvitationVariable[],\n template: XOTemplate,\n actionIdentifier: string,\n): XOInvitationOutput => {\n const completedOutput: XOInvitationOutput = { ...output };\n\n if (output.outputIdentifier === undefined) {\n // Commit may include token directly when no template outputIdentifier is used.\n if (output.token !== undefined) {\n completedOutput.token = completeCommittedToken(output.token, output.sourceCommitIdentifier, outputIndex);\n }\n\n return completedOutput;\n }\n\n const templateOutput = getTemplateOutputOrThrow(template, output.outputIdentifier);\n const compilationVariables = mergeTemplateConstantsWithInvitationVariables(template, variables);\n\n // Resolve valueSatoshis from the template when the commit does not supply an amount.\n if (completedOutput.valueSatoshis === undefined && templateOutput.valueSatoshis !== undefined) {\n completedOutput.valueSatoshis = resolveTemplateOutputValueSatoshis({\n templateValueSatoshis: templateOutput.valueSatoshis,\n variables: compilationVariables,\n template,\n outputIdentifier: output.outputIdentifier,\n });\n }\n\n // Resolve lockingBytecode from template if not provided\n if (completedOutput.lockingBytecode === undefined && templateOutput.lockingScript !== undefined) {\n completedOutput.lockingBytecode = resolveTemplateOutputLockingBytecode(template, output.outputIdentifier, variables);\n }\n\n if (output.token !== undefined) {\n // A commit token overrides the template token.\n completedOutput.token = completeCommittedToken(output.token, output.sourceCommitIdentifier, outputIndex);\n } else {\n // Without a commit token, the template output defines the token.\n const templateToken = resolveTemplateTokenForOutput(output.outputIdentifier, compilationVariables, template, templateOutput.token);\n\n if (templateToken !== undefined) {\n completedOutput.token = templateToken;\n }\n }\n\n if (completedOutput.transactionIndex === undefined) {\n const templateTransactionOutputIndex = resolveTemplateTransactionItemIndex(template, actionIdentifier, 'output', output.outputIdentifier);\n\n if (templateTransactionOutputIndex !== undefined) {\n completedOutput.transactionIndex = templateTransactionOutputIndex;\n }\n }\n\n if (completedOutput.lockingBytecode === undefined) {\n throw new MergedOutputLockingBytecodeMissingError(\n output.outputIdentifier,\n outputIndex,\n completedOutput.transactionIndex,\n output.sourceCommitIdentifier,\n generateTemplateIdentifier(template),\n );\n }\n\n return completedOutput;\n};\n\n/**\n * Resolves every merged output with the values its commits left unset.\n *\n * @param {readonly MergedInvitationOutput[]} mergedOutputs - Merged outputs in introduction order.\n * @param {XOInvitationVariable[]} mergedVariables - Merged invitation variables used to evaluate CashAssembly.\n * @param {XOTemplate} template - Template that defines output locking scripts, values, and tokens.\n * @param {string} actionIdentifier - Invitation action for the template transaction lookup.\n * @returns {MergedInvitationOutput[]} - Resolved outputs in introduction order.\n * @throws {@link MergedOutputLockingBytecodeMissingError} - When neither the template output nor its commit provides locking bytecode.\n */\nexport const resolveMergedOutputs = (\n mergedOutputs: readonly MergedInvitationOutput[],\n mergedVariables: XOInvitationVariable[],\n template: XOTemplate,\n actionIdentifier: string,\n): MergedInvitationOutput[] => {\n const resolvedOutputs: MergedInvitationOutput[] = [];\n\n for (const [ outputIndex, mergedOutput ] of mergedOutputs.entries()) {\n // Template outputs get their locking bytecode, value, and token from the template and the merged variables.\n const completedOutput = completeMergedOutput(mergedOutput, outputIndex, mergedVariables, template, actionIdentifier);\n\n // Completion returns the output fields only, so the source commit is carried over explicitly.\n resolvedOutputs.push({ ...completedOutput, sourceCommitIdentifier: mergedOutput.sourceCommitIdentifier });\n }\n\n return resolvedOutputs;\n};\n","/**\n * Merges invitation commits into one transaction view.\n *\n * Commits form one chain in stored order, and each commit names the commit before it. A later commit can add new\n * inputs and outputs, or extend an input or output from an earlier commit through mergesWith. An extension only fills\n * fields that earlier versions left empty, so no participant can overwrite what another participant committed.\n *\n * Merging runs in three stages.\n *\n * 1. Merge. Only committed values are combined, and the template is not consulted. Each leaf item is walked back\n * through mergesWith to the funding item that introduced it, and the versions in that chain are combined from the\n * funding item to the leaf so earlier values are kept. Inputs that spend one outpoint through sibling extensions\n * collapse into one input. Items are listed in the order their funding items were introduced.\n * 2. Resolve. The template and the merged variables fill every value the commits left unset, and the values the\n * transaction needs but no commit set receive their defaults.\n * 3. Order. Items are ordered by transactionIndex. Items that tie, or have none, keep their introduction order.\n *\n * Resolving runs after merging because template values can depend on variables other participants commit later.\n * Keeping introduction order for ties means an input stays at the same position after an unlocking extension\n * replaces it, which signatures that cover every input require.\n */\n\nimport { binToHex } from '@bitauth/libauth';\nimport { DEFAULT_LOCKTIME, DEFAULT_VERSION, PLACEHOLDER_UNLOCKING_BYTECODE } from '../../defaults.ts';\nimport type {\n XOInvitation,\n XOInvitationCommitIdentifier,\n XOInvitationIdentifier,\n XOInvitationVariable,\n XOInvitationCommit,\n XOTemplate,\n} from '@xo-cash/types';\nimport {\n TransactionLocktimeDuplicatedError,\n TransactionVersionDuplicatedError,\n InvitationVariableIdentifierInvalidError,\n} from '../../errors/index.ts';\nimport type { MergedInvitationInput, MergedInvitationOutput, MergedInvitation, MergedInputWithIntroductionOrder } from './types.ts';\nimport { validateCommitChain, listCommittedItems, fillEmptyFields, combineCommittedItems } from './chain.ts';\nimport { validateTransactionIndices, orderByIntroduction, orderByTransactionIndex } from './order.ts';\nimport { resolveMergedInputs, resolveMergedOutputs } from './complete.ts';\n\n/**\n * Merges the commit level data that is not an input or output.\n *\n * Variables are collected from every commit in chain order. Version and locktime may each be set by one commit only,\n * because the transaction can have only one of each.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @returns {object} - Variables in commit order, and the version and locktime when a commit sets them.\n * @throws {@link InvitationVariableIdentifierInvalidError} - When any variable identifier contains a dot.\n * @throws {@link TransactionVersionDuplicatedError} - When more than one commit sets the transaction version.\n * @throws {@link TransactionLocktimeDuplicatedError} - When more than one commit sets the transaction locktime.\n */\nconst mergeVariablesVersionAndLocktime = (commits: readonly XOInvitationCommit[]): {\n variables: XOInvitationVariable[];\n transactionVersion: number | undefined;\n transactionLocktime: number | undefined;\n} => {\n const variables: XOInvitationVariable[] = [];\n const invalidVariables: Array<{ variableIdentifier: string; commitIdentifier: XOInvitationCommitIdentifier }> = [];\n const versionCommitIdentifiers: XOInvitationCommitIdentifier[] = [];\n const locktimeCommitIdentifiers: XOInvitationCommitIdentifier[] = [];\n\n let transactionVersion: number | undefined;\n let transactionLocktime: number | undefined;\n\n for (const commit of commits) {\n if (commit.data.variables !== undefined) {\n for (const variable of commit.data.variables) {\n // The compiler reads a dotted identifier as an operation on a key, so a dotted variable would replace\n // the public key or signature that operation derives from the key.\n if (variable.variableIdentifier.includes('.')) {\n invalidVariables.push({ variableIdentifier: variable.variableIdentifier, commitIdentifier: commit.commitIdentifier });\n\n continue;\n }\n\n variables.push(variable);\n }\n }\n\n if (commit.data.transactionVersion !== undefined) {\n versionCommitIdentifiers.push(commit.commitIdentifier);\n if (transactionVersion === undefined) {\n transactionVersion = commit.data.transactionVersion;\n }\n }\n\n if (commit.data.transactionLocktime !== undefined) {\n locktimeCommitIdentifiers.push(commit.commitIdentifier);\n if (transactionLocktime === undefined) {\n transactionLocktime = commit.data.transactionLocktime;\n }\n }\n }\n\n // Every invalid identifier is reported together so all offending commits can be fixed at once.\n if (invalidVariables.length > 0) {\n throw new InvitationVariableIdentifierInvalidError(invalidVariables);\n }\n\n if (versionCommitIdentifiers.length > 1) {\n throw new TransactionVersionDuplicatedError(versionCommitIdentifiers);\n }\n\n if (locktimeCommitIdentifiers.length > 1) {\n throw new TransactionLocktimeDuplicatedError(locktimeCommitIdentifiers);\n }\n\n return { variables, transactionVersion, transactionLocktime };\n};\n\n/**\n * Returns true when unlocking bytecode is absent or still the merge placeholder.\n *\n * @param {MergedInvitationInput['unlockingBytecode']} unlockingBytecode - Unlocking script on a merged input.\n * @returns {boolean} - True when the input is not signed yet.\n */\nexport const isUnlockingBytecodeMissingOrPlaceholder = (unlockingBytecode: MergedInvitationInput['unlockingBytecode']): boolean => {\n if (unlockingBytecode === undefined) {\n return true;\n }\n\n // Merger normalizes unlock to bytes. Match the placeholder used for unsigned inputs.\n if (unlockingBytecode.length !== PLACEHOLDER_UNLOCKING_BYTECODE.length) {\n return false;\n }\n\n for (let byteIndex = 0; byteIndex < unlockingBytecode.length; byteIndex += 1) {\n if (unlockingBytecode[byteIndex] !== PLACEHOLDER_UNLOCKING_BYTECODE[byteIndex]) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Combines two combined inputs that spend the same outpoint.\n *\n * Two extensions can target one funding input, for example one that sets the transaction index and one that signs.\n * Both are combined before completion, so every field the later sibling committed can still fill a field the\n * earlier sibling left empty. The earlier sibling keeps every field it set.\n *\n * @param {MergedInvitationInput} earlierSibling - Input combined from the earlier leaf.\n * @param {MergedInvitationInput} laterSibling - Input combined from the later leaf that spends the same outpoint.\n * @returns {MergedInvitationInput} - One input that keeps committed fields from both siblings.\n */\nconst combineInputSiblings = (earlierSibling: MergedInvitationInput, laterSibling: MergedInvitationInput): MergedInvitationInput => {\n // An empty unlocking script counts as unsigned, so a signature from the later sibling is still accepted.\n const isSignedOnlyByLaterSibling =\n isUnlockingBytecodeMissingOrPlaceholder(earlierSibling.unlockingBytecode)\n && isUnlockingBytecodeMissingOrPlaceholder(laterSibling.unlockingBytecode) === false;\n\n const combinedInput = fillEmptyFields(earlierSibling, laterSibling);\n\n if (isSignedOnlyByLaterSibling) {\n combinedInput.unlockingBytecode = laterSibling.unlockingBytecode;\n\n // The signing sibling is the commit that last wrote this input, and later signing extends its leaf.\n combinedInput.sourceCommitIdentifier = laterSibling.sourceCommitIdentifier;\n }\n\n return combinedInput;\n};\n\n/**\n * Collapses combined inputs that spend the same outpoint into one input.\n *\n * Runs before completion so defaults never occupy a field a sibling committed. Inputs keep the position of the\n * first sibling seen for each outpoint. Inputs without an outpoint follow them.\n *\n * @param {MergedInputWithIntroductionOrder[]} inputsWithIntroductionOrder - Combined inputs in leaf order.\n * @returns {MergedInputWithIntroductionOrder[]} - At most one input per outpoint.\n */\nconst collapseInputsSpendingOneOutpoint = (inputsWithIntroductionOrder: MergedInputWithIntroductionOrder[]): MergedInputWithIntroductionOrder[] => {\n const inputByOutpointKey = new Map<string, MergedInputWithIntroductionOrder>();\n const inputsWithoutOutpoint: MergedInputWithIntroductionOrder[] = [];\n\n for (const inputWithIntroductionOrder of inputsWithIntroductionOrder) {\n const { outpointTransactionHash, outpointIndex } = inputWithIntroductionOrder.mergedItem;\n\n // An input without an outpoint cannot share one with a sibling.\n if (outpointTransactionHash === undefined || outpointIndex === undefined) {\n inputsWithoutOutpoint.push(inputWithIntroductionOrder);\n\n continue;\n }\n\n const outpointKey = `${binToHex(outpointTransactionHash)}:${String(outpointIndex)}`;\n const earlierSibling = inputByOutpointKey.get(outpointKey);\n\n if (earlierSibling === undefined) {\n inputByOutpointKey.set(outpointKey, inputWithIntroductionOrder);\n\n continue;\n }\n\n // The earlier sibling keeps its introduction order so the input does not move after it is signed.\n inputByOutpointKey.set(outpointKey, {\n mergedItem: combineInputSiblings(earlierSibling.mergedItem, inputWithIntroductionOrder.mergedItem),\n introductionOrder: earlierSibling.introductionOrder,\n });\n }\n\n return [ ...inputByOutpointKey.values(), ...inputsWithoutOutpoint ];\n};\n\n/**\n * Merges the committed values of every input, without consulting the template.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @param {ReadonlyMap<XOInvitationCommitIdentifier, number>} commitPositionByIdentifier - Position of each commit in the chain.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation whose commits hold the inputs, named in errors.\n * @returns {MergedInvitationInput[]} - Merged inputs in introduction order, holding only committed values.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an input that does not exist.\n */\nconst mergeInputs = (\n commits: readonly XOInvitationCommit[],\n commitPositionByIdentifier: ReadonlyMap<XOInvitationCommitIdentifier, number>,\n invitationIdentifier: XOInvitationIdentifier,\n): MergedInvitationInput[] => {\n const committedInputs = listCommittedItems(commits, (commit) => commit.data.inputs);\n const combinedInputsWithIntroductionOrder = combineCommittedItems(committedInputs, commitPositionByIdentifier, 'input', invitationIdentifier);\n\n // Siblings collapse before resolving so its defaults cannot block a value another sibling committed.\n const collapsedInputs = collapseInputsSpendingOneOutpoint(combinedInputsWithIntroductionOrder);\n\n return orderByIntroduction(collapsedInputs);\n};\n\n/**\n * Merges the committed values of every output, without consulting the template.\n *\n * @param {readonly XOInvitationCommit[]} commits - Invitation commits in stored order.\n * @param {ReadonlyMap<XOInvitationCommitIdentifier, number>} commitPositionByIdentifier - Position of each commit in the chain.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation whose commits hold the outputs, named in errors.\n * @returns {MergedInvitationOutput[]} - Merged outputs in introduction order, holding only committed values.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an output that does not exist.\n */\nconst mergeOutputs = (\n commits: readonly XOInvitationCommit[],\n commitPositionByIdentifier: ReadonlyMap<XOInvitationCommitIdentifier, number>,\n invitationIdentifier: XOInvitationIdentifier,\n): MergedInvitationOutput[] => {\n const committedOutputs = listCommittedItems(commits, (commit) => commit.data.outputs);\n const outputsWithIntroductionOrder = combineCommittedItems(committedOutputs, commitPositionByIdentifier, 'output', invitationIdentifier);\n\n return orderByIntroduction(outputsWithIntroductionOrder);\n};\n\n/**\n * Merges invitation commits and transforms it into MergedInvitation structure.\n *\n * @param {XOInvitation} invitation - The invitation containing commits to merge.\n * @param {XOTemplate} template - The template used for resolving output identifiers.\n * @returns {MergedInvitation} - Merged invitation structure.\n * @throws {@link CommitIdentifierDuplicatedError} - When a commit identifier appears more than once.\n * @throws {@link ParentCommitNotFoundError} - When a commit names a previous commit that is not in the invitation.\n * @throws {@link CommitChainOrderInvalidError} - When a commit does not name the commit stored before it.\n * @throws {@link InvitationVariableIdentifierInvalidError} - When any variable identifier contains a dot.\n * @throws {@link TransactionVersionDuplicatedError} - When more than one commit sets the transaction version.\n * @throws {@link TransactionLocktimeDuplicatedError} - When more than one commit sets the transaction locktime.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an item that does not exist.\n * @throws {@link MergedOutputLockingBytecodeMissingError} - When neither the template output nor its commit provides locking bytecode.\n * @throws {@link TransactionIndexDuplicatedError} - When two merged inputs or two merged outputs claim the same transactionIndex.\n * @todo Handle different variables with the same identifier according to the minimum and maximum the template sets.\n */\nexport const mergeInvitationCommits = (invitation: XOInvitation, template: XOTemplate): MergedInvitation => {\n const { commits } = invitation;\n\n // Earlier commits are authoritative only when stored order and previous commit links agree, so the chain is checked first.\n const commitPositionByIdentifier = validateCommitChain(commits);\n\n // Merge variables, state, version, and locktime\n const { variables: mergedVariables, transactionVersion, transactionLocktime } = mergeVariablesVersionAndLocktime(commits);\n\n // Merge. Only committed values are combined here, and the template is not consulted.\n const mergedInputs = mergeInputs(commits, commitPositionByIdentifier, invitation.invitationIdentifier);\n const mergedOutputs = mergeOutputs(commits, commitPositionByIdentifier, invitation.invitationIdentifier);\n\n // Resolve. The template and the merged variables fill the values the commits left unset.\n const resolvedInputs = resolveMergedInputs(mergedInputs, template, invitation.actionIdentifier);\n const resolvedOutputs = resolveMergedOutputs(mergedOutputs, mergedVariables, template, invitation.actionIdentifier);\n\n // Order. Template indexes are only known after resolving, so duplicates and positions are checked last.\n validateTransactionIndices(resolvedInputs, 'input');\n validateTransactionIndices(resolvedOutputs, 'output');\n\n return {\n inputs: orderByTransactionIndex(resolvedInputs),\n outputs: orderByTransactionIndex(resolvedOutputs),\n variables: mergedVariables,\n transactionVersion: transactionVersion ?? DEFAULT_VERSION,\n transactionLocktime: transactionLocktime ?? DEFAULT_LOCKTIME,\n };\n};\n","import { TransactionHash } from '@xo-cash/primitives';\nimport type { XOInvitation, XOInvitationCommit, XOInvitationMergesWithReference } from '@xo-cash/types';\nimport type { MergedInvitation, MergedInvitationInput, MergedInvitationOutput } from './types.ts';\n\n/**\n * Finds the output index inside a commit that corresponds to a merged output.\n *\n * Match order is output identifier, then transaction index. A single output commit is unambiguous.\n * No match returns undefined rather than guessing the last item.\n *\n * Later extension commits often omit fields that earlier commits already supplied. Matching therefore\n * continues through weaker strategies instead of stopping after the first failed strong match.\n *\n * @param {XOInvitationCommit} sourceCommit - Commit that last wrote the merged output.\n * @param {MergedInvitationOutput} mergedOutput - Merged output from mergeInvitationCommits.\n * @returns {number | undefined} - Index in commit.data.outputs, or undefined when no match is found.\n */\nconst findOutputIndexInCommitForMergedOutput = (sourceCommit: XOInvitationCommit, mergedOutput: MergedInvitationOutput): number | undefined => {\n const outputs = sourceCommit.data.outputs;\n\n // An empty or missing outputs array cannot host a mergesWith item index.\n if (outputs === undefined || outputs.length === 0) {\n return undefined;\n }\n\n // Prefer the template output identifier when the merged output still carries one.\n if (mergedOutput.outputIdentifier !== undefined) {\n for (let outputIndex = 0; outputIndex < outputs.length; outputIndex += 1) {\n if (outputs[outputIndex].outputIdentifier === mergedOutput.outputIdentifier) {\n return outputIndex;\n }\n }\n }\n\n // Fall through when the source commit is an extension that omitted outputIdentifier.\n // Transaction index still uniquely identifies the slot once the merged view has one.\n if (mergedOutput.transactionIndex !== undefined) {\n for (let outputIndex = 0; outputIndex < outputs.length; outputIndex += 1) {\n if (outputs[outputIndex].transactionIndex === mergedOutput.transactionIndex) {\n return outputIndex;\n }\n }\n }\n\n // A single output commit is unambiguous even when identifiers and indexes are absent.\n if (outputs.length === 1) {\n return 0;\n }\n\n // Multiple candidates without a deterministic key must not guess an item.\n return undefined;\n};\n\n/**\n * Finds the input index inside a commit that corresponds to a merged input.\n *\n * Match order is outpoint, then input identifier, then transaction index. A single input commit is unambiguous.\n * No match returns undefined rather than guessing the last item.\n *\n * Extension commits that only append fields such as transactionIndex often lack the original outpoint.\n * Failed outpoint matching therefore continues to weaker strategies so a later commit can still resolve mergesWith.\n *\n * @param {XOInvitationCommit} sourceCommit - Commit that last wrote the merged input.\n * @param {MergedInvitationInput} mergedInput - Merged input from mergeInvitationCommits.\n * @returns {number | undefined} - Index in commit.data.inputs, or undefined when no match is found.\n */\nconst findInputIndexInCommitForMergedInput = (sourceCommit: XOInvitationCommit, mergedInput: MergedInvitationInput): number | undefined => {\n const inputs = sourceCommit.data.inputs;\n\n // An empty or missing inputs array cannot host a mergesWith item index.\n if (inputs === undefined || inputs.length === 0) {\n return undefined;\n }\n\n // Outpoint is the strongest match when the source commit still records it.\n if (mergedInput.outpointTransactionHash !== undefined && mergedInput.outpointIndex !== undefined) {\n // Normalize through TransactionHash so hex and byte encodings compare as the same outpoint.\n const mergedOutpointTransactionHash = new TransactionHash(mergedInput.outpointTransactionHash);\n\n for (let inputIndex = 0; inputIndex < inputs.length; inputIndex += 1) {\n const commitInput = inputs[inputIndex];\n\n // Both sides must carry a complete outpoint before equality is meaningful.\n if (\n commitInput.outpointTransactionHash !== undefined\n && commitInput.outpointIndex !== undefined\n && mergedOutpointTransactionHash.equals(new TransactionHash(commitInput.outpointTransactionHash))\n && commitInput.outpointIndex === mergedInput.outpointIndex\n ) {\n return inputIndex;\n }\n }\n }\n\n // Fall through when the source commit omitted outpoint after an earlier extension.\n // Template input identifiers remain stable across mergesWith chains when present.\n if (mergedInput.inputIdentifier !== undefined) {\n for (let inputIndex = 0; inputIndex < inputs.length; inputIndex += 1) {\n if (inputs[inputIndex].inputIdentifier === mergedInput.inputIdentifier) {\n return inputIndex;\n }\n }\n }\n\n // Transaction index identifies the funding slot once the merged input has one.\n if (mergedInput.transactionIndex !== undefined) {\n for (let inputIndex = 0; inputIndex < inputs.length; inputIndex += 1) {\n if (inputs[inputIndex].transactionIndex === mergedInput.transactionIndex) {\n return inputIndex;\n }\n }\n }\n\n // A single input commit is unambiguous even when outpoint and identifiers are absent.\n if (inputs.length === 1) {\n return 0;\n }\n\n // Multiple candidates without a deterministic key must not guess an item.\n return undefined;\n};\n\n/**\n * Resolves the mergesWith target for one merged input or output.\n *\n * @param {XOInvitation} invitation - Invitation that contains source commits.\n * @param {MergedInvitation} mergedCommit - Full merged transaction.\n * @param {'input' | 'output'} itemType - Whether the item is a merged input or a merged output.\n * @param {number} mergedItemIndex - Position in mergedCommit.inputs or mergedCommit.outputs.\n * @returns {XOInvitationMergesWithReference | undefined} - Merge target for the merged item, or undefined when the item cannot be matched.\n */\nexport const resolveMergedItemMergeTarget = (\n invitation: XOInvitation,\n mergedCommit: MergedInvitation,\n itemType: 'input' | 'output',\n mergedItemIndex: number,\n): XOInvitationMergesWithReference | undefined => {\n const mergedInput = mergedCommit.inputs[mergedItemIndex];\n const mergedOutput = mergedCommit.outputs[mergedItemIndex];\n\n let mergedItem: MergedInvitationInput | MergedInvitationOutput | undefined = mergedOutput;\n if (itemType === 'input') {\n mergedItem = mergedInput;\n }\n\n // The merged preview array index must already exist before a mergesWith target can be built.\n if (mergedItem === undefined) {\n return undefined;\n }\n\n const { sourceCommitIdentifier } = mergedItem;\n\n // Merger always tags resolved items with the commit that last authored them.\n if (sourceCommitIdentifier === undefined) {\n return undefined;\n }\n\n // Locate that authoring commit in the stored invitation history.\n const sourceCommit = invitation.commits.find((commit) => commit.commitIdentifier === sourceCommitIdentifier);\n\n // A missing commit means the merged view and stored history have diverged.\n if (sourceCommit === undefined) {\n return undefined;\n }\n\n // Map the merged item onto an index inside that commit's inputs or outputs array. Inputs and outputs match on different fields.\n let itemIndexInCommit: number | undefined;\n if (itemType === 'input') {\n itemIndexInCommit = findInputIndexInCommitForMergedInput(sourceCommit, mergedInput);\n } else {\n itemIndexInCommit = findOutputIndexInCommitForMergedOutput(sourceCommit, mergedOutput);\n }\n\n // Without a concrete item index the mergesWith reference would point at the wrong item.\n if (itemIndexInCommit === undefined) {\n return undefined;\n }\n\n // The returned reference is what later commits use as mergesWith.\n return {\n commitIdentifier: sourceCommitIdentifier,\n itemIndex: itemIndexInCommit,\n };\n};\n","import type { State, StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitationIdentifier, XOTemplate } from '@xo-cash/types';\nimport { mergeInvitationCommits, type MergedInvitation } from '../merge/index.ts';\n\n/**\n * Loads a stored invitation and its template, and merges the invitation commits.\n *\n * @param {State} state - State that stores the invitation and the template.\n * @param {XOInvitationIdentifier} invitationIdentifier - Identifier of the stored invitation.\n * @returns {Promise<{ storedInvitation: StoredInvitation, template: XOTemplate, mergedInvitation: MergedInvitation }>} - The stored\n * invitation, its template, and the merged invitation built from its commits.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not stored.\n * @throws {@link CommitIdentifierDuplicatedError} - When a commit identifier appears more than once.\n * @throws {@link ParentCommitNotFoundError} - When a commit names a previous commit that is not in the invitation.\n * @throws {@link CommitChainOrderInvalidError} - When a commit does not name the commit stored before it.\n * @throws {@link InvitationVariableIdentifierInvalidError} - When any variable identifier contains a dot.\n * @throws {@link TransactionVersionDuplicatedError} - When more than one commit sets the transaction version.\n * @throws {@link TransactionLocktimeDuplicatedError} - When more than one commit sets the transaction locktime.\n * @throws {@link MergesWithCommitNotFoundError} - When a mergesWith reference names a missing commit.\n * @throws {@link MergesWithCommitNotEarlierError} - When a mergesWith reference names the same commit or a later one.\n * @throws {@link CommitItemNotFoundError} - When a mergesWith reference points at an item that does not exist.\n * @throws {@link MergedOutputLockingBytecodeMissingError} - When neither the template output nor its commit provides locking bytecode.\n * @throws {@link TransactionIndexDuplicatedError} - When two merged inputs or two merged outputs claim the same transactionIndex.\n */\nexport const getMergedInvitationOrThrow = async (\n state: State,\n invitationIdentifier: XOInvitationIdentifier,\n): Promise<{ storedInvitation: StoredInvitation; template: XOTemplate; mergedInvitation: MergedInvitation }> => {\n const storedInvitation = await state.getInvitationOrThrow(invitationIdentifier);\n\n // The template defines the defaults the merge fills in for values the commits left unset.\n const storedTemplate = await state.getTemplateOrThrow(storedInvitation.invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n const mergedInvitation = mergeInvitationCommits(storedInvitation.invitation, template);\n\n return { storedInvitation, template, mergedInvitation };\n};\n","import { binToHex, encodeTransaction, generateTransaction, hashTransaction } from '@bitauth/libauth';\nimport type { State } from '@xo-cash/state';\nimport { TransactionHash } from '@xo-cash/primitives';\nimport type { XOInvitationIdentifier, XOInvitationOutput, XOTemplate, XOTemplateActionIdentifier } from '@xo-cash/types';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport { DEFAULT_FEE_SATOSHIS_PER_INPUT, DEFAULT_FEE_SATOSHIS_PER_OUTPUT } from '../../defaults.ts';\nimport { TemplateActionTransactionNotFoundError, TransactionGenerationFailedError } from '../../errors/index.ts';\nimport { getTemplateActionOrThrow } from '../../template.ts';\nimport { formatLibauthFailureReason } from '../../compilation/libauth-utils.ts';\nimport { getMergedInvitationOrThrow } from '../helpers/merged-invitation.ts';\nimport type { BuiltInvitationTransaction } from '../interfaces.ts';\nimport { completeMergedInput, completeMergedOutput } from '../merge/complete.ts';\nimport type { MergedInvitation } from '../merge/types.ts';\n\n/**\n * Estimates miner fee from input and output count\n *\n * @param {number} inputCount - Number of transaction inputs.\n * @param {number} outputCount - Number of transaction outputs.\n * @returns {number} - Fee in satoshis.\n */\nexport const estimateTransactionFeeFromInputOutputCounts = (inputCount: number, outputCount: number): number => {\n return inputCount * DEFAULT_FEE_SATOSHIS_PER_INPUT + outputCount * DEFAULT_FEE_SATOSHIS_PER_OUTPUT;\n};\n\n/**\n * Encodes the merged invitation as a libauth transaction for size and hash measurement.\n *\n * @param {MergedInvitation} mergedCommit - Merged commit whose inputs and outputs are encoded.\n * @param {XOTemplate} template - Template that defines the action.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action the transaction is built for, used to complete outputs without locking bytecode.\n * @returns {Uint8Array} - Serialized transaction bytes.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action has no transaction definition.\n * @throws {@link TransactionGenerationFailedError} - When libauth cannot build the transaction.\n */\nexport const encodeMergedInvitationTransaction = (\n mergedCommit: MergedInvitation,\n template: XOTemplate,\n actionIdentifier: XOTemplateActionIdentifier,\n): Uint8Array => {\n const action = getTemplateActionOrThrow(template, actionIdentifier);\n\n if (action.transaction === undefined) {\n throw new TemplateActionTransactionNotFoundError(generateTemplateIdentifier(template), actionIdentifier);\n }\n\n const transactionInputs = mergedCommit.inputs.map((input) => completeMergedInput(input));\n const transactionOutputs: XOInvitationOutput[] = [];\n\n // The position in the merged output list is kept so errors name the same output the merge reported.\n for (const [ outputIndex, output ] of mergedCommit.outputs.entries()) {\n const isZeroValueOutput = output.valueSatoshis !== undefined && output.valueSatoshis <= 0n;\n\n // An output carrying no satoshis is left out of the transaction.\n if (isZeroValueOutput) {\n continue;\n }\n\n if (output.lockingBytecode !== undefined) {\n transactionOutputs.push(output);\n continue;\n }\n\n transactionOutputs.push(completeMergedOutput(output, outputIndex, mergedCommit.variables, template, actionIdentifier));\n }\n\n const resultTransaction = generateTransaction({\n version: mergedCommit.transactionVersion,\n locktime: mergedCommit.transactionLocktime,\n // @ts-expect-error merged inputs carry fields beyond generateTransaction's minimal input type.\n inputs: transactionInputs,\n // @ts-expect-error invitation outputs may omit fields required by generateTransaction's strict output type.\n outputs: transactionOutputs,\n });\n\n if (resultTransaction.success === false) {\n throw new TransactionGenerationFailedError(\n generateTemplateIdentifier(template),\n actionIdentifier,\n formatLibauthFailureReason(resultTransaction),\n );\n }\n\n return encodeTransaction(resultTransaction.transaction);\n};\n\n/**\n * Estimates the miner fee of an invitation transaction from the input and output counts of its merged commits.\n *\n * @param {State} state - State that stores the invitation and its template.\n * @param {XOInvitationIdentifier} invitationIdentifier - Identifier of the stored invitation.\n * @returns {Promise<number>} - Fee in satoshis.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not stored.\n */\nexport const estimateTransactionFee = async (state: State, invitationIdentifier: XOInvitationIdentifier): Promise<number> => {\n // Load the invitation and its template, and merge the invitation commits.\n const { mergedInvitation } = await getMergedInvitationOrThrow(state, invitationIdentifier);\n\n // Estimate the transaction fee from the input and output counts.\n return estimateTransactionFeeFromInputOutputCounts(mergedInvitation.inputs.length, mergedInvitation.outputs.length);\n};\n\n/**\n * Encodes the merged invitation commit as a transaction and returns hex plus size metadata.\n *\n * @param {MergedInvitation} mergedCommit - Merged inputs and outputs from the invitation.\n * @param {XOTemplate} template - Template that defines the action transaction shape.\n * @param {XOTemplateActionIdentifier} actionIdentifier - Action used to validate that a transaction is defined.\n * @returns {BuiltInvitationTransaction} - Serialized transaction hex, byte length, and hash.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action has no transaction definition.\n * @throws {@link TransactionGenerationFailedError} - When libauth cannot build the transaction.\n */\nexport const buildInvitationTransactionFromMergedCommit = (\n mergedCommit: MergedInvitation,\n template: XOTemplate,\n actionIdentifier: XOTemplateActionIdentifier,\n): BuiltInvitationTransaction => {\n const encodedTransaction = encodeMergedInvitationTransaction(mergedCommit, template, actionIdentifier);\n const serializedTransaction = binToHex(encodedTransaction);\n const transactionHash = new TransactionHash(hashTransaction(encodedTransaction)).toHex();\n\n const estimatedFeeSatoshis = estimateTransactionFeeFromInputOutputCounts(mergedCommit.inputs.length, mergedCommit.outputs.length);\n\n return {\n serializedTransaction,\n transactionByteLength: encodedTransaction.byteLength,\n serializedTransactionCharacterCount: serializedTransaction.length,\n transactionHash,\n feeEstimateInputCount: mergedCommit.inputs.length,\n feeEstimateOutputCount: mergedCommit.outputs.length,\n estimatedFeeSatoshis,\n };\n};\n","import { broadcastTransaction, monitorTransaction } from '@electrum-cash/application';\nimport { verifyInvitationTransactionBroadcastedResultSignature } from '@xo-cash/crypto';\nimport type {\n XOInvitation,\n XOInvitationCommitIdentifier,\n XOInvitationEntityIdentifier,\n XOInvitationIdentifier,\n XOInvitationTransactionHash,\n XOTemplate,\n} from '@xo-cash/types';\nimport {\n RootCommitNotFoundError,\n TransactionBroadcastFailedError,\n TransactionResultAlreadyExistsError,\n TransactionResultNotFoundError,\n} from '../../errors/index.ts';\nimport { getTemplateActionTransactionIdentifierOrThrow } from '../../template.ts';\nimport { getMergedInvitationOrThrow } from '../helpers/merged-invitation.ts';\nimport { buildInvitationTransactionFromMergedCommit } from '../generation/transaction.ts';\nimport { findRootCommitIdentifierInInvitation } from '../helpers/commits.ts';\nimport { isInvitationTransactionCreatedResultComplete } from '../helpers/transaction-result.ts';\nimport type { AccountContext, ExecuteActionParameters, ExecuteActionResult } from '../interfaces.ts';\nimport { InvitationBuilder } from './builder.ts';\n\n/**\n * Entity identifier and root commit used to sign an invitation result.\n */\ntype EntitySigningContext = {\n entityIdentifier: XOInvitationEntityIdentifier;\n rootCommitIdentifier: XOInvitationCommitIdentifier;\n};\n\n/**\n * Resolves the local entity identifier and HD root commit used for invitation result signing.\n *\n * @param {XOInvitation} invitation - Invitation the result is signed for.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - This account's entity in the invitation.\n * @returns {EntitySigningContext} - Entity identifier and root commit identifier for this participation.\n * @throws {@link RootCommitNotFoundError} - When the entity root commit cannot be resolved.\n */\nconst resolveEntitySigningContext = (invitation: XOInvitation, entityIdentifier: XOInvitationEntityIdentifier): EntitySigningContext => {\n const rootCommitIdentifier = findRootCommitIdentifierInInvitation(invitation, entityIdentifier);\n\n if (rootCommitIdentifier === undefined) {\n throw new RootCommitNotFoundError(invitation.invitationIdentifier, entityIdentifier);\n }\n\n return {\n entityIdentifier,\n rootCommitIdentifier,\n };\n};\n\n/**\n * Records a signed transaction created result on the invitation and persists it to storage.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Invitation the transaction was built from.\n * @param {XOTemplate} template - Template of the invitation, which names the action transaction.\n * @param {XOInvitationTransactionHash} transactionHash - Hash of the built transaction.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - This account's entity in the invitation, which signs the result.\n * @returns {Promise<XOInvitation>} - The invitation after the result is persisted.\n * @throws {@link RootCommitNotFoundError} - When the entity root commit cannot be resolved.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action has no transaction definition.\n * @throws {@link TransactionResultAlreadyExistsError} - When a created result already exists for the action transaction.\n */\nconst recordInvitationTransactionCreatedResult = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n transactionHash: XOInvitationTransactionHash,\n entityIdentifier: XOInvitationEntityIdentifier,\n): Promise<XOInvitation> => {\n const transactionIdentifier = getTemplateActionTransactionIdentifierOrThrow(template, invitation.actionIdentifier);\n const signingContext = resolveEntitySigningContext(invitation, entityIdentifier);\n\n // The result is signed at the moment it is recorded, which is when the transaction was built.\n const signedCreatedResult = context.crypto.signInvitationTransactionCreatedResult({\n invitationIdentifier: invitation.invitationIdentifier,\n templateIdentifier: invitation.templateIdentifier,\n rootCommitIdentifier: signingContext.rootCommitIdentifier,\n transactionHash,\n createdAtTimestamp: Date.now(),\n });\n const invitationBuilder = InvitationBuilder.fromInvitation(invitation, context.network);\n const existingTransactionResult = invitationBuilder.getResult()?.transactions?.[transactionIdentifier];\n\n if (existingTransactionResult !== undefined) {\n const isExistingCreatedResultComplete = isInvitationTransactionCreatedResultComplete(\n invitation.invitationIdentifier,\n existingTransactionResult,\n );\n\n if (isExistingCreatedResultComplete === true) {\n if (existingTransactionResult.transactionHash === transactionHash) {\n return invitation;\n }\n\n throw new TransactionResultAlreadyExistsError(invitation.invitationIdentifier, transactionIdentifier);\n }\n\n invitationBuilder.removeTransactionResult(transactionIdentifier);\n }\n\n invitationBuilder.addTransactionCreatedResult(transactionIdentifier, signedCreatedResult);\n\n const updatedInvitation = invitationBuilder.build();\n\n // Storage replaces only the shared invitation so the created result is written and this account's fields are kept.\n await context.state.updateInvitation(invitation.invitationIdentifier, updatedInvitation);\n\n return updatedInvitation;\n};\n\n/**\n * Records signed broadcast metadata on an existing invitation transaction result.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitation} invitation - Invitation that already carries the created result.\n * @param {XOTemplate} template - Template of the invitation, which names the action transaction.\n * @param {XOInvitationEntityIdentifier} entityIdentifier - This account's entity in the invitation, which signs the result.\n * @returns {Promise<XOInvitation>} - The invitation after the broadcast result is persisted.\n * @throws {@link RootCommitNotFoundError} - When the entity root commit cannot be resolved.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action has no transaction definition.\n * @throws {@link TransactionResultNotFoundError} - When no created transaction result exists yet.\n */\nconst recordInvitationTransactionBroadcastedResult = async (\n context: Required<AccountContext>,\n invitation: XOInvitation,\n template: XOTemplate,\n entityIdentifier: XOInvitationEntityIdentifier,\n): Promise<XOInvitation> => {\n const transactionIdentifier = getTemplateActionTransactionIdentifierOrThrow(template, invitation.actionIdentifier);\n const signingContext = resolveEntitySigningContext(invitation, entityIdentifier);\n const invitationBuilder = InvitationBuilder.fromInvitation(invitation, context.network);\n const existingTransactionResult = invitationBuilder.getResult()?.transactions?.[transactionIdentifier];\n\n if (existingTransactionResult === undefined) {\n throw new TransactionResultNotFoundError(invitation.invitationIdentifier, transactionIdentifier);\n }\n\n // Broadcast fields are written together through primitives, so key presence is enough.\n if (\n 'broadcastedByEntityIdentifier' in existingTransactionResult\n && 'broadcastedBySignature' in existingTransactionResult\n && 'broadcastedAtTimestamp' in existingTransactionResult\n ) {\n try {\n const isBroadcastResultComplete = verifyInvitationTransactionBroadcastedResultSignature({\n invitationIdentifier: invitation.invitationIdentifier,\n transactionResult: existingTransactionResult,\n });\n\n if (isBroadcastResultComplete === true) {\n return invitation;\n }\n } catch (verificationError: unknown) {\n if (verificationError instanceof Error === false) {\n throw verificationError;\n }\n }\n }\n\n // The broadcast is signed at the moment it is recorded, which is right after the network accepted the transaction.\n const signedBroadcastResult = context.crypto.signInvitationTransactionBroadcastedResult({\n invitationIdentifier: invitation.invitationIdentifier,\n templateIdentifier: invitation.templateIdentifier,\n rootCommitIdentifier: signingContext.rootCommitIdentifier,\n transactionResult: existingTransactionResult,\n broadcastedAtTimestamp: Date.now(),\n });\n\n invitationBuilder.addTransactionBroadcastedResult(transactionIdentifier, signedBroadcastResult);\n\n const updatedInvitation = invitationBuilder.build();\n\n // Storage replaces only the shared invitation so the broadcast result is written and this account's fields are kept.\n await context.state.updateInvitation(invitation.invitationIdentifier, updatedInvitation);\n\n return updatedInvitation;\n};\n\n/**\n * Executes an action for a given invitation.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation whose action to execute.\n * @param {ExecuteActionParameters} params - Parameters for executing the action.\n * @returns {Promise<ExecuteActionResult>} - Encoded transaction metadata and the persisted invitation.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateNotFoundInStoreError} - If the invitation's template is not found in the store.\n * @throws {@link TransactionResultAlreadyExistsError} - If a different transaction was already recorded for the action.\n * @throws {@link TransactionBroadcastFailedError} - If the network rejects the transaction.\n * @throws {@link TransactionResultNotFoundError} - If the created result is missing when the broadcast is recorded.\n */\nexport const executeAction = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n params: ExecuteActionParameters,\n): Promise<ExecuteActionResult> => {\n // Load the invitation and its template, and merge the invitation commits. Its entity identifier is this account's, which signs the results.\n const { storedInvitation, template, mergedInvitation: mergedCommit } = await getMergedInvitationOrThrow(context.state, invitationIdentifier);\n const { entityIdentifier } = storedInvitation;\n let { invitation } = storedInvitation;\n\n // Build the encoded transaction from the merged commit.\n const builtTransaction = buildInvitationTransactionFromMergedCommit(mergedCommit, template, invitation.actionIdentifier);\n\n // Record the transaction created result on the invitation that was just loaded and merged.\n invitation = await recordInvitationTransactionCreatedResult(context, invitation, template, builtTransaction.transactionHash, entityIdentifier);\n\n // If the broadcast transaction flag is true then broadcast the transaction.\n if (params.broadcastTransaction === true) {\n try {\n // Publish the encoded transaction so connected Electrum servers can relay it.\n await broadcastTransaction(builtTransaction.serializedTransaction);\n } catch (broadcastIssue: unknown) {\n throw new TransactionBroadcastFailedError(invitation.invitationIdentifier, builtTransaction.transactionHash, String(broadcastIssue), {\n cause: broadcastIssue,\n });\n }\n\n // Watch this transaction for mempool inclusion, confirmation, and double spend proofs.\n await monitorTransaction(builtTransaction.transactionHash);\n\n try {\n // The invitation that now carries the created result is the one the broadcast result is added to.\n invitation = await recordInvitationTransactionBroadcastedResult(context, invitation, template, entityIdentifier);\n } finally {\n await context.state.clearInvitationUnspentOutputReservations(invitationIdentifier);\n }\n }\n\n // Only the shared invitation changed, so this account's own fields are kept around it.\n return {\n builtTransaction,\n storedInvitation: { ...storedInvitation, invitation },\n };\n};\n","import type { State } from '@xo-cash/state';\nimport type { XOInvitation, XOInvitationIdentifier, XOTemplateRoleIdentifier } from '@xo-cash/types';\nimport { getTemplateActionOrThrow } from '../../template.ts';\nimport type { InvitationMissingRequirements, InvitationRequirementIdentifierLists } from '../interfaces.ts';\nimport { listAvailableRolesForInvitation, listMissingParticipants } from './roles.ts';\nimport { listInputsMissingSignatures } from './signatures.ts';\nimport { listRequirementsFromTemplate, listUnfilledRequirements } from './template.ts';\n\n/**\n * Lists roles that can still accept another participant on this invitation.\n *\n * @param {State} state - State that stores the template for this account.\n * @param {XOInvitation} invitation - Invitation whose action and filled slots are read.\n * @returns {Promise<XOTemplateRoleIdentifier[]>} - Roles that still have an open slot.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n */\nexport const listAvailableRoles = async (state: State, invitation: XOInvitation): Promise<XOTemplateRoleIdentifier[]> => {\n // Slot limits live on the template action, so the stored template is required before roles can be listed.\n const storedTemplate = await state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n const action = getTemplateActionOrThrow(template, invitation.actionIdentifier);\n\n return listAvailableRolesForInvitation(invitation, action);\n};\n\n/**\n * Lists the requirements the template action expects for this invitation.\n *\n * @param {State} state - State that stores the template for this account.\n * @param {XOInvitation} invitation - Invitation whose template and action identify the requirements.\n * @returns {Promise<InvitationRequirementIdentifierLists>} - Requirements declared by the template action.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n */\nexport const listRequirements = async (state: State, invitation: XOInvitation): Promise<InvitationRequirementIdentifierLists> => {\n // Expected variables, inputs, and outputs are declared on the template action.\n const storedTemplate = await state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n const action = getTemplateActionOrThrow(template, invitation.actionIdentifier);\n\n return listRequirementsFromTemplate(template, action);\n};\n\n/**\n * Lists template data that is still absent, inputs that are still unsigned, and roles that still need an entity to join.\n *\n * @param {State} state - State that stores the invitation and template for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Identifier of the stored invitation to inspect.\n * @returns {Promise<InvitationMissingRequirements>} - Template gaps and unsigned inputs.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not in the store.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n */\nexport const listMissingRequirements = async (state: State, invitationIdentifier: XOInvitationIdentifier): Promise<InvitationMissingRequirements> => {\n const { invitation } = await state.getInvitationOrThrow(invitationIdentifier);\n\n // Expected requirements are declared on the template action, then compared with commits already stored.\n const storedTemplate = await state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n const action = getTemplateActionOrThrow(template, invitation.actionIdentifier);\n const templateRequirements = listUnfilledRequirements(invitation, template, action);\n\n // An outpoint can already be committed while its unlocking bytecode is still absent.\n const inputsMissingSignatures = listInputsMissingSignatures(invitation, template);\n\n // A role the action requires may still be waiting for an entity to join with it.\n const participants = listMissingParticipants(invitation, action);\n\n return { templateRequirements, inputsMissingSignatures, participants };\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { State } from '@xo-cash/state';\nimport type { XOInvitationIdentifier } from '@xo-cash/types';\nimport { getMergedInvitationOrThrow } from './merged-invitation.ts';\n\n/**\n * Finds all the merged inputs that are reserved by this account.\n *\n * @param {State} state - State that stores the invitation, its template, and this account's unspent outputs.\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to find inputs for.\n * @returns {Promise<number[]>} - The indexes of the inputs that are reserved by this account.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not in the store.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n */\nexport const listOwnInputIndexes = async (state: State, invitationIdentifier: XOInvitationIdentifier): Promise<number[]> => {\n // Load the invitation and its template, and merge the invitation commits.\n const { storedInvitation, mergedInvitation } = await getMergedInvitationOrThrow(state, invitationIdentifier);\n const { invitation } = storedInvitation;\n\n const inputIndexes: number[] = [];\n\n for (const [ index, input ] of mergedInvitation.inputs.entries()) {\n if (input.outpointTransactionHash === undefined || input.outpointIndex === undefined) {\n continue;\n }\n\n const outpointTransactionHash = binToHex(input.outpointTransactionHash);\n const outpointIndex = input.outpointIndex;\n\n const unspentOutput = await state.getUnspentOutputData(outpointTransactionHash, outpointIndex);\n\n // An output this account tracks that no other invitation reserved is its own too.\n const isReservableHere = unspentOutput?.reservedBy === invitation.invitationIdentifier || unspentOutput?.reservedBy === undefined;\n const isOwnInput = unspentOutput !== undefined && isReservableHere;\n\n if (isOwnInput) {\n inputIndexes.push(index);\n }\n }\n\n return inputIndexes;\n};\n","import { binToHex } from '@bitauth/libauth';\nimport type { StoredInvitation } from '@xo-cash/state';\nimport type { XOInvitation, XOInvitationIdentifier, XOInvitationMergesWithReference } from '@xo-cash/types';\nimport { InputOwnResolutionsNotFoundError, MergedInputCommitNotFoundError } from '../../errors/index.ts';\nimport { generateInputUnlockingBytecode, listUnlockingScriptResolutions } from '../../compilation/generate-unlocking-bytecode.ts';\nimport { getMergedInvitationOrThrow } from '../helpers/merged-invitation.ts';\nimport type { AccountContext, InvitationResolutionRequirements } from '../interfaces.ts';\nimport { resolveMergedItemMergeTarget } from '../merge/merge-targets.ts';\nimport type { MergedInvitation } from '../merge/types.ts';\nimport { applyInvitationAppend } from '../participation/apply-append.ts';\n\n/**\n * Resolves the mergesWith target for one merged input.\n *\n * The index is the position in the merged input list. The stored invitation supplies the commit that last wrote that input.\n *\n * @param {XOInvitation} invitation - Stored invitation whose commits contain the input leaf.\n * @param {MergedInvitation} mergedInvitation - Merged inputs produced from those commits.\n * @param {number} inputIndex - Position of the input in the merged input list.\n * @returns {XOInvitationMergesWithReference} - Commit and item index the unlocking commit extends.\n * @throws {@link MergedInputCommitNotFoundError} - When that merged input has no leaf to extend.\n */\nconst resolveUnlockingInputMergeTarget = (\n invitation: XOInvitation,\n mergedInvitation: MergedInvitation,\n inputIndex: number,\n): XOInvitationMergesWithReference => {\n // The merged index identifies the leaf. The stored commits supply the item index inside that leaf.\n const mergeTarget = resolveMergedItemMergeTarget(invitation, mergedInvitation, 'input', inputIndex);\n\n if (mergeTarget === undefined) {\n throw new MergedInputCommitNotFoundError(invitation.invitationIdentifier, inputIndex);\n }\n\n return mergeTarget;\n};\n\n/**\n * Reserves the output a merged input spends for the invitation, when this account tracks it and no invitation reserved it yet.\n *\n * A participant signing an output it shares with others did not add the input, so the output is reserved here.\n *\n * @param {Required<AccountContext>} context - State for this account.\n * @param {MergedInvitation} mergedInvitation - Merged inputs of the invitation.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output is reserved for.\n * @param {number} inputIndex - Index of the merged input.\n * @returns {Promise<void>} - Resolves once the output is reserved, or straight away when there is nothing to reserve.\n */\nconst reserveTrackedInputOutput = async (\n context: Required<AccountContext>,\n mergedInvitation: MergedInvitation,\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n): Promise<void> => {\n const { outpointTransactionHash, outpointIndex } = mergedInvitation.inputs[inputIndex] ?? {};\n\n // An input without an outpoint spends nothing this account could reserve.\n if (outpointTransactionHash === undefined || outpointIndex === undefined) {\n return;\n }\n\n const unspentOutput = await context.state.getUnspentOutputData(binToHex(outpointTransactionHash), outpointIndex);\n\n if (unspentOutput !== undefined && unspentOutput.reservedBy === undefined) {\n await context.state.executeBulkUnspentOutputReservation({\n outpoints: [{ outpointTransactionHash: binToHex(outpointTransactionHash), outpointIndex }],\n shouldBeReserved: true,\n invitationIdentifier,\n });\n }\n};\n\n/**\n * Signs the provided invitation once all the resources are reserved and the invitation is complete.\n * This method is used to sign own inputs and provide unlocking data for them, this appends the\n * invitation and adds new commit with unlocking data.\n *\n * An unlocking script that needs values other entities hold, such as their signatures, is only signed once the invitation\n * holds them. Use {@link listInputResolutions} to see what the input still needs, and\n * {@link appendOwnInputResolutions} to add this account's part.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to sign.\n * The invitation must already exist in the store.\n * @param {number} inputIndex - Index of the merged input to sign.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the unlocking commit is appended.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputCommitNotFoundError} - When the compiled input has no merged leaf to extend.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link UnlockingScriptResolutionsMissingError} - When the unlocking script needs values the invitation does not hold yet.\n * @throws {@link UnlockingCompilationContextMissingError} - When the unlocking compilation carries no context to verify against.\n * @throws {@link UnlockingBytecodeVerificationFailedError} - When the unlocking bytecode built with other entities' values fails.\n */\nexport const signInvitation = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n): Promise<StoredInvitation> => {\n // Load the invitation and its template, and merge the invitation commits.\n const { storedInvitation, template, mergedInvitation } = await getMergedInvitationOrThrow(context.state, invitationIdentifier);\n const { invitation } = storedInvitation;\n\n await reserveTrackedInputOutput(context, mergedInvitation, invitationIdentifier, inputIndex);\n\n // The compiled input index is already the merged input position, so the append extends that leaf.\n const mergeTarget = resolveUnlockingInputMergeTarget(invitation, mergedInvitation, inputIndex);\n\n // Generate the unlocking bytecode for the input.\n const compiledInput = await generateInputUnlockingBytecode(context, invitation, template, inputIndex);\n\n // Append the unlocking bytecode onto the merged leaf for this input.\n return applyInvitationAppend(context, storedInvitation, {\n inputs: [\n {\n mergesWith: mergeTarget,\n unlockingBytecode: compiledInput.unlockingBytecode,\n },\n ],\n });\n};\n\n/**\n * Lists the key operations an invitation input's unlocking script needs from participants, without signing or adding anything.\n *\n * Each operation is reported as provided when the invitation or the input holds it, as this account's own when only this\n * account's keys resolve it, such as its signature, or as missing when another participant holds the key.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the input belongs to.\n * @param {number} inputIndex - Index of the merged input.\n * @returns {Promise<InvitationResolutionRequirements>} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the spent output has no stored script hash.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When the unlocking script fails to compile for a reason other than a missing identifier.\n */\nexport const listInputResolutions = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n): Promise<InvitationResolutionRequirements> => {\n const { invitation } = await context.state.getInvitationOrThrow(invitationIdentifier);\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n return listUnlockingScriptResolutions(context, invitation, template, inputIndex);\n};\n\n/**\n * Adds the key operations this account resolved for an invitation input, such as its signature, to that input, so the\n * participant holding the remaining keys can complete the unlocking bytecode.\n *\n * Only values the invitation and the input do not hold yet are added, in one commit that extends the input. The output the\n * input spends is reserved for the invitation, the same as when the input is signed. Use {@link listInputResolutions}\n * first to check that there is something to add.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the input belongs to.\n * @param {number} inputIndex - Index of the merged input.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit with the values.\n * @throws {@link InputOwnResolutionsNotFoundError} - If this account resolved nothing the invitation does not already hold.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputCommitNotFoundError} - When the input has no merged leaf to extend.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When the unlocking script fails to compile for a reason other than a missing identifier.\n */\nexport const appendOwnInputResolutions = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n inputIndex: number,\n): Promise<StoredInvitation> => {\n // Load the invitation and its template, and merge the invitation commits.\n const { storedInvitation, template, mergedInvitation } = await getMergedInvitationOrThrow(context.state, invitationIdentifier);\n const { invitation } = storedInvitation;\n\n const { ownResolutions } = await listUnlockingScriptResolutions(context, invitation, template, inputIndex);\n\n // Nothing is committed when the invitation already holds every value this account can resolve for the input.\n if (ownResolutions.length === 0) {\n throw new InputOwnResolutionsNotFoundError(invitationIdentifier, inputIndex);\n }\n\n await reserveTrackedInputOutput(context, mergedInvitation, invitationIdentifier, inputIndex);\n\n // The values extend the merged leaf for this input, so the next entity can complete the unlocking bytecode.\n return applyInvitationAppend(context, storedInvitation, {\n inputs: [\n {\n mergesWith: resolveUnlockingInputMergeTarget(invitation, mergedInvitation, inputIndex),\n resolutions: ownResolutions,\n },\n ],\n });\n};\n","import type { State, StoredDefaultPolicies } from '@xo-cash/state';\nimport { WalletSettingsKeys } from '@xo-cash/state';\nimport { TemplateIdentifier } from '@xo-cash/primitives';\nimport type { XOTemplateIdentifier, XOTemplateLockingScriptIntent, XOTemplateOutputIntent } from '@xo-cash/types';\nimport { generateTemplateIdentifier } from '@xo-cash/utils';\nimport { DefaultPolicyNotSetError, TemplateDefaultPolicyMissingError } from '../errors/index.ts';\nimport type { DefaultPolicyTemplate, WalletDefaultPolicies } from '../interfaces.ts';\n\n/**\n * The template defaults intent behind a stored wallet default policy.\n */\nexport type ResolvedDefaultPolicyIntent = {\n\n /**\n * Template the stored policy names.\n */\n policyTemplateIdentifier: XOTemplateIdentifier;\n\n /**\n * Defaults intent from that template for the policy kind.\n */\n intent: XOTemplateOutputIntent | XOTemplateLockingScriptIntent;\n};\n\n/**\n * Sets the wallet default policies used for change, receive, and address generation.\n *\n * Each policy is set independently. A policy omitted from `policiesToSet` keeps its stored value,\n * so setting the change policy never clears the receive or address policy.\n * Resolution order is manual override, then template defaults, then these default policies.\n *\n * @param {State} state - State that stores the templates and wallet settings for this account.\n * @param {WalletDefaultPolicies} policiesToSet - Policies to set, each naming a template that defines that policy in its defaults.\n * @returns {Promise<void>} - Resolves when the provided policies have been stored.\n * @throws {@link TemplateNotFoundInStoreError} - When a policy names a template that is not stored.\n * @throws {@link TemplateDefaultPolicyMissingError} - When a policy names a template whose defaults do not define that policy.\n */\nexport const setDefaultPolicies = async (state: State, policiesToSet: WalletDefaultPolicies): Promise<void> => {\n const policies: Array<keyof WalletDefaultPolicies> = [ 'change', 'receive', 'address' ];\n\n // Collect validated policies first so an invalid entry fails before anything is written.\n const validatedPolicies: StoredDefaultPolicies = {};\n\n for (const policy of policies) {\n const policyToSet = policiesToSet[policy];\n\n // Continue if the policy is not set using the parameters\n if (policyToSet === undefined) {\n continue;\n }\n\n // Read and check the template identifier.\n const templateIdentifier = new TemplateIdentifier(policyToSet.templateIdentifier).toHex();\n\n // Get the template from the state.\n const storedTemplate = await state.getTemplateOrThrow(templateIdentifier);\n const template = storedTemplate.template;\n\n // The wallet policy only points at a template, so that template must define how this policy generates its output.\n if (template.defaults?.[policy] === undefined) {\n throw new TemplateDefaultPolicyMissingError(templateIdentifier, policy);\n }\n\n validatedPolicies[policy] = { templateIdentifier };\n }\n\n // Fetch wallet settings\n const walletSettings = await state.getWalletSettings();\n\n // Wallet settings merge only at the top level, so the nested policies are merged here before writing.\n return state.updateWalletSettings({\n defaultPolicies: {\n ...walletSettings.defaultPolicies,\n ...validatedPolicies,\n },\n });\n};\n\n/**\n * Removes wallet default policies so change, receive, or address generation no longer uses them.\n *\n * Each policy is removed independently. A policy not listed in `policiesToRemove` keeps its stored value.\n * Removing a policy that is not stored changes nothing.\n *\n * @param {State} state - State that stores the wallet settings for this account.\n * @param {Array<keyof WalletDefaultPolicies>} policiesToRemove - Policies to remove, each one of change, receive, or address.\n * @returns {Promise<void>} - Resolves when the listed policies are no longer stored.\n */\nexport const unsetDefaultPolicies = async (state: State, policiesToRemove: Array<keyof WalletDefaultPolicies>): Promise<void> => {\n // Fetch wallet settings so the policies that stay can be written back.\n const walletSettings = await state.getWalletSettings();\n\n // A wallet that never set a policy has nothing to remove.\n if (walletSettings.defaultPolicies === undefined) {\n return;\n }\n\n const policies: Array<keyof WalletDefaultPolicies> = [ 'change', 'receive', 'address' ];\n\n // Copy every stored policy except the ones being removed.\n const remainingPolicies: StoredDefaultPolicies = {};\n\n for (const policy of policies) {\n const storedPolicy = walletSettings.defaultPolicies[policy];\n const isPolicyKept = storedPolicy !== undefined && policiesToRemove.includes(policy) === false;\n\n if (isPolicyKept) {\n remainingPolicies[policy] = storedPolicy;\n }\n }\n\n // Remove the whole field when no policy remains, so the settings read the same as a wallet that never set one.\n if (Object.keys(remainingPolicies).length === 0) {\n return state.unsetWalletSettings([ WalletSettingsKeys.DEFAULT_POLICIES ]);\n }\n\n // Wallet settings merge only at the top level, so writing the field replaces the stored policies.\n return state.updateWalletSettings({ defaultPolicies: remainingPolicies });\n};\n\n/**\n * Returns the wallet default policies used for change, receive, and address generation.\n *\n * Each policy is present only when it has been set with {@link setDefaultPolicies}.\n *\n * @param {State} state - State that stores the wallet settings for this account.\n * @returns {Promise<WalletDefaultPolicies>} - Stored default policies, or an empty object when none are stored.\n */\nexport const getDefaultPolicies = async (state: State): Promise<WalletDefaultPolicies> => {\n const walletSettings = await state.getWalletSettings();\n\n // A wallet that never set a policy has no stored policies.\n if (walletSettings.defaultPolicies === undefined) {\n return {};\n }\n\n return walletSettings.defaultPolicies;\n};\n\n/**\n * Lists the stored templates that can provide the given wallet default policy.\n *\n * @param {State} state - State that stores the templates for this account.\n * @param {keyof WalletDefaultPolicies} policy - Default policy being chosen, one of change, receive, or address.\n * @returns {Promise<DefaultPolicyTemplate[]>} - Matching templates with their storage identifiers.\n */\nexport const listTemplatesForDefaultPolicy = async (state: State, policy: keyof WalletDefaultPolicies): Promise<DefaultPolicyTemplate[]> => {\n // List all templates, internally listTemplates excludes archived templates by default.\n const storedTemplates = await state.listTemplates();\n\n // List of templates that match the policy.\n const matchingTemplates: DefaultPolicyTemplate[] = [];\n\n // Iterate over all templates and check if they match the policy.\n for (const storedTemplate of storedTemplates) {\n const { template } = storedTemplate;\n\n // If the template does not define the policy, continue.\n if (template.defaults?.[policy] === undefined) {\n continue;\n }\n\n matchingTemplates.push({\n templateIdentifier: generateTemplateIdentifier(template),\n template,\n });\n }\n\n return matchingTemplates;\n};\n\n/**\n * Gets the template defaults intent behind a stored wallet default policy.\n *\n * @param {State} state - State that stores the templates and wallet settings for this account.\n * @param {keyof WalletDefaultPolicies} policyKind - Default policy to resolve.\n * @returns {Promise<ResolvedDefaultPolicyIntent>} - The policy template and its defaults intent.\n * @throws {@link TemplateNotFoundInStoreError} - When the policy template is not stored.\n * @throws {@link DefaultPolicyNotSetError} - When the policy is not set.\n * @throws {@link TemplateDefaultPolicyMissingError} - When its template does not define it.\n */\nexport const getDefaultPolicyIntentOrThrow = async (state: State, policyKind: keyof WalletDefaultPolicies): Promise<ResolvedDefaultPolicyIntent> => {\n const defaultPolicies = await getDefaultPolicies(state);\n const policy = defaultPolicies[policyKind];\n\n // Nothing can be created from a policy that was never set.\n if (policy === undefined) {\n throw new DefaultPolicyNotSetError(policyKind);\n }\n\n // Get the policy template from the state.\n const storedPolicyTemplate = await state.getTemplateOrThrow(policy.templateIdentifier);\n const policyTemplate = storedPolicyTemplate.template;\n\n const intent = policyTemplate.defaults?.[policyKind];\n\n // The policy only names a template, so the template defaults must say what to create.\n if (intent === undefined) {\n throw new TemplateDefaultPolicyMissingError(policy.templateIdentifier, policyKind);\n }\n\n return { policyTemplateIdentifier: policy.templateIdentifier, intent };\n};\n","import type { State } from '@xo-cash/state';\nimport { TemplateIdentifier } from '@xo-cash/primitives';\nimport type {\n XOInvitationIdentifier,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateIdentifier,\n XOTemplateLockingScriptIdentifier,\n XOTemplateLockingScriptIntent,\n XOTemplateOutputIdentifier,\n XOTemplateOutputIntent,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport type { WalletDefaultPolicies } from '../interfaces.ts';\nimport type { AccountContext } from '../invitation/interfaces.ts';\nimport { getDefaultPolicyIntentOrThrow } from '../state/default-policies.ts';\nimport { getTemplateLockingScriptIdentifierOrThrow } from '../template.ts';\nimport { generateAccountLockingBytecode } from './generate-locking-bytecode.ts';\nimport { listIntentRequiredVariableIdentifiers, resolveIntentCompilationVariables } from './intent-variables.ts';\n\n/**\n * The template and locking script a template defaults intent generates.\n */\ntype IntentTarget = {\n\n /**\n * Template that defines what the intent generates, which is the template holding the intent unless the intent names another.\n */\n targetTemplateIdentifier: XOTemplateIdentifier;\n\n /**\n * The template behind `targetTemplateIdentifier`.\n */\n targetTemplate: XOTemplate;\n\n /**\n * Locking script the intent generates, read from the intent output when the intent targets an output.\n */\n lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n};\n\n/**\n * What a locking bytecode is generated from when a template defaults intent names it.\n */\nexport type IntentLockingBytecodeGenerationParameters = {\n\n /**\n * Template whose defaults hold the intent.\n */\n templateIdentifier: XOTemplateIdentifier;\n\n /**\n * Defaults intent that names the output or locking script to generate.\n */\n intent: XOTemplateOutputIntent | XOTemplateLockingScriptIntent;\n\n /**\n * Values for the variables the intent requires.\n */\n variableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>;\n\n /**\n * Invitation the locking bytecode is built for, whose already generated keys are used instead of new ones.\n */\n invitationIdentifier?: XOInvitationIdentifier;\n};\n\n/**\n * Gets the template and locking script a template defaults intent generates.\n *\n * @param {State} state - State that stores the templates for this account.\n * @param {XOTemplateIdentifier} templateIdentifier - Template whose defaults hold the intent.\n * @param {XOTemplateOutputIntent | XOTemplateLockingScriptIntent} intent - Defaults intent that names an output or a locking script.\n * @returns {Promise<IntentTarget>} - The template the intent generates from and the locking script it generates.\n * @throws {@link TemplateNotFoundInStoreError} - When the intent target template is not stored.\n * @throws {@link TemplateOutputNotFoundError} - When an output intent names an output the target template does not define.\n * @throws {@link TemplateOutputLockingScriptNotFoundError} - When the output an intent names has no locking script reference.\n */\nconst getIntentTargetOrThrow = async (\n state: State,\n templateIdentifier: XOTemplateIdentifier,\n intent: XOTemplateOutputIntent | XOTemplateLockingScriptIntent,\n): Promise<IntentTarget> => {\n let targetTemplateIdentifier = templateIdentifier;\n\n // An intent may point at an output or locking script defined in another template.\n if (intent.templateIdentifier !== undefined) {\n targetTemplateIdentifier = new TemplateIdentifier(intent.templateIdentifier).toHex();\n }\n\n const storedTargetTemplate = await state.getTemplateOrThrow(targetTemplateIdentifier);\n const targetTemplate = storedTargetTemplate.template;\n\n let lockingScriptIdentifier: XOTemplateLockingScriptIdentifier;\n\n // The address policy names its locking script, while change and receive reach it through their output.\n if ('lockingScript' in intent) {\n lockingScriptIdentifier = intent.lockingScript;\n } else {\n lockingScriptIdentifier = getTemplateLockingScriptIdentifierOrThrow(targetTemplate, intent.output);\n }\n\n return { targetTemplateIdentifier, targetTemplate, lockingScriptIdentifier };\n};\n\n/**\n * Generates a locking bytecode from a template defaults intent.\n *\n * The intent names an output or a locking script, the role, and the secrets to generate. Every variable the intent\n * requires must be in `variableValues`, otherwise nothing is generated and no derivation index is used.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {IntentLockingBytecodeGenerationParameters} parameters - Template holding the intent, the intent, variable values, and the\n * invitation the locking bytecode is built for.\n * @returns {Promise<string>} - The generated locking bytecode as a hexadecimal string.\n * @throws {@link TemplateNotFoundInStoreError} - When the intent target template is not stored.\n * @throws {@link TemplateOutputNotFoundError} - When an output intent names an output the target template does not define.\n * @throws {@link TemplateOutputLockingScriptNotFoundError} - When the output an intent names has no locking script reference.\n * @throws {@link IntentVariablesMissingError} - When a required variable value is missing.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link InvitationNotFoundInStoreError} - When an invitation is given and it is not stored.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for that invitation is not in the secret store.\n */\nexport const generateLockingBytecodeFromIntent = async (\n context: Required<AccountContext>,\n parameters: IntentLockingBytecodeGenerationParameters,\n): Promise<string> => {\n const { templateIdentifier, intent, variableValues, invitationIdentifier } = parameters;\n const { targetTemplateIdentifier, targetTemplate, lockingScriptIdentifier } = await getIntentTargetOrThrow(\n context.state,\n templateIdentifier,\n intent,\n );\n\n // Missing required values fail here, before a derivation index is allocated for the intent secrets.\n const compilationVariables = resolveIntentCompilationVariables(targetTemplate, intent, lockingScriptIdentifier, variableValues);\n\n // The intent already names its locking script, directly for the address policy or through the output for change and receive.\n let intentOutputIdentifier: XOTemplateOutputIdentifier | undefined;\n\n // Change and receive intents name the output the script is for, which is stored with the script.\n if ('output' in intent) {\n intentOutputIdentifier = intent.output;\n }\n\n return generateAccountLockingBytecode(context, {\n templateIdentifier: targetTemplateIdentifier,\n lockingScriptIdentifier,\n roleIdentifier: intent.role,\n secretIdentifiers: intent.generate,\n compilationVariables,\n invitationIdentifier,\n outputIdentifier: intentOutputIdentifier,\n });\n};\n\n/**\n * Lists the variables a caller must provide to create a locking bytecode from a wallet default policy.\n *\n * These are the variables the policy template's defaults intent marks with a null value, plus any the generated\n * locking script needs that the template constants and intent presets do not supply.\n * Pass their values to {@link generateLockingBytecodeFromDefaultPolicy}.\n *\n * @param {State} state - State that stores the templates and wallet settings for this account.\n * @param {keyof WalletDefaultPolicies} policyKind - Default policy to inspect, one of change, receive, or address.\n * @returns {Promise<XOTemplateVariableIdentifier[]>} - Required variable identifiers, empty when nothing needs to be provided.\n * @throws {@link TemplateNotFoundInStoreError} - When the policy template or the intent target template is not stored.\n * @throws {@link DefaultPolicyNotSetError} - When the policy is not set.\n * @throws {@link TemplateDefaultPolicyMissingError} - When its template does not define it.\n */\nexport const listDefaultPolicyRequiredVariables = async (\n state: State,\n policyKind: keyof WalletDefaultPolicies,\n): Promise<XOTemplateVariableIdentifier[]> => {\n const { policyTemplateIdentifier, intent } = await getDefaultPolicyIntentOrThrow(state, policyKind);\n const { targetTemplate, lockingScriptIdentifier } = await getIntentTargetOrThrow(state, policyTemplateIdentifier, intent);\n\n return listIntentRequiredVariableIdentifiers(targetTemplate, intent, lockingScriptIdentifier);\n};\n\n/**\n * Generates a locking bytecode from a wallet default policy.\n *\n * The stored policy names a template, and that template's defaults intent says which output or locking script,\n * role, and secrets to use. Every variable from {@link listDefaultPolicyRequiredVariables} must be in\n * `variableValues`, otherwise nothing is generated and no derivation index is used.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {keyof WalletDefaultPolicies} policyKind - Default policy to create from, one of change, receive, or address.\n * @param {Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>} variableValues - Values for the variables the intent requires.\n * @param {XOInvitationIdentifier} [invitationIdentifier] - Invitation the locking bytecode is built for. Keys this account already\n * generated for it under the policy template are used instead of new ones.\n * @returns {Promise<string>} - The generated locking bytecode as a hexadecimal string.\n * @throws {@link TemplateNotFoundInStoreError} - When the policy template or the intent target template is not stored.\n * @throws {@link DefaultPolicyNotSetError} - When the policy is not set.\n * @throws {@link TemplateDefaultPolicyMissingError} - When its template does not define it.\n * @throws {@link IntentVariablesMissingError} - When a required variable value is missing.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link InvitationNotFoundInStoreError} - When an invitation is given and it is not stored.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for that invitation is not in the secret store.\n */\nexport const generateLockingBytecodeFromDefaultPolicy = async (\n context: Required<AccountContext>,\n policyKind: keyof WalletDefaultPolicies,\n variableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>,\n invitationIdentifier?: XOInvitationIdentifier,\n): Promise<string> => {\n const { policyTemplateIdentifier, intent } = await getDefaultPolicyIntentOrThrow(context.state, policyKind);\n\n // The policy template holds the intent, so the intent is generated the same way as any template defaults intent.\n return generateLockingBytecodeFromIntent(context, {\n templateIdentifier: policyTemplateIdentifier,\n intent,\n variableValues,\n invitationIdentifier,\n });\n};\n","import { binToHex, hexToBin } from '@bitauth/libauth';\nimport type { OutputToken } from '@xo-cash/types';\nimport { fetchDecodedTransactionOutput } from '../../network/electrum.ts';\nimport { MergedItemTokenIncompleteError, MergedItemValueSatoshisMissingError } from '../../errors/index.ts';\nimport type { MergedInvitation, MergeItemType } from '../merge/types.ts';\n\n/**\n * Input and output token.amount totals for one category.\n */\ntype TokenAmounts = {\n\n /**\n * Sum of token.amount on inputs of this category.\n */\n inputAmount: bigint;\n\n /**\n * Sum of token.amount on outputs of this category.\n */\n outputAmount: bigint;\n};\n\n/**\n * Leftover satoshi and fungible tokens.\n */\nexport type MergedInvitationChange = {\n\n /**\n * Leftover satoshis. This remainder is the fee until a change output takes part of it.\n */\n valueSatoshis: bigint;\n\n /**\n * Leftover fungible tokens.\n */\n tokens: OutputToken[];\n};\n\n/**\n * Derives the satoshis remainder.\n *\n * @param {MergedInvitation} mergedInvitation - Merged inputs and outputs. Each input has valueSatoshis or an outpoint.\n * @returns {Promise<bigint>} - Leftover satoshis.\n * @throws {@link MergedItemValueSatoshisMissingError} - When an input has neither valueSatoshis nor an outpoint,\n * or an output is missing valueSatoshis.\n */\nconst deriveMergedInvitationSatoshiChange = async (mergedInvitation: MergedInvitation): Promise<bigint> => {\n let satoshisInInputs = 0n;\n let satoshisInOutputs = 0n;\n\n // Loop through the inputs of the merged invitation\n for (const [ inputIndex, input ] of mergedInvitation.inputs.entries()) {\n if (input.valueSatoshis !== undefined) {\n satoshisInInputs += input.valueSatoshis;\n continue;\n }\n\n if (input.outpointTransactionHash === undefined || input.outpointIndex === undefined) {\n throw new MergedItemValueSatoshisMissingError('input', inputIndex, input.sourceCommitIdentifier);\n }\n\n // Fetch the transaction that produced the outpoint and add the valueSatoshis to the total\n const parentOutput = await fetchDecodedTransactionOutput(binToHex(input.outpointTransactionHash), input.outpointIndex);\n\n satoshisInInputs += parentOutput.valueSatoshis;\n }\n\n // Loop through the outputs of the merged invitation\n for (const [ outputIndex, output ] of mergedInvitation.outputs.entries()) {\n if (output.valueSatoshis === undefined) {\n throw new MergedItemValueSatoshisMissingError('output', outputIndex, output.sourceCommitIdentifier);\n }\n\n // Add the valueSatoshis to the total\n satoshisInOutputs += output.valueSatoshis;\n }\n\n return satoshisInInputs - satoshisInOutputs;\n};\n\n/**\n * Adds a token amount to the input or output total of its category.\n *\n * A category seen for the first time is added with input and output totals of zero before the amount is added.\n *\n * @param {Map<string, TokenAmounts>} tokenAmountsByCategory - Totals for each category, keyed by the category as hex.\n * @param {Uint8Array} category - Token category of the amount.\n * @param {MergeItemType} itemType - Whether the amount is on a merged input or a merged output.\n * @param {bigint} tokenAmount - Token amount to add.\n * @returns {void}\n */\nconst pushCategoryTokenAmount = (\n tokenAmountsByCategory: Map<string, TokenAmounts>,\n category: Uint8Array,\n itemType: MergeItemType,\n tokenAmount: bigint,\n): void => {\n // Categories are compared by value, so the map is keyed by the category as hex.\n const encodedCategory = binToHex(category);\n\n let categoryTokenAmounts = tokenAmountsByCategory.get(encodedCategory);\n\n // A category seen for the first time starts with zero input and output totals.\n if (categoryTokenAmounts === undefined) {\n categoryTokenAmounts = { inputAmount: 0n, outputAmount: 0n };\n tokenAmountsByCategory.set(encodedCategory, categoryTokenAmounts);\n }\n\n // The amount counts toward the total of the side the item is on.\n if (itemType === 'input') {\n categoryTokenAmounts.inputAmount += tokenAmount;\n } else {\n categoryTokenAmounts.outputAmount += tokenAmount;\n }\n};\n\n/**\n * Derives the leftover token amounts for each category.\n *\n * @param {MergedInvitation} mergedInvitation - Merged inputs and outputs.\n * @returns {Promise<OutputToken[]>} - One token per category whose input amount exceeds its output amount.\n * @throws {@link MergedItemTokenIncompleteError} - When a token prefix is missing its category or amount on an input or output.\n */\nconst deriveMergedInvitationTokenChange = async (mergedInvitation: MergedInvitation): Promise<OutputToken[]> => {\n // Create a map to store the token amounts for each category\n const tokenAmountsByCategory = new Map<string, TokenAmounts>();\n\n // Loop through the inputs of the merged invitation\n for (const [ inputIndex, input ] of mergedInvitation.inputs.entries()) {\n let tokenCategory: Uint8Array | undefined;\n let tokenAmount: bigint | undefined;\n\n // If the input has a token, get the category and amount\n if (input.token !== undefined) {\n // If the token is incomplete, throw an error\n if (input.token.category === undefined || input.token.amount === undefined) {\n throw new MergedItemTokenIncompleteError('input', inputIndex, input.sourceCommitIdentifier);\n }\n\n // Get the category and amount\n tokenCategory = input.token.category;\n tokenAmount = input.token.amount;\n } else if (input.outpointTransactionHash !== undefined && input.outpointIndex !== undefined) {\n // If the input has an outpoint, fetch the parent output and get the category and amount\n const parentOutput = await fetchDecodedTransactionOutput(binToHex(input.outpointTransactionHash), input.outpointIndex);\n\n // If the parent output has a token, get the category and amount\n if (parentOutput.token !== undefined) {\n tokenCategory = parentOutput.token.category;\n tokenAmount = parentOutput.token.amount;\n }\n }\n\n // If the input has no token, continue to the next input\n if (tokenCategory === undefined || tokenAmount === undefined) {\n continue;\n }\n\n // Add the amount to the category input total\n pushCategoryTokenAmount(tokenAmountsByCategory, tokenCategory, 'input', tokenAmount);\n }\n\n // Loop through the outputs of the merged invitation\n for (const [ outputIndex, output ] of mergedInvitation.outputs.entries()) {\n // If the output has no token, continue to the next output\n if (output.token === undefined) {\n continue;\n }\n\n // If the output token is incomplete, throw an error\n if (output.token.category === undefined || output.token.amount === undefined) {\n throw new MergedItemTokenIncompleteError('output', outputIndex, output.sourceCommitIdentifier);\n }\n\n // Add the amount to the category output total\n pushCategoryTokenAmount(tokenAmountsByCategory, output.token.category, 'output', output.token.amount);\n }\n\n // Create an array to store the tokens\n const tokens: OutputToken[] = [];\n\n // Loop through the token amounts by category\n for (const [ categoryHex, categoryTokenAmounts ] of tokenAmountsByCategory) {\n // Calculate the token change for the category\n const tokenChange = categoryTokenAmounts.inputAmount - categoryTokenAmounts.outputAmount;\n\n // Only a positive remainder is change\n if (tokenChange > 0n) {\n tokens.push({\n category: hexToBin(categoryHex),\n amount: tokenChange,\n });\n }\n }\n\n // Return the tokens change\n return tokens;\n};\n\n/**\n * Derives the satoshi remainder and the leftover fungible tokens.\n *\n * @param {MergedInvitation} mergedInvitation - Merged inputs and outputs. Inputs may carry values or only an outpoint.\n * @returns {Promise<MergedInvitationChange>} - Satoshi remainder and leftover fungible tokens.\n * @throws {@link MergedItemValueSatoshisMissingError} - When a value is missing and cannot be read from the parent output.\n * @throws {@link MergedItemTokenIncompleteError} - When a token prefix is missing its category or amount.\n */\nexport const deriveMergedInvitationChange = async (mergedInvitation: MergedInvitation): Promise<MergedInvitationChange> => {\n // Derive the satoshi change\n const valueSatoshis = await deriveMergedInvitationSatoshiChange(mergedInvitation);\n\n // Derive the token change\n const tokens = await deriveMergedInvitationTokenChange(mergedInvitation);\n\n // Return the satoshi and token change\n return {\n valueSatoshis,\n tokens,\n };\n};\n","import { hexToBin } from '@bitauth/libauth';\nimport type { StoredInvitation } from '@xo-cash/state';\nimport type {\n XOInvitation,\n XOInvitationIdentifier,\n XOInvitationOutput,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport { ChangeLockingBytecodeMissingError } from '../../errors/index.ts';\nimport { generateLockingBytecodeFromDefaultPolicy, generateLockingBytecodeFromIntent } from '../../compilation/intent-locking-bytecode.ts';\nimport { getDefaultPolicies } from '../../state/default-policies.ts';\nimport { getMergedInvitationOrThrow } from '../helpers/merged-invitation.ts';\nimport { deriveMergedInvitationChange } from './derive.ts';\nimport { estimateTransactionFee } from '../generation/transaction.ts';\nimport type { AccountContext } from '../interfaces.ts';\nimport { appendInvitation } from '../participation/append.ts';\n\n/**\n * What the locking bytecode of an invitation change output is chosen from.\n */\ntype ChangeLockingBytecodeParameters = {\n\n /**\n * Invitation the change output is built for.\n */\n invitation: XOInvitation;\n\n /**\n * Template of the invitation, whose defaults may hold a change policy.\n */\n template: XOTemplate;\n\n /**\n * Values the change intent requires.\n */\n changeVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>;\n\n /**\n * Locking bytecode to send the change to, as hex.\n */\n providedLockingBytecode?: string;\n};\n\n/**\n * Generates the locking bytecode of an invitation change output.\n *\n * The provided locking bytecode is used first, then the change policy in the invitation template, and then the wallet\n * default change policy. A locking bytecode built from a policy uses the keys this account already generated for the\n * invitation instead of new ones.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {ChangeLockingBytecodeParameters} parameters - Invitation, its template, the change variable values, and the provided locking bytecode.\n * @returns {Promise<string>} - The change locking bytecode as a hexadecimal string.\n * @throws {@link ChangeLockingBytecodeMissingError} - When no locking bytecode is provided, the template defines no change policy, and the\n * wallet has no default change policy.\n * @throws {@link TemplateNotFoundInStoreError} - When the change intent target template or the wallet policy template is not stored.\n * @throws {@link TemplateDefaultPolicyMissingError} - When the template of the wallet default change policy does not define change.\n * @throws {@link TemplateOutputNotFoundError} - When the change intent names an output its target template does not define.\n * @throws {@link IntentVariablesMissingError} - When a variable the change intent requires has no value.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n */\nconst generateChangeLockingBytecode = async (context: Required<AccountContext>, parameters: ChangeLockingBytecodeParameters): Promise<string> => {\n const { invitation, template, changeVariableValues, providedLockingBytecode } = parameters;\n\n // A locking bytecode given by the caller is used before any change policy.\n if (providedLockingBytecode !== undefined) {\n return providedLockingBytecode;\n }\n\n const changePolicy = template.defaults?.change;\n\n // The invitation template's change policy is used before the wallet default change policy.\n if (changePolicy !== undefined) {\n return generateLockingBytecodeFromIntent(context, {\n templateIdentifier: invitation.templateIdentifier,\n intent: changePolicy,\n variableValues: changeVariableValues,\n invitationIdentifier: invitation.invitationIdentifier,\n });\n }\n\n const defaultPolicies = await getDefaultPolicies(context.state);\n\n // The wallet default change policy is used when the invitation template defines no change policy.\n if (defaultPolicies.change !== undefined) {\n return generateLockingBytecodeFromDefaultPolicy(context, 'change', changeVariableValues, invitation.invitationIdentifier);\n }\n\n throw new ChangeLockingBytecodeMissingError(invitation.invitationIdentifier, invitation.templateIdentifier);\n};\n\n/**\n * Appends a change output to an invitation, holding the satoshis left after the outputs and the estimated fee.\n *\n * The change locks to the provided locking bytecode, otherwise to the change policy in the invitation template, and\n * otherwise to the wallet default change policy.\n *\n * @param {Required<AccountContext>} context - State, signing, and network for this account.\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the change output is appended to.\n * @param {Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>} changeVariableValues - Values the change intent requires.\n * @param {string} [providedLockingBytecode] - Locking bytecode to send the change to, as hex.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the change output is appended.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not stored.\n * @throws {@link ChangeLockingBytecodeMissingError} - When no locking bytecode is provided, the template defines no change policy, and the\n * wallet has no default change policy.\n * @throws {@link TemplateDefaultPolicyMissingError} - When the template of the wallet default change policy does not define change.\n * @throws {@link TemplateOutputNotFoundError} - When the change intent names an output its target template does not define.\n * @throws {@link IntentVariablesMissingError} - When a variable the change intent requires has no value.\n */\nexport const addChangeToInvitation = async (\n context: Required<AccountContext>,\n invitationIdentifier: XOInvitationIdentifier,\n changeVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>,\n providedLockingBytecode?: string,\n): Promise<StoredInvitation> => {\n // Get the invitation from the store.\n const { invitation } = await context.state.getInvitationOrThrow(invitationIdentifier);\n\n // Get the template for the invitation.\n const storedTemplate = await context.state.getTemplateOrThrow(invitation.templateIdentifier);\n const template = storedTemplate.template;\n\n // The change locks to the provided locking bytecode, or to the template or wallet change policy.\n const changeLockingBytecode = await generateChangeLockingBytecode(context, {\n invitation,\n template,\n changeVariableValues,\n providedLockingBytecode,\n });\n\n const { mergedInvitation } = await getMergedInvitationOrThrow(context.state, invitationIdentifier);\n\n const calculatedChangeAfterInputsAppend = await deriveMergedInvitationChange(mergedInvitation);\n\n const transactionFee = await estimateTransactionFee(context.state, invitation.invitationIdentifier);\n\n // Change is only its locking bytecode and value. The role and output it was built for are stored with the locking script in state.\n const changeOutput: XOInvitationOutput = {\n valueSatoshis: calculatedChangeAfterInputsAppend.valueSatoshis - BigInt(transactionFee),\n lockingBytecode: hexToBin(changeLockingBytecode),\n };\n\n return appendInvitation(context, invitationIdentifier, {\n templateIdentifier: invitation.templateIdentifier,\n actionIdentifier: invitation.actionIdentifier,\n outputs: [ changeOutput ],\n });\n};\n","import { Crypto, computeAccountHash, convertMnemonicToSeedBytes } from '@xo-cash/crypto';\nimport {\n State,\n createStorageAdapter,\n type ScriptHashData,\n type ScriptHashDataQuery,\n type SecretData,\n type StoredSecretData,\n type StorageListOptions,\n type StoredInvitation,\n type StoredTemplate,\n type UnspentOutputData,\n type UnspentOutputDataFilter,\n type UnspentOutputDataQuery,\n} from '@xo-cash/state';\nimport type {\n XOInvitation,\n XOInvitationCommit,\n XOInvitationIdentifier,\n XOInvitationVariableValue,\n XOTemplate,\n XOTemplateIdentifier,\n XOTemplateOutputIdentifier,\n XOTemplateRoleIdentifier,\n XOTemplateVariableIdentifier,\n} from '@xo-cash/types';\nimport { getChainStatus, initializeElectrumApplication, monitorScriptHash, type ChainStatus } from '@electrum-cash/application';\nimport { acceptInvitation } from './invitation/participation/accept.ts';\nimport { createInvitation } from './invitation/participation/create.ts';\nimport { joinInvitationRole } from './invitation/participation/join.ts';\nimport { appendInvitation } from './invitation/participation/append.ts';\nimport { executeAction } from './invitation/participation/execute.ts';\nimport { updateInvitation } from './invitation/participation/update.ts';\nimport { listAvailableRoles, listMissingRequirements, listRequirements } from './invitation/requirements/stored.ts';\nimport { listOwnInputIndexes } from './invitation/helpers/own-inputs.ts';\nimport { listCommitsForEntity } from './invitation/helpers/commits.ts';\nimport { generateUnlockingBytecode, type GeneratedInputUnlockingBytecode } from './compilation/generate-unlocking-bytecode.ts';\nimport { appendOwnInputResolutions, listInputResolutions, signInvitation } from './invitation/generation/unlocking-bytecode.ts';\nimport {\n appendOwnOutputResolutions,\n listOutputResolutions,\n resolveInvitationOutputLockingBytecode,\n} from './invitation/generation/locking-bytecode.ts';\nimport { BlockchainMonitor } from './network/blockchain.ts';\nimport { fetchScriptHashUnspentOutputs, listElectrumConnections, type ElectrumConnection } from './network/electrum.ts';\nimport { DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, DEFAULT_STORAGE_TYPE, DEFAULT_XO_NETWORK, type XONetwork } from './defaults.ts';\nimport {\n buildElectrumCacheDatabaseFilename,\n buildNetworkDatabaseFilename,\n resolveElectrumServersForNetwork,\n resolveHdKeyNetwork,\n} from './network/helper.ts';\nimport type { ListSpendableUnspentOutputsParameters, XOEngineOptions, WalletDefaultPolicies, DefaultPolicyTemplate } from './interfaces.ts';\nimport type {\n BuiltInvitationTransaction,\n ExecuteActionParameters,\n ExecuteActionResult,\n InvitationMissingRequirements,\n InvitationAcceptanceParameters,\n InvitationCreationParameters,\n InvitationParameters,\n InvitationRequirementIdentifierLists,\n InvitationResolutionRequirements,\n AccountContext,\n} from './invitation/interfaces.ts';\nimport { getDefaultPolicies, listTemplatesForDefaultPolicy, unsetDefaultPolicies, setDefaultPolicies } from './state/default-policies.ts';\nimport { generateLockingBytecodeFromDefaultPolicy, listDefaultPolicyRequiredVariables } from './compilation/intent-locking-bytecode.ts';\nimport { getMergedInvitationOrThrow } from './invitation/helpers/merged-invitation.ts';\nimport { WalletNameMissingError } from './errors/index.ts';\nimport type { MergedInvitationChange } from './invitation/change/derive.ts';\nimport { deriveMergedInvitationChange } from './invitation/change/derive.ts';\nimport { addChangeToInvitation } from './invitation/change/add.ts';\nimport { buildInvitationTransactionFromMergedCommit, estimateTransactionFee } from './invitation/generation/transaction.ts';\nimport { listSpendableUnspentOutputs, getSecretPublicKey, updateUnspentOutputsForScriptHash } from './state/index.ts';\n\n/**\n * Public interface of the XO engine. It holds the state, keys, network, and blockchain monitor of one account.\n */\nexport class Engine {\n /**\n * The crypto instance.\n */\n #crypto: Crypto;\n\n /**\n * The state instance.\n */\n #state: State;\n\n /**\n * The blockchain monitor instance.\n */\n #blockchainMonitor: BlockchainMonitor;\n\n /**\n * Network this engine instance targets.\n */\n readonly #network: XONetwork;\n\n /**\n * Constructs a new instance of XO Engine.\n * @private\n * @param {string} mnemonic - The BIP39 mnemonic to be used for this instance of the engine.\n * @param {State} state - State instance.\n * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.\n * @param {XONetwork} network - Network this instance derives keys and isolates storage for.\n */\n private constructor(mnemonic: string, state: State, blockchainMonitor: BlockchainMonitor, network: XONetwork) {\n // Derive keys on the HD network that matches this network.\n this.#crypto = new Crypto(convertMnemonicToSeedBytes(mnemonic), {\n network: resolveHdKeyNetwork(network),\n });\n\n // Store the network this instance was created for so later calls use the same network.\n this.#network = network;\n\n this.#state = state;\n this.#blockchainMonitor = blockchainMonitor;\n }\n\n /**\n * Network this engine instance targets.\n *\n * @returns {XONetwork} - Network this engine instance targets.\n */\n get network(): XONetwork {\n return this.#network;\n }\n\n /**\n * Lists every Electrum server this engine connects to, with the state of each connection.\n *\n * @returns {ElectrumConnection[]} - One entry per Electrum client, empty before Electrum is initialized.\n */\n listElectrumConnections(): ElectrumConnection[] {\n return listElectrumConnections();\n }\n\n /**\n * Reads the chain status the Electrum application last reported, with the reported and verified block heights.\n *\n * @returns {Promise<ChainStatus>} - Current height, verified height, and verified percent of the chain.\n */\n async getChainStatus(): Promise<ChainStatus> {\n return getChainStatus();\n }\n\n /**\n * Initializes and creates a new XO Engine instance.\n * Opens storage, configures Electrum, and starts the blockchain monitor.\n *\n * @param {string} mnemonic - BIP39 mnemonic to be used for this instance of the engine.\n * @param {XOEngineOptions} options - Storage, Electrum, network, and remote state settings for this instance.\n * @returns {Promise<Engine>} - An initialized Engine instance.\n */\n static async create(mnemonic: string, options: XOEngineOptions): Promise<Engine> {\n const network = options.network ?? DEFAULT_XO_NETWORK;\n\n // Resolve the Electrum servers for this network.\n const resolvedElectrumServers = options.electrumServers ?? resolveElectrumServersForNetwork(network);\n\n // The storage adapter and the Electrum name both include this hash.\n const accountHash = computeAccountHash(mnemonic);\n\n // Build the database filenames for this network. Each network has its own database.\n const networkDatabaseFilename = buildNetworkDatabaseFilename(network, options.databaseFilename);\n\n // Build the Electrum cache database filename for this account on this network, kept apart from the account database.\n const electrumCacheDatabaseFilename = buildElectrumCacheDatabaseFilename(network, accountHash, options.databaseFilename);\n\n // Configure Electrum.\n await initializeElectrumApplication(options.electrumApplicationIdentifier ?? DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, {\n electrumServersOrSockets: resolvedElectrumServers,\n databasePath: options.databasePath,\n databaseFilename: electrumCacheDatabaseFilename,\n });\n\n // Open the account database for this network.\n const storageAdapter = await createStorageAdapter({\n storageType: options.storageType ?? DEFAULT_STORAGE_TYPE,\n databasePath: options.databasePath,\n databaseFilename: networkDatabaseFilename,\n accountHash,\n });\n\n // Wrap the adapter so later methods share one State instance.\n const stateInstance = new State(storageAdapter);\n\n // Create the blockchain monitor instance.\n const blockchainMonitor = new BlockchainMonitor(stateInstance);\n\n // Register listeners.\n blockchainMonitor.initializeEventListeners();\n\n // Construct the engine instance.\n const engineInstance = new Engine(mnemonic, stateInstance, blockchainMonitor, network);\n\n // Electrum and the state are open, so subscribe to the stored script hashes and update their unspent outputs.\n await engineInstance.#monitorStoredScriptHashes();\n\n // Return the engine instance.\n return engineInstance;\n }\n\n /**\n * Stops the engine instance and cleans up resources.\n * @returns {Promise<void>} - Resolves when the engine is stopped.\n */\n async stop(): Promise<void> {\n // Stop the blockchain monitor and subscription\n await this.#blockchainMonitor.stop();\n\n // Destroy the crypto instance.\n this.#crypto.destroy();\n\n // Close the state.\n await this.#state.close();\n }\n\n // ============================================================================\n // Template Management\n // ============================================================================\n\n /**\n * Retrieves a template by its identifier from the state.\n * @param {XOTemplateIdentifier} templateIdentifier - Template identifier.\n * @returns {Promise<XOTemplate | undefined>} - The template object.\n */\n async getTemplate(templateIdentifier: XOTemplateIdentifier): Promise<XOTemplate | undefined> {\n const storedTemplate = await this.#state.getTemplate(templateIdentifier);\n\n // A template that was never imported has nothing to return.\n if (storedTemplate === undefined) {\n return undefined;\n }\n\n return storedTemplate.template;\n }\n\n /**\n * Imports a template into the Engine after sanitization and validation.\n *\n * @param {string | XOTemplate} untrustedJsonOrObject - JSON or object containing the untrusted template to import.\n * @returns {Promise<{ template: XOTemplate; templateIdentifier: XOTemplateIdentifier }>} - The imported template and its identifier.\n * @throws {@link TemplateInvalidError} - If the template is invalid.\n * @throws {@link DatabaseWriteOperationFailedError} - If an unexpected database error occurs.\n */\n async importTemplate(untrustedJsonOrObject: string | XOTemplate): Promise<{ template: XOTemplate; templateIdentifier: XOTemplateIdentifier }> {\n return this.#state.importTemplate(untrustedJsonOrObject);\n }\n\n /**\n * Lists templates for this account.\n *\n * @param {StorageListOptions} [options] - Optional list options such as archive filter.\n * @returns {Promise<StoredTemplate[]>} - Templates for this account.\n */\n async listTemplates(options?: StorageListOptions): Promise<StoredTemplate[]> {\n return this.#state.listTemplates(options);\n }\n\n /**\n * Archives one stored template in local storage.\n *\n * @param {XOTemplateIdentifier} templateIdentifier - Identifier of the template to archive\n * @returns {Promise<void>} - Resolves when the template is archived\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not in the store.\n */\n async archiveTemplate(templateIdentifier: XOTemplateIdentifier): Promise<void> {\n return this.#state.archiveTemplate(templateIdentifier);\n }\n\n /**\n * Restores one archived template in local storage.\n *\n * @param {XOTemplateIdentifier} templateIdentifier - Identifier of the template to restore\n * @returns {Promise<void>} - Resolves when restoration completes\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not in the store\n */\n async unarchiveTemplate(templateIdentifier: XOTemplateIdentifier): Promise<void> {\n return this.#state.unarchiveTemplate(templateIdentifier);\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Returns the stored name of this wallet.\n *\n * @returns {Promise<string | undefined>} - Stored wallet name, or undefined when no name has been stored.\n */\n async getWalletName(): Promise<string | undefined> {\n const walletSettings = await this.#state.getWalletSettings();\n\n // A wallet that never stored a name has none to return.\n if (walletSettings.walletName === undefined) {\n return undefined;\n }\n\n return walletSettings.walletName;\n }\n\n /**\n * Stores the name of this wallet.\n *\n * The name is trimmed before it is stored and replaces any name stored before.\n *\n * @param {string} walletName - Name to store.\n * @returns {Promise<void>} - Resolves when the trimmed name has been stored.\n * @throws {@link WalletNameMissingError} - When the name is empty or contains only whitespace.\n */\n async setWalletName(walletName: string): Promise<void> {\n // Trim before the check so a name of only whitespace is rejected and stored names carry no surrounding spaces.\n const trimmedWalletName = walletName.trim();\n\n // Reject an empty name before anything is written.\n if (trimmedWalletName.length === 0) {\n throw new WalletNameMissingError();\n }\n\n return this.#state.updateWalletSettings({ walletName: trimmedWalletName });\n }\n\n /**\n * Sets the wallet default policies used for change, receive, and address generation.\n *\n * Each policy is set independently. A policy omitted from `policiesToSet` keeps its stored value,\n * so setting the change policy never clears the receive or address policy.\n * Resolution order is override, then template defaults, then these default policies.\n *\n * @param {WalletDefaultPolicies} policiesToSet - Policies to set, each naming a template that defines that policy in its defaults.\n * @returns {Promise<void>} - Resolves when the provided policies have been stored.\n * @throws {@link TemplateNotFoundInStoreError} - When a policy names a template that is not stored.\n * @throws {@link TemplateDefaultPolicyMissingError} - When a policy names a template whose defaults do not define that policy.\n */\n async setDefaultPolicies(policiesToSet: WalletDefaultPolicies): Promise<void> {\n return setDefaultPolicies(this.#state, policiesToSet);\n }\n\n /**\n * Removes wallet default policies so change, receive, or address generation no longer uses them.\n *\n * Each policy is removed independently. A policy not listed in `policiesToRemove` keeps its stored value.\n * Removing a policy that is not stored changes nothing.\n *\n * @param {Array<keyof WalletDefaultPolicies>} policiesToRemove - Policies to remove, each one of change, receive, or address.\n * @returns {Promise<void>} - Resolves when the listed policies are no longer stored.\n */\n async unsetDefaultPolicies(policiesToRemove: Array<keyof WalletDefaultPolicies>): Promise<void> {\n return unsetDefaultPolicies(this.#state, policiesToRemove);\n }\n\n /**\n * Returns the wallet default policies used for change, receive, and address generation.\n *\n * Each policy is present only when it has been set with {@link Engine.setDefaultPolicies}.\n *\n * @returns {Promise<WalletDefaultPolicies>} - Stored default policies, or an empty object when none are stored.\n */\n async getDefaultPolicies(): Promise<WalletDefaultPolicies> {\n return getDefaultPolicies(this.#state);\n }\n\n /**\n * Lists the stored templates that can back the given wallet default policy.\n *\n * @param {keyof WalletDefaultPolicies} policy - Default policy being chosen, one of change, receive, or address.\n * @returns {Promise<DefaultPolicyTemplate[]>} - Matching templates with their storage identifiers.\n */\n async listTemplatesForDefaultPolicy(policy: keyof WalletDefaultPolicies): Promise<DefaultPolicyTemplate[]> {\n return listTemplatesForDefaultPolicy(this.#state, policy);\n }\n\n /**\n * Lists the variables a caller must provide to create a locking bytecode from a wallet default policy.\n *\n * These are the variables the policy template's defaults intent marks with a null value, plus any the generated\n * locking script needs that the template constants and intent presets do not supply.\n * Pass their values to {@link Engine.generateLockingBytecodeFromDefaultPolicy}.\n *\n * @param {keyof WalletDefaultPolicies} policy - Default policy to inspect, one of change, receive, or address.\n * @returns {Promise<XOTemplateVariableIdentifier[]>} - Required variable identifiers, empty when nothing needs to be provided.\n * @throws {@link TemplateNotFoundInStoreError} - When the policy template or the intent target template is not stored.\n * @throws {@link DefaultPolicyNotSetError} - When the policy is not set.\n * @throws {@link TemplateDefaultPolicyMissingError} - When its template does not define it.\n */\n async listDefaultPolicyRequiredVariables(policy: keyof WalletDefaultPolicies): Promise<XOTemplateVariableIdentifier[]> {\n return listDefaultPolicyRequiredVariables(this.#state, policy);\n }\n\n /**\n * Generates a locking bytecode from a wallet default policy.\n *\n * The stored policy names a template, and that template's defaults intent says which output or locking script,\n * role, and secrets to use. Every variable from {@link Engine.listDefaultPolicyRequiredVariables} must be in\n * `variableValues`, otherwise nothing is generated and no derivation index is used.\n *\n * @param {keyof WalletDefaultPolicies} policy - Default policy to create from, one of change, receive, or address.\n * @param {Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>} [variableValues] - Values for the variables the intent requires,\n * empty when none are passed.\n * @param {XOInvitationIdentifier} [invitationIdentifier] - Invitation the locking bytecode is built for. Keys this account already\n * generated for it under the policy template are used instead of new ones.\n * @returns {Promise<string>} - The generated locking bytecode as a hexadecimal string.\n * @throws {@link TemplateNotFoundInStoreError} - When the policy template or the intent target template is not stored.\n * @throws {@link DefaultPolicyNotSetError} - When the policy is not set.\n * @throws {@link TemplateDefaultPolicyMissingError} - When its template does not define it.\n * @throws {@link IntentVariablesMissingError} - When a required variable value is missing.\n * @throws {@link LockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link InvitationNotFoundInStoreError} - When an invitation is given and it is not stored.\n * @throws {@link SecretDataNotFoundError} - When a secret recorded for that invitation is not in the secret store.\n */\n async generateLockingBytecodeFromDefaultPolicy(\n policy: keyof WalletDefaultPolicies,\n variableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue> = {},\n invitationIdentifier?: XOInvitationIdentifier,\n ): Promise<string> {\n return generateLockingBytecodeFromDefaultPolicy(this.#accountContext, policy, variableValues, invitationIdentifier);\n }\n\n // ============================================================================\n // Deleting the account database\n // ============================================================================\n\n /**\n * Permanently deletes the full local account database for this engine instance.\n *\n * @returns {Promise<void>} - Resolves when the local database is deleted.\n * @throws {Error} - If shutdown or deletion fails.\n * @warning This permanently deletes templates, invitations, script hashes, unspent outputs, and events.\n * Use this only when the developer fully understands the data loss impact.\n */\n async DANGEROUS_deleteAccountDatabase(): Promise<void> {\n // Stop the monitor first to avoid concurrent writes during deletion.\n await this.#blockchainMonitor.stop();\n\n await this.#state.DANGEROUS_deleteDatabase();\n }\n\n // ============================================================================\n // Invitation Operations\n // ============================================================================\n\n /**\n * Retrieves an invitation by its identifier from the state.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation identifier.\n * @returns {Promise<StoredInvitation | undefined>} - The invitation, or undefined when it is not stored.\n */\n async getInvitation(invitationIdentifier: XOInvitationIdentifier): Promise<StoredInvitation | undefined> {\n return this.#state.getInvitation(invitationIdentifier);\n }\n\n /**\n * Lists invitations for this account.\n *\n * @param {StorageListOptions} [options] - Optional list options such as archive filter.\n * @returns {Promise<StoredInvitation[]>} - Invitations for this account.\n */\n async listInvitations(options?: StorageListOptions): Promise<StoredInvitation[]> {\n return this.#state.listInvitations(options);\n }\n\n /**\n * Archives one stored invitation in local storage.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Identifier of the invitation to archive\n * @returns {Promise<void>} - Resolves when the invitation is archived and its reservations are cleared\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not in the store\n * @warning This archives local invitation history for the identifier.\n */\n async archiveInvitation(invitationIdentifier: XOInvitationIdentifier): Promise<void> {\n return this.#state.archiveInvitation(invitationIdentifier);\n }\n\n /**\n * Restores one archived invitation in local storage.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Identifier of the invitation to restore\n * @returns {Promise<void>} - Resolves when restoration completes\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not in the store\n */\n async unarchiveInvitation(invitationIdentifier: XOInvitationIdentifier): Promise<void> {\n return this.#state.unarchiveInvitation(invitationIdentifier);\n }\n\n /**\n * Creates an invitation that can be shared with other entities, user, application, etc.\n * Invitation is the fundamental communication unit in XO, all the interactions done using the\n * xo template are done using invitations.\n *\n * @param {InvitationCreationParameters} params - The parameters for invitation creation.\n * @param {XOTemplateIdentifier} params.templateIdentifier - Identifier for the template to use.\n * @param {XOTemplateActionIdentifier} params.actionIdentifier - Identifier for the action to initiate.\n * @param {XOTemplateRoleIdentifier} [params.roleIdentifier] - Role this account takes in the action, when no intent names it.\n * @param {XOTemplateActionIntent} [params.intent] - Intent this account acted on. Its role is the role taken, and its generate list\n * is generated together with the action role's, one key per variable.\n * @returns {Promise<StoredInvitation>} - The constructed invitation as stored, including this account's entity identifier.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n * @throws {@link InvitationIntentMismatchError} - If the intent names another template or action.\n * @throws {@link InvitationRoleDuplicatedError} - If the role is given both directly and on the intent.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n * @throws {@link UnspentOutputReservationExternalConflictError} - If a local outpoint is already reserved by another invitation.\n * @throws {@link UnspentOutputReservationInternalConflictError} - If a local outpoint is already reserved by this invitation.\n *\n * @throws {@link SecretDataNotFoundError} - If a script hash of this account lists a secret that is not stored.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If the first commit gives this account more than one role with a follow up.\n */\n async createInvitation(params: InvitationCreationParameters): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return createInvitation(context, params);\n }\n\n /**\n * Accepts an invitation, an entity accepts an invitation and becomes part of the invitation.\n *\n * @param {XOInvitation} invitation - The invitation to be accepted.\n * @param {InvitationAcceptanceParameters} params - Optional parameters for accepting the invitation, including the role or intent\n * this account acts on.\n * @returns {Promise<StoredInvitation>} - The accepted invitation as stored, including this account's entity identifier.\n * @throws {@link InvitationInvalidError} - If the invitation does not match the XOInvitation type.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n * @throws {@link InvitationIntentMismatchError} - If the intent names another template or another action than the invitation.\n * @throws {@link InvitationRoleDuplicatedError} - If the role is given both directly and on the intent.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n * @throws {@link InvitationValidationFailedError} - If invitation validation fails once implemented.\n * @throws {@link InvitationItemFieldConflictError} - If a received commit changes a value an earlier commit set.\n * @throws {@link RoleVariableEntityMismatchError} - If a commit provides a variable of a role its entity does not hold.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If a commit gives an entity more than one role with a follow up.\n * @throws {@link SecretDataNotFoundError} - If a script hash of this account lists a secret that is not stored.\n */\n async acceptInvitation(invitation: XOInvitation, params?: InvitationAcceptanceParameters): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return acceptInvitation(context, invitation, params);\n }\n\n /**\n * Joins an invitation this account already takes part in with another role.\n *\n * The role must still have a free slot, and the keys it asks for are generated with the commit that names it.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation to join with the role.\n * @param {XOTemplateRoleIdentifier} roleIdentifier - Role to take.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit that names the role.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not stored.\n * @throws {@link InvitationRoleUnavailableError} - If the role has no free slot left.\n * @throws {@link TemplateActionRoleNotFoundError} - If the action does not define the role.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If the role would give this account more than one role with a follow up.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n * @throws {@link TemplateGeneratedVariableTypeUnsupportedError} - If a variable to generate is not a private key.\n */\n async joinInvitationRole(invitationIdentifier: XOInvitationIdentifier, roleIdentifier: XOTemplateRoleIdentifier): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return joinInvitationRole(context, invitationIdentifier, roleIdentifier);\n }\n\n /**\n * Updates the stored invitation with a newer version received from an external participant or through some subscription.\n * The updated invitation should have the shared history with the stored invitation, and the invitation must already be stored.\n *\n * An output another participant added that locks to one of this account's scripts is stored and tracked like a script\n * this account built, so its funds are seen and it can be unlocked later.\n *\n * @param {XOInvitation} updatedInvitation - Shared invitation to store. The local entity identifier and archive fields keep their stored values.\n * @returns {Promise<StoredInvitation>} - The updated invitation as stored, including the local entity identifier when present.\n * @throws {@link InvitationInvalidError} - If the updated invitation does not match the XOInvitation type.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not already in the store.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link InvitationValidationFailedError} - If the updated invitation fails validation.\n * @throws {@link InvitationHistoryConflictError} - If a stored commit is missing, reordered, or has a\n * different identifier or signature at its expected position in the updated invitation.\n * @throws {@link InvitationItemFieldConflictError} - If a commit changes a value an earlier commit set.\n * @throws {@link RoleVariableEntityMismatchError} - If a commit provides a variable of a role its entity does not hold.\n * @throws {@link EntityMultipleRolesWithFollowUpUnsupportedError} - If a commit gives an entity more than one role with a follow up.\n */\n async updateInvitation(updatedInvitation: XOInvitation): Promise<StoredInvitation> {\n return updateInvitation(this.#accountContext, updatedInvitation);\n }\n\n /**\n * Appends the invitation with the new information.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to append. The invitation must already exist in the store.\n * @param {InvitationParameters} params - The parameters to append the invitation with.\n * @returns {Promise<StoredInvitation>} - The appended invitation as stored, including the local entity identifier.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link AppendInvitationParametersEmptyError} - When every appendable field is omitted.\n * @throws {@link UnspentOutputReservationExternalConflictError} - If a local outpoint is already reserved by another invitation.\n * @throws {@link UnspentOutputReservationInternalConflictError} - If this invitation already reserves or spends the outpoint.\n * @throws {@link TemplateOutputNotFoundError} - If an output names a template output the template does not define.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If an output names a role its locking script does not define.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking bytecode of an output that names only a template output cannot be\n * compiled.\n * @throws {@link LockingScriptSecretsNotFoundError} - If such an output's locking script uses secrets this account has not generated for the\n * invitation.\n * @throws {@link LockingScriptResolutionsMissingError} - If such an output's locking script needs values the invitation does not hold yet.\n * Use {@link Engine.listOutputResolutions} to see them and {@link Engine.appendOwnOutputResolutions} to add this account's part.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\n async appendInvitation(invitationIdentifier: XOInvitationIdentifier, params: InvitationParameters): Promise<StoredInvitation> {\n return appendInvitation(this.#accountContext, invitationIdentifier, params);\n }\n\n /**\n * Resolves the locking bytecode an invitation output compiles to, without generating or storing anything.\n *\n * The locking script compiles with the template constants, the invitation variables, and the keys this account already\n * generated for the invitation, which is what {@link Engine.appendInvitation} uses when the output is added. The script's\n * secrets are existing secrets and are never generated for it, so a secret the invitation does not hold fails the\n * resolution the same way adding the output would.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output to resolve.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<string>} - The locking bytecode as a hexadecimal string.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking bytecode cannot be compiled.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n * @throws {@link CashAssemblyCompilationFailedError} - If the output locking script is a CashAssembly expression that cannot be compiled.\n * @throws {@link LockingScriptCompilationFailedError} - If the template locking script the output names cannot be compiled.\n * @throws {@link LockingScriptResolutionsMissingError} - If the script uses key operations other participants have not resolved yet.\n */\n async resolveInvitationOutputLockingBytecode(\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n ): Promise<string> {\n const context = this.#accountContext;\n\n return resolveInvitationOutputLockingBytecode(context, invitationIdentifier, outputIdentifier, roleIdentifier);\n }\n\n /**\n * Lists the key operations an invitation output's locking script needs from participants, without adding anything.\n *\n * Each operation is reported as provided when the invitation holds it, as this account's own when only this account's\n * keys resolve it, or as missing when another participant holds the key. The output can be added once nothing is\n * this account's own or missing.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output to check.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<InvitationResolutionRequirements>} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking script fails to compile for a reason other than a missing identifier.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\n async listOutputResolutions(\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n ): Promise<InvitationResolutionRequirements> {\n const context = this.#accountContext;\n\n return listOutputResolutions(context, invitationIdentifier, outputIdentifier, roleIdentifier);\n }\n\n /**\n * Adds the key operations this account resolved for an invitation output to the invitation, so other participants can\n * compile the same locking script.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the output belongs to.\n * @param {XOTemplateOutputIdentifier} outputIdentifier - Template output whose locking script the values are for.\n * @param {XOTemplateRoleIdentifier} [roleIdentifier] - Role on the output, when one is set.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit with the values.\n * @throws {@link OutputOwnResolutionsNotFoundError} - If this account resolved nothing the invitation does not already hold.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateOutputNotFoundError} - If the template does not define the output.\n * @throws {@link TemplateLockingScriptRoleNotFoundError} - If the role is not defined on the output's locking script.\n * @throws {@link LockingScriptSecretsNotFoundError} - If the locking script uses secrets this account has not generated for the invitation.\n * @throws {@link LockingBytecodeGenerationFailedError} - If the locking script fails to compile for a reason other than a missing identifier.\n * @throws {@link SecretDataNotFoundError} - If a secret recorded for this invitation is not in the secret store.\n */\n async appendOwnOutputResolutions(\n invitationIdentifier: XOInvitationIdentifier,\n outputIdentifier: XOTemplateOutputIdentifier,\n roleIdentifier?: XOTemplateRoleIdentifier,\n ): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return appendOwnOutputResolutions(context, invitationIdentifier, outputIdentifier, roleIdentifier);\n }\n\n /**\n * Lists the key operations an invitation input's unlocking script needs from participants, without signing or adding anything.\n *\n * Each operation is reported as provided when the invitation or the input holds it, as this account's own when only\n * this account's keys resolve it, such as its signature, or as missing when another participant holds the key. The\n * input can be signed with {@link Engine.signInvitation} once nothing is this account's own or missing.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the input belongs to.\n * @param {number} inputIndex - Index of the merged input.\n * @returns {Promise<InvitationResolutionRequirements>} - Provided identifiers, values this account can add, and identifiers others still owe.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the spent output has no stored script hash.\n * @throws {@link TemplateUnlockingScriptNotFoundError} - When neither the template input nor the locking script names an unlocking script.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When the unlocking script fails to compile for a reason other than a missing\n * identifier.\n */\n async listInputResolutions(invitationIdentifier: XOInvitationIdentifier, inputIndex: number): Promise<InvitationResolutionRequirements> {\n const context = this.#accountContext;\n\n return listInputResolutions(context, invitationIdentifier, inputIndex);\n }\n\n /**\n * Adds the key operations this account resolved for an invitation input, such as its signature, to that input, so the\n * participant holding the remaining keys can complete the unlocking bytecode.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation the input belongs to.\n * @param {number} inputIndex - Index of the merged input.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the commit with the values.\n * @throws {@link InputOwnResolutionsNotFoundError} - If this account resolved nothing the invitation does not already hold.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputCommitNotFoundError} - When the input has no merged leaf to extend.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When the unlocking script fails to compile for a reason other than a missing\n * identifier.\n */\n async appendOwnInputResolutions(invitationIdentifier: XOInvitationIdentifier, inputIndex: number): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return appendOwnInputResolutions(context, invitationIdentifier, inputIndex);\n }\n\n /**\n * Signs one input of the invitation with this account's keys and appends a commit that holds its unlocking bytecode.\n *\n * An unlocking script that needs values other entities hold, such as their signatures, is only signed once the invitation\n * holds them. Use {@link Engine.listInputResolutions} to see what the input still needs, and\n * {@link Engine.appendOwnInputResolutions} to add this account's part.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to sign.\n * The invitation must already exist in the store.\n * @param {number} inputIndex - Index of the merged input to sign.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the unlocking commit is appended.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link MergedInputCommitNotFoundError} - When the compiled input has no merged leaf to extend.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link UnlockingScriptResolutionsMissingError} - When the unlocking script needs values the invitation does not hold yet.\n * @throws {@link UnlockingCompilationContextMissingError} - When the unlocking compilation carries no context to verify against.\n * @throws {@link UnlockingBytecodeVerificationFailedError} - When the unlocking bytecode built with other entities' values fails.\n */\n async signInvitation(invitationIdentifier: XOInvitationIdentifier, inputIndex: number): Promise<StoredInvitation> {\n const context = this.#accountContext;\n\n return signInvitation(context, invitationIdentifier, inputIndex);\n }\n\n /**\n * Builds the encoded transaction for an invitation without broadcasting or persisting a hash.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Stored invitation to encode.\n * @returns {Promise<BuiltInvitationTransaction>} - Transaction hex and size metadata.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is missing.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is missing.\n * @throws {@link TemplateActionTransactionNotFoundError} - When the action has no transaction definition.\n * @throws {@link TransactionGenerationFailedError} - When libauth cannot build the transaction.\n */\n async buildInvitationTransactionFromMergedCommit(invitationIdentifier: XOInvitationIdentifier): Promise<BuiltInvitationTransaction> {\n const { storedInvitation, template, mergedInvitation: mergedCommit } = await getMergedInvitationOrThrow(this.#state, invitationIdentifier);\n\n return buildInvitationTransactionFromMergedCommit(mergedCommit, template, storedInvitation.invitation.actionIdentifier);\n }\n\n /**\n * Executes an action for a given invitation.\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation whose action to execute.\n * The invitation must already exist in the store.\n * @param {ExecuteActionParameters} params - Parameters for executing the action.\n * @returns {Promise<ExecuteActionResult>} - Encoded transaction metadata and the persisted invitation.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateNotFoundInStoreError} - If the invitation's template is not found in the store.\n * @throws {@link TransactionResultAlreadyExistsError} - If a different transaction was already recorded for the action.\n * @throws {@link TransactionBroadcastFailedError} - If the network rejects the transaction.\n * @throws {@link TransactionResultNotFoundError} - If the created result is missing when the broadcast is recorded.\n */\n async executeAction(invitationIdentifier: XOInvitationIdentifier, params: ExecuteActionParameters): Promise<ExecuteActionResult> {\n const context = this.#accountContext;\n\n return executeAction(context, invitationIdentifier, params);\n }\n\n /**\n * Lists available roles for the given invitation.\n *\n * @param {XOInvitation} invitation - The invitation to examine.\n * @returns {Promise<XOTemplateRoleIdentifier[]>} - The list of roles that still require data.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found.\n * @throws {@link TemplateActionNotFoundError} - If the action is not found.\n */\n async listAvailableRoles(invitation: XOInvitation): Promise<string[]> {\n return listAvailableRoles(this.#state, invitation);\n }\n\n /**\n * Lists requirements for the provided invitation.\n *\n * @param {XOInvitation} invitation - The invitation to analyze requirements for.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n * @returns {Promise<InvitationRequirementIdentifierLists>} - The requirements information.\n */\n async listRequirements(invitation: XOInvitation): Promise<InvitationRequirementIdentifierLists> {\n return listRequirements(this.#state, invitation);\n }\n\n /**\n * Lists all missing requirements for the provided invitation. They fall in two categories, which are\n * requirements expected by the template but not yet provided in any commit, and inputs\n * already committed with a real UTXO outpoint that are still missing their unlocking bytecode.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to analyze. The invitation must exist in the store.\n * @returns {Promise<InvitationMissingRequirements>} - Both the template-level gaps and the unsigned input gaps.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n * @throws {@link TemplateNotFoundInStoreError} - If the template is not found in the store.\n * @throws {@link TemplateActionNotFoundError} - When the action is not on the template.\n */\n async listMissingRequirements(invitationIdentifier: XOInvitationIdentifier): Promise<InvitationMissingRequirements> {\n return listMissingRequirements(this.#state, invitationIdentifier);\n }\n\n /**\n * Returns all commits in the invitation that were made by the current entity.\n *\n * @param {string} invitationIdentifier - The identifier of the invitation to examine.\n * @returns {Promise<XOInvitationCommit[]>} - Commits belonging to this engine's entity, in order.\n * @throws {@link InvitationNotFoundInStoreError} - If the invitation is not found in the store.\n */\n async listOwnCommits(invitationIdentifier: XOInvitationIdentifier): Promise<XOInvitationCommit[]> {\n const storedInvitation = await this.#state.getInvitationOrThrow(invitationIdentifier);\n\n return listCommitsForEntity(storedInvitation.invitation, storedInvitation.entityIdentifier);\n }\n\n /**\n * Finds all the inputs that are reserved by the current entity.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to find inputs for.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not in the store.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not in the store.\n * @returns {Promise<number[]>} - The indexes of the inputs that are reserved by the current entity.\n */\n async listOwnInputIndexes(invitationIdentifier: XOInvitationIdentifier): Promise<number[]> {\n return listOwnInputIndexes(this.#state, invitationIdentifier);\n }\n\n // ============================================================================\n // Resource Management\n // ============================================================================\n\n /**\n * Calculates the change for the invitation.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to calculate the change for.\n * @returns {Promise<MergedInvitationChange>} - The calculated change.\n */\n async calculateChange(invitationIdentifier: XOInvitationIdentifier): Promise<MergedInvitationChange> {\n // Load the invitation and its template, and merge the invitation commits.\n const { mergedInvitation } = await getMergedInvitationOrThrow(this.#state, invitationIdentifier);\n\n // Derive the merged invitation change\n return deriveMergedInvitationChange(mergedInvitation);\n }\n\n /**\n * Estimates the transaction fee for the invitation.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to estimate the transaction fee for.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not stored.\n * @returns {Promise<number>} - The estimated transaction fee.\n */\n async estimateTransactionFee(invitationIdentifier: XOInvitationIdentifier): Promise<number> {\n return estimateTransactionFee(this.#accountContext.state, invitationIdentifier);\n }\n\n /**\n * Adds the change to the invitation.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to add the change to.\n * @param {string} [providedLockingBytecode] - Locking bytecode to send the change to, as hex.\n * @param {Record<XOTemplateVariableIdentifier, XOInvitationVariableValue>} [changeVariableValues] - Values the change intent requires.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is not stored.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is not stored.\n * @throws {@link ChangeLockingBytecodeMissingError} - When no locking bytecode is provided, the template defines no change policy, and the\n * wallet has no default change policy.\n * @throws {@link TemplateDefaultPolicyMissingError} - When the template of the wallet default change policy does not define change.\n * @throws {@link TemplateOutputNotFoundError} - When the change intent names an output its target template does not define.\n * @throws {@link IntentVariablesMissingError} - When a variable the change intent requires has no value.\n * @returns {Promise<StoredInvitation>} - The invitation as stored after the change output is appended.\n */\n async addChangeToInvitation(\n invitationIdentifier: XOInvitationIdentifier,\n providedLockingBytecode?: string,\n changeVariableValues: Record<XOTemplateVariableIdentifier, XOInvitationVariableValue> = {},\n ): Promise<StoredInvitation> {\n return addChangeToInvitation(this.#accountContext, invitationIdentifier, changeVariableValues, providedLockingBytecode);\n }\n\n /**\n * Lists the unspent outputs this account tracks, each with the confirmation status Electrum last reported.\n *\n * @param {UnspentOutputDataQuery} [query] - Template, reservation, script hash, or status to select outputs by.\n * @param {UnspentOutputDataFilter} [filter] - Reservation and token fields every returned output must match.\n * @returns {Promise<UnspentOutputData[]>} - Unspent outputs matching the query and filter, or every tracked output when both are omitted.\n */\n async listUnspentOutputs(query?: UnspentOutputDataQuery, filter?: UnspentOutputDataFilter): Promise<UnspentOutputData[]> {\n return this.#state.listUnspentOutputsData(query, filter);\n }\n\n /**\n * Lists the unreserved unspent outputs that are free to spend.\n *\n * Outputs reserved by an invitation are excluded so the same output is never offered to two invitations.\n * When {@link ListSpendableUnspentOutputsParameters} are passed, only outputs locked by that template output\n * and matching every provided token field are returned.\n *\n * @param {ListSpendableUnspentOutputsParameters} [options] - Template output and token fields that every returned output must match.\n * @returns {Promise<UnspentOutputData[]>} - The unreserved unspent outputs that match the provided options.\n * @throws {@link TemplateNotFoundInStoreError} - When the template in the options is not stored.\n * @throws {@link TemplateOutputNotFoundError} - When the output in the options is not defined by that template.\n */\n async listSpendableUnspentOutputs(options?: ListSpendableUnspentOutputsParameters): Promise<UnspentOutputData[]> {\n return listSpendableUnspentOutputs(this.#state, options);\n }\n\n // ============================================================================\n // Script Hash Operations\n // ============================================================================\n\n /**\n * Lists the script hashes of every stored template. By default only the script hashes of un-archived templates are returned.\n *\n * @param {StorageListOptions} [options] - Optional list options.\n * @param {ArchiveFilter} [options.archived] - Filter applied to the templates based on archive state.\n * @returns {Promise<ScriptHashData[]>} - The script hash data of every matching template.\n * @throws {@link ArchiveFilterInvalidError} - When the archive filter is not one of the supported filters.\n */\n async listScriptHashes(options?: StorageListOptions): Promise<ScriptHashData[]> {\n return this.#state.listScriptHashes(options);\n }\n\n /**\n * Lists script hashes via state indexed storage query.\n *\n * Forwards to {@link State.listScriptHashData}. Exactly one of templateIdentifier, scriptHash, or invitationIdentifier.\n *\n * @param {ScriptHashDataQuery} query - Storage query accepted by the state package.\n * @returns {Promise<ScriptHashData[]>} - Matching script hashes from storage.\n * @throws {@link QueryFieldsLimitExceededError} - When more than one query field is set.\n * @throws {@link QueryInvalidError} - When no recognized query field is set.\n */\n async listScriptHashData(query: ScriptHashDataQuery): Promise<ScriptHashData[]> {\n return this.#state.listScriptHashData(query);\n }\n\n /**\n * Lists every secret this account has generated.\n *\n * Each secret holds a derivation index, not a key.\n *\n * @returns {Promise<StoredSecretData[]>} - The generated secrets, each with its lookup key, empty when none are stored.\n */\n async listSecretData(): Promise<StoredSecretData[]> {\n return this.#state.listSecretData();\n }\n\n /**\n * Returns the public key of a secret whose value is entropy. If the value is not entropy or the secret\n * doesn't exist, undefined is returned.\n *\n * @param {string} secretLookupKey - Lookup key the secret is stored under.\n * @returns {Promise<string | undefined>} - The compressed public key as hex, or undefined when the secret holds no entropy.\n */\n async getSecretPublicKey(secretLookupKey: string): Promise<string | undefined> {\n return getSecretPublicKey(this.#accountContext, secretLookupKey);\n }\n\n /**\n * Lists the secrets stored for a script hash, in the order the script hash lists them.\n *\n * Stored script hash data keeps only the lookup key of each secret, so each secret is read by its lookup key.\n *\n * @param {string} scriptHash - Script hash of a stored locking script.\n * @returns {Promise<SecretData[]>} - The secrets for the script hash, empty when it lists none.\n * @throws {@link ScriptHashDataNotFoundError} - When the script hash is not stored.\n * @throws {@link SecretDataNotFoundError} - When the script hash lists a lookup key that has no stored secret.\n */\n async listSecretsForScriptHash(scriptHash: string): Promise<SecretData[]> {\n return this.#state.listSecretsForScriptHash(scriptHash);\n }\n\n // ============================================================================\n // Unlocking Bytecode\n // ============================================================================\n\n /**\n * Compiles unlocking bytecode for one merged input without appending it to the invitation.\n *\n * @param {XOInvitationIdentifier} invitationIdentifier - Invitation that owns the input.\n * @param {number} inputIndex - Index of the merged input to unlock.\n * @returns {Promise<GeneratedInputUnlockingBytecode>} - Unlocking bytecode for that input.\n * @throws {@link InvitationNotFoundInStoreError} - When the invitation is absent from the store.\n * @throws {@link MergedInputOutpointMissingError} - When the merged input has no outpoint.\n * @throws {@link InputUnspentOutputUnavailableError} - When the spent output is not tracked by this account or is reserved by another invitation.\n * @throws {@link ScriptHashDataNotFoundError} - When the reserved output has no stored script hash.\n * @throws {@link UnlockingBytecodeGenerationFailedError} - When Libauth compilation fails.\n * @throws {@link TemplateNotFoundInStoreError} - When the template is absent from the store.\n */\n async generateUnlockingBytecode(invitationIdentifier: XOInvitationIdentifier, inputIndex: number): Promise<GeneratedInputUnlockingBytecode> {\n return generateUnlockingBytecode(this.#accountContext, invitationIdentifier, inputIndex);\n }\n\n /**\n * State, signing, and network of this account, in the form the invitation functions take.\n *\n * @returns {Required<AccountContext>} - The state, crypto, and network this engine was created with.\n */\n get #accountContext(): Required<AccountContext> {\n return {\n state: this.#state,\n crypto: this.#crypto,\n network: this.#network,\n };\n }\n\n /**\n * Subscribes to Electrum updates for every stored script hash,\n * and replaces the stored unspent outputs of each one with the list Electrum reports.\n *\n * Fails with the first subscribe, fetch, or store update that fails.\n *\n * @returns {Promise<void>} - Resolves when every stored script hash is subscribed and its unspent outputs are updated.\n */\n async #monitorStoredScriptHashes(): Promise<void> {\n const scriptHashDataList = await this.#state.listScriptHashes();\n\n const syncPromises = scriptHashDataList.map(async (scriptHashData) => {\n // Subscribe to update notifications for the script hash.\n await monitorScriptHash(scriptHashData.scriptHash);\n\n // Fetch the current unspent outputs and persist them.\n const unspentOutputsFromBlockchain = await fetchScriptHashUnspentOutputs(scriptHashData.scriptHash);\n\n await updateUnspentOutputsForScriptHash(this.#state, scriptHashData.scriptHash, unspentOutputsFromBlockchain);\n });\n await Promise.all(syncPromises);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAWA,MAAa,4CAA4C,MAAS,KAAK;;;;AAKvE,MAAa,uBAAuB,YAAY;;;;AAKhD,MAAa,0BAA0B;;;;AAKvC,MAAa,mBAAmB;;;;AAKhC,MAAa,kBAAkB;;;;AAK/B,MAAa,iBAAiB,IAAI,YAAY;;;;;;;;;;;AAY9C,MAAa,iCAAiC;;;;AAK9C,MAAa,0CAA0C;;;;AAKvD,MAAa,sBAAsB;;;;AAKnC,MAAa,wCAAwC;;;;AAKrD,MAAa,iCAAiC;;;;AAK9C,MAAa,kCAAkC;;;;AAK/C,MAAa,6BAA6B;;;;AAK1C,MAAa,yCAAyC,OAAO;;;;;AAM7D,MAAa,qCAAqC;CAC9C,WAAW;CACX,QAAQ;CACR,SAAS;CACZ;;;;AAUD,MAAa,yCAAoF;CAC7F,mCAAmC;CACnC,mCAAmC;CACnC,mCAAmC;CACtC;;;;AAKD,MAAa,wBAAwB;CACjC,SAAS;CACT,SAAS;CACT,UAAU;CACb;;;;AAUD,MAAa,qBAAgC,sBAAsB;;;;AAKnE,MAAa,oCAAoC;;;;AAKjD,MAAa,2CAA2C;;;;;;;;;;ACxHxD,MAAa,wBAAwB,UAAsC;AACvE,QAAO,UAAU,sBAAsB,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