@xo-cash/engine 0.0.1-development.14141361677 → 0.0.1-development.14148570389
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.
- package/dist/index.d.mts +85 -94
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +229 -240
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -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/builder.ts","../source/invitation/commit.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 ActionNotFoundError extends Error {\n constructor(actionIdentifier?: string) {\n const defaultMessage = 'Action not found in template';\n super(actionIdentifier ? `${defaultMessage}: actionIdentifier \"${actionIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when an output is not found in the template.\n */\nexport class OutputNotFoundError extends Error {\n constructor(outputIdentifier?: string) {\n const defaultMessage = 'Output not found in template';\n super(outputIdentifier ? `${defaultMessage}: outputIdentifier \"${outputIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a template is not found.\n */\nexport class TemplateNotFoundError extends Error {\n constructor(templateIdentifier?: string) {\n const defaultMessage = 'Template not found';\n super(templateIdentifier ? `${defaultMessage}: templateIdentifier \"${templateIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a locking script is not found in the template.\n */\nexport class LockingScriptNotFoundError extends Error {\n constructor(lockingScriptIdentifier?: string) {\n const defaultMessage = 'Locking script not found in template';\n super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier \"${lockingScriptIdentifier}\"` : defaultMessage);\n }\n}\n\n/**\n * Error thrown when a locking script type is not found in the template.\n */\nexport class LockingScriptTypeNotFoundError extends Error {\n constructor(lockingScriptIdentifier?: string) {\n const defaultMessage = 'Locking script type not found in template';\n super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier \"${lockingScriptIdentifier}\"` : defaultMessage);\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 TransactionNotFoundError extends Error {\n constructor(transactionIdentifier?: string) {\n const defaultMessage = 'Transaction not found in template';\n super(transactionIdentifier ? `${defaultMessage}: transactionIdentifier \"${transactionIdentifier}\"` : defaultMessage);\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 !== undefined ? ` (transactionIndex: ${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\nexport class TemplateIdentifierMismatchError extends Error {\n constructor() {\n const defaultMessage = 'Template identifier mismatch';\n super(defaultMessage);\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 RoleNotFoundError extends Error {\n constructor(roleIdentifier?: string) {\n const defaultMessage = 'Role not found';\n super(roleIdentifier ? `${defaultMessage}: roleIdentifier \"${roleIdentifier}\"` : defaultMessage);\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 OutputLockingScriptNotFoundError extends Error {\n constructor(outputIdentifier: string) {\n const defaultMessage = 'Output does not have a locking script';\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 LockingScriptNotFoundError,\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.getOutput(outputIdentifier);\n\n // Get the locking script for the output.\n const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);\n\n // Validate that locking script exists\n if (!lockingScriptForOutput.lockingBytecode) {\n throw new LockingScriptNotFoundError(lockingScriptForOutput.lockingBytecode);\n }\n\n // Validate the locking script, this checks if unlocking script and locking type are present\n // in the template for the given locking script identifier.\n template.validateLockingScript(lockingScriptForOutput, output.lockingScript);\n\n const lockingScriptIdentifier = output.lockingScript;\n\n // TODO: fix it hardcoded 'owner' role\n let roleIdentifier = 'owner';\n try {\n template.getRole(lockingScriptIdentifier, roleIdentifier);\n } catch {\n // If 'owner' doesn't exist, get first role\n const [ firstRoleId ] = template.getFirstRole(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 type { ScriptHashSubscribeNotification } from '@electrum-cash/protocol';\nimport { 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} 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 // TODO: Waiting for https://gitlab.com/electrum-cash/application/-/merge_requests/9\n // // Script hash events\n // electrumEvents.on('ScriptHashUpdate', async (_data: ScriptHashUpdate) => {\n // // Event listener registered but data is not stored\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 all associated\n * locking bytecodes and updates their unspent outputs in the store.\n *\n * @param {ScriptHashSubscribeNotification} data - The script hash subscription notification data.\n * @returns {Promise<void>} Resolves when all unspent outputs are updated.\n */\n async onScriptHashUpdate(data: ScriptHashSubscribeNotification): Promise<void> {\n const [ scriptHash ] = data.params;\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, hash256, hexToBin, stringify } 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 TemplateIdentifierMismatchError,\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';\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 TemplateIdentifierMismatchError();\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 const data: XOInvitationCommit['data'] = {\n variables: params.variables && params.variables.length > 0 ? params.variables : undefined,\n inputs: params.inputs && params.inputs.length > 0 ? params.inputs : undefined,\n outputs: params.outputs && params.outputs.length > 0 ? params.outputs : undefined,\n };\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 // TODO: Find a better way to generate the commit identifier.\n const commitIdentifier = binToHex(hash256(hexToBin(stringify(data) + params.previousCommitIdentifier + params.expiresAtTimestamp)));\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 { 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 type {\n XOTemplate,\n XOTemplateAction,\n XOTemplateTransaction,\n XOTemplateOutput,\n XOTemplateLockingScript,\n XOTemplateLockingScriptRole,\n XOTemplateActionIntent,\n} from '@xo-cash/types';\nimport {\n ActionNotFoundError,\n TransactionNotFoundError,\n OutputNotFoundError,\n LockingScriptNotFoundError,\n LockingScriptTypeNotFoundError,\n RoleNotFoundError,\n TemplateNotFoundError,\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 | undefined) {\n if (!template) {\n throw new TemplateNotFoundError();\n }\n\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 * Step 1 in the flow: template → output\n * @throws {OutputNotFoundError} If the output is not found.\n */\n getOutput(outputIdentifier: string): XOTemplateOutput {\n const output = this.template.outputs[outputIdentifier];\n if (!output) {\n throw new OutputNotFoundError(outputIdentifier);\n }\n\n return output;\n }\n\n /**\n * Retrieves the locking script identifier from an output.\n * Step 2 in the flow: output → locking script identifier\n * @throws {OutputNotFoundError} If the output is not found.\n * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.\n */\n getLockingScriptIdentifier(outputIdentifier: string): string {\n const output = this.getOutput(outputIdentifier);\n if (!output.lockingScript) {\n throw new LockingScriptNotFoundError(outputIdentifier);\n }\n\n return output.lockingScript;\n }\n\n /**\n * Retrieves a locking script definition by identifier.\n * Step 3 in the flow: locking script identifier → locking script\n * @throws {LockingScriptNotFoundError} If the locking script is not found.\n */\n getLockingScript(lockingScriptIdentifier: string): XOTemplateLockingScript {\n const lockingScript = this.template.lockingScripts[lockingScriptIdentifier];\n if (!lockingScript) {\n throw new LockingScriptNotFoundError(lockingScriptIdentifier);\n }\n\n return lockingScript;\n }\n\n /**\n * Retrieves the locking script for a given output.\n * Combines steps 1-3: output → locking script identifier → locking script\n * @throws {OutputNotFoundError} If the output is not found.\n * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.\n * @throws {LockingScriptNotFoundError} If the locking script is not found.\n */\n getLockingScriptForOutput(outputIdentifier: string): XOTemplateLockingScript {\n const lockingScriptIdentifier = this.getLockingScriptIdentifier(outputIdentifier);\n\n return this.getLockingScript(lockingScriptIdentifier);\n }\n\n /**\n * Validates that a locking script has required unlocking script and locking type.\n * Step 4 in the flow: validate locking script\n * @param lockingScript - The locking script to validate.\n * @param lockingScriptIdentifier - The identifier of the locking script (for error messages).\n * @throws {LockingScriptTypeNotFoundError} If lockingType is missing.\n */\n validateLockingScript(lockingScript: XOTemplateLockingScript, lockingScriptIdentifier: string): void {\n if (!lockingScript.lockingType) {\n throw new LockingScriptTypeNotFoundError(lockingScriptIdentifier);\n }\n }\n\n /**\n * Retrieves a role within a locking script.\n * Step 5 in the flow: locking script → role\n * @param lockingScriptIdentifier - The locking script identifier.\n * @param roleIdentifier - The role identifier.\n * @throws {LockingScriptNotFoundError} If the locking script is not found.\n * @throws {RoleNotFoundError} If the role is not found.\n */\n getRole(lockingScriptIdentifier: string, roleIdentifier: string): XOTemplateLockingScriptRole {\n const lockingScript = this.getLockingScript(lockingScriptIdentifier);\n const role = lockingScript.roles?.[roleIdentifier];\n if (!role) {\n throw new RoleNotFoundError(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 {LockingScriptNotFoundError} If the locking script is not found.\n * @throws {RoleNotFoundError} If no roles exist.\n */\n getFirstRole(lockingScriptIdentifier: string): [string, XOTemplateLockingScriptRole] {\n const lockingScript = this.getLockingScript(lockingScriptIdentifier);\n const roles = lockingScript.roles ?? {};\n const roleKeys = Object.keys(roles);\n if (roleKeys.length === 0) {\n throw new RoleNotFoundError();\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 * Step 6 in the flow: role → secrets (or locking script → secrets)\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 {LockingScriptNotFoundError} If the locking script is not found.\n * @throws {RoleNotFoundError} If roleIdentifier is provided but the role is not found.\n */\n getSecrets(lockingScriptIdentifier: string, roleIdentifier?: string): string[] {\n if (roleIdentifier) {\n const role = this.getRole(lockingScriptIdentifier, roleIdentifier);\n\n return role.state?.secrets ?? [];\n }\n\n const lockingScript = this.getLockingScript(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 {ActionNotFoundError} If the action is not found.\n */\n getActionOrThrow(actionIdentifier: string): XOTemplateAction {\n const action = this.template.actions[actionIdentifier];\n if (!action) {\n throw new ActionNotFoundError(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 {TransactionNotFoundError} If the transaction is not found.\n */\n getTransaction(transactionIdentifier: string): XOTemplateTransaction {\n const transaction = this.template.transactions?.[transactionIdentifier];\n if (!transaction) {\n throw new TransactionNotFoundError(transactionIdentifier);\n }\n\n return transaction;\n }\n\n /**\n * Retrieves the transaction for a given action.\n * Flow: action → transaction identifier → transaction\n * @param actionIdentifier - The identifier of the action.\n * @throws {ActionNotFoundError} If the action is not found.\n * @throws {TransactionNotFoundError} If the action doesn't have a transaction or it's not found.\n */\n getTransactionForAction(actionIdentifier: string): XOTemplateTransaction {\n const action = this.getActionOrThrow(actionIdentifier);\n if (!action.transaction) {\n throw new TransactionNotFoundError(action.transaction);\n }\n\n return this.getTransaction(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.getOutput(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).getTransaction(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 LockingScriptTypeNotFoundError,\n MergedCommitNotFoundError,\n TemplateNotFoundError,\n TransactionGenerationFailedError,\n TransactionNotFoundError,\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} seed - The wallet seed.\n * @param {State} store - Store instance.\n * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.\n */\n private constructor(seed: string, state: State, blockchainMonitor: BlockchainMonitor) {\n // Set the crypto instance\n this.crypto = new Crypto(convertMnemonicToSeedBytes(seed));\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} seed - Wallet seed used for signing and/or key derivation.\n * @param {XOEngineOptions} options - Database configuration options.\n * @returns {Promise<Engine>} An initialized Engine instance.\n */\n static async create(seed: 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 seed.\n const accountHash = binToHex(sha256.hash(utf8ToBin(seed)));\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(seed, 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 const template = await this.state.getTemplate(templateIdentifier);\n\n return template;\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 const templates = await this.state.listTemplates();\n\n return templates ?? [];\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\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 {ActionNotFoundError} 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 {ActionNotFoundError} 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 {XOInvitation} invitation - The invitation to append.\n * @param {AppendInvitationParameters} params - The parameters to append the invitation with.\n * @returns {Promise<XOInvitation>} The appended invitation.\n */\n async appendInvitation(invitation: XOInvitation, params: AppendInvitationParameters): Promise<XOInvitation> {\n const invitationFromStore = await this.getInvitationOrThrow(invitation.invitationIdentifier);\n\n // TODO: Perform validation.\n\n // Find the root commit identifier for the entity from the stored invitation.\n const rootCommitIdentifier = findRootCommitIdentifierInInvitation(invitationFromStore, invitationFromStore.entityIdentifier);\n\n // If the root commit identifier is not found, throw an error.\n if (rootCommitIdentifier === undefined) {\n throw new RootCommitNotFoundError(invitationFromStore.entityIdentifier);\n }\n\n // Create a invitation builder from the existing invitation.\n const invitationBuilder = InvitationBuilder.fromInvitation(invitation);\n\n // If outputs are provided as part of the parameters then check of the outputs are merging with a parent commit.\n if (params.outputs) {\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 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 invitation builder.\n invitationBuilder.addCommit(signedCommit);\n\n // TODO: Work on the following steps.\n // 1. Ensure that the invitation is stored in the local state and store if not.\n // 2. Create an event and store in the local state.\n // 3. Push the events to the encryption server.\n // 4. Lookup the resources (i.e inputs) and mark them as reserved\n // 5. Register this event in local state and push to the encryption server.\n // 6. 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: invitationFromStore.entityIdentifier,\n });\n\n // Return the updated invitation.\n return updatedInvitation;\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 {XOInvitation} invitation - The invitation to sign.\n * @returns {Promise<XOInvitation>} Resolves when signing is complete.\n *\n * TODO: Add all the throws that happen during the execution of the method.\n */\n async signInvitation(invitation: XOInvitation): Promise<XOInvitation> {\n // Fetch the invitation from the store to confirm it exists.\n const invitationFromStore = await this.getInvitationOrThrow(invitation.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) {\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) {\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 === invitationFromStore.invitationIdentifier\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 data: PrivateKeyRecordForLibauthCompiler | undefined;\n\n if (scriptHashData.derivationSource) {\n if (scriptHashData.derivationSource.lockingType === 'standard') {\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) {\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.getLockingScriptIdentifier(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 data = 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 (!data) {\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,\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) {\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 // Create the invitation from the existing invitation.\n let extendedInvitation: XOInvitation = InvitationBuilder.fromInvitation(invitation).build();\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) {\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 extendedInvitation.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 // Append the commit to the invitation.\n extendedInvitation = await this.appendInvitation(extendedInvitation, {\n inputs: [\n {\n mergesWith: {\n commitIdentifier: commitToExtend.commitIdentifier,\n index: indexToExtend,\n },\n unlockingBytecode: input.unlockingBytecode,\n },\n ],\n });\n }\n\n // Return the extended invitation.\n return extendedInvitation;\n }\n\n /**\n * Executes an action for a given invitation.\n * @param {XOInvitation} invitation - The invitation whose action to execute.\n * @param {ExecuteActionParameters} params - Parameters for executing the action.\n * @returns {Promise<void>} Resolves when the action is executed.\n *\n * TODO: Add all the throws that happen during the execution of the method.\n */\n async executeAction(invitation: XOInvitation, params: ExecuteActionParameters): Promise<TransactionHash> {\n // Get the template from the state.\n const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);\n\n // Validate the invitation\n const builder = InvitationBuilder.fromInvitation(invitation).validate(templateFromStore)\n.build();\n\n // Get the action from the template.\n const action = new Template(templateFromStore).getActionOrThrow(builder.actionIdentifier);\n\n // Merge invitation commits into transaction data\n const mergedCommit = mergeInvitationCommits(builder, templateFromStore);\n\n // If no merged commit is generated then there is nothing to sign.\n if (!mergedCommit) {\n throw new MergedCommitNotFoundError();\n }\n\n if (!action.transaction) {\n throw new TransactionNotFoundError();\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 * Fully validates a given XOInvitation according to template and signature checks.\n *\n * @param {XOInvitation} invitation - The invitation to validate.\n * @returns {Promise<void>} Resolves if invitation is valid.\n * @throws {TemplateNotFoundError} If the template is not found.\n * @throws {ActionNotFoundError} If the action is not found.\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 async isInvitationValid(invitation: XOInvitation): Promise<boolean> {\n const templateData = await this.state.getTemplate(invitation.templateIdentifier);\n\n // Create a template object from the template data, if template is undefined this will throw.\n const template = new Template(templateData);\n\n try {\n // Validate the invitation.\n InvitationBuilder.fromInvitation(invitation).validate(template.getTemplate());\n\n return true;\n } catch {\n // If the invitation is not valid, return false.\n return false;\n }\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 {ActionNotFoundError} 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 {XOInvitation} invitation - The invitation to analyze.\n * @returns {Promise<XOInvitationRequirements>} The missing requirements.\n */\n async listMissingRequirements(invitation: XOInvitation): Promise<XOInvitationRequirements> {\n // Get the template from the state.\n const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);\n\n // Create a template object from the template data, if template is undefined this will throw.\n const action = new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier);\n\n // List the missing requirements for the invitation.\n return listMissingRequirements(invitation, templateFromStore, 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).getOutput(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 templateData = await this.state.getTemplate(templateIdentifier);\n\n // Create a template object from the template data if it doesn't exists it throws in constructor.\n const template = new Template(templateData);\n\n // Get the output from the template.\n const output = template.getOutput(outputIdentifier);\n\n // Get the locking script from the output in template\n const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);\n\n // Validate the locking script.\n // Check if unlockingScript and lockingType are present.\n if (!output.lockingScript) {\n throw new LockingScriptTypeNotFoundError(outputIdentifier);\n }\n\n template.validateLockingScript(lockingScriptForOutput, output.lockingScript);\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.getFirstRole(output.lockingScript)[0];\n // Validate role exists if provided\n if (roleIdentifier) {\n template.getRole(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 LockingScriptTypeNotFoundError(outputIdentifier);\n }\n\n const unlockingScripts: CompilerConfiguration['unlockingScripts'] = {\n [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode,\n };\n\n const { lockingType } = lockingScriptForOutput;\n if (!lockingType) {\n throw new LockingScriptTypeNotFoundError(outputIdentifier);\n }\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 LockingScriptTypeNotFoundError(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(lockingBytecode);\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 * 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":";;;;;;;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;;;;;;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":["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,sBA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