@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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { bigIntToVmNumber, binToHex, binToUtf8, createCompilerBch, encodeTransaction, generateRandomBytes, generateTransaction, hash256, hashTransaction, hexToBin, sha256, stringify, utf8ToBin, vmNumberToBigInt } from "@bitauth/libauth";
1
+ import { bigIntToVmNumber, binToHex, binToUtf8, createCompilerBch, encodeTransaction, generateRandomBytes, generateTransaction, hashTransaction, hexToBin, sha256, utf8ToBin, vmNumberToBigInt } from "@bitauth/libauth";
2
2
  import { Crypto, buildInvitationCommitSigningPayload, convertMnemonicToSeedBytes, verifySchnorrSignature } from "@xo-cash/crypto";
3
3
  import { State, StorageType, UnspentOutputStatus, createStorageAdapter } from "@xo-cash/state";
4
4
  import { generateTemplateIdentifier, generateTemplateIdentifier as generateTemplateIdentifier$1, parseTemplate, parseTemplate as parseTemplate$1, scriptToScriptHash } from "@xo-cash/utils";
@@ -11,19 +11,17 @@ import { PublicKey } from "@xo-cash/primitives";
11
11
  /**
12
12
  * Error thrown when an action is not found in the template.
13
13
  */
14
- var ActionNotFoundError = class extends Error {
14
+ var TemplateActionNotFoundError = class extends Error {
15
15
  constructor(actionIdentifier) {
16
- const defaultMessage = "Action not found in template";
17
- super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
16
+ super(`Template action not found, actionIdentifier "${actionIdentifier}"`);
18
17
  }
19
18
  };
20
19
  /**
21
20
  * Error thrown when an output is not found in the template.
22
21
  */
23
- var OutputNotFoundError = class extends Error {
22
+ var TemplateOutputNotFoundError = class extends Error {
24
23
  constructor(outputIdentifier) {
25
- const defaultMessage = "Output not found in template";
26
- super(outputIdentifier ? `${defaultMessage}: outputIdentifier "${outputIdentifier}"` : defaultMessage);
24
+ super(`Template output not found, outputIdentifier "${outputIdentifier}"`);
27
25
  }
28
26
  };
29
27
  /**
@@ -31,26 +29,23 @@ var OutputNotFoundError = class extends Error {
31
29
  */
32
30
  var TemplateNotFoundError = class extends Error {
33
31
  constructor(templateIdentifier) {
34
- const defaultMessage = "Template not found";
35
- super(templateIdentifier ? `${defaultMessage}: templateIdentifier "${templateIdentifier}"` : defaultMessage);
32
+ super(`Template not found, templateIdentifier "${templateIdentifier}"`);
36
33
  }
37
34
  };
38
35
  /**
39
36
  * Error thrown when a locking script is not found in the template.
40
37
  */
41
- var LockingScriptNotFoundError = class extends Error {
38
+ var TemplateLockingScriptNotFoundError = class extends Error {
42
39
  constructor(lockingScriptIdentifier) {
43
- const defaultMessage = "Locking script not found in template";
44
- super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier "${lockingScriptIdentifier}"` : defaultMessage);
40
+ super(`Template locking script not found, lockingScriptIdentifier "${lockingScriptIdentifier}"`);
45
41
  }
46
42
  };
47
43
  /**
48
44
  * Error thrown when a locking script type is not found in the template.
49
45
  */
50
- var LockingScriptTypeNotFoundError = class extends Error {
46
+ var TemplateLockingScriptTypeNotFoundError = class extends Error {
51
47
  constructor(lockingScriptIdentifier) {
52
- const defaultMessage = "Locking script type not found in template";
53
- super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier "${lockingScriptIdentifier}"` : defaultMessage);
48
+ super(`Template locking script type not found, lockingScriptIdentifier "${lockingScriptIdentifier}"`);
54
49
  }
55
50
  };
56
51
  /**
@@ -83,10 +78,9 @@ var StartingActionNotFoundError = class extends Error {
83
78
  /**
84
79
  * Error thrown when a transaction is not found in the template.
85
80
  */
86
- var TransactionNotFoundError = class extends Error {
81
+ var TemplateTransactionNotFoundError = class extends Error {
87
82
  constructor(transactionIdentifier) {
88
- const defaultMessage = "Transaction not found in template";
89
- super(transactionIdentifier ? `${defaultMessage}: transactionIdentifier "${transactionIdentifier}"` : defaultMessage);
83
+ super(`Template transaction not found, transactionIdentifier "${transactionIdentifier}"`);
90
84
  }
91
85
  };
92
86
  /**
@@ -273,7 +267,7 @@ var ItemNotFoundInCommitError = class extends Error {
273
267
  */
274
268
  var LockingBytecodeNotFoundForOutputError = class extends Error {
275
269
  constructor(outputIdentifier, transactionIndex) {
276
- const indexInfo = transactionIndex !== void 0 ? ` (transactionIndex: ${transactionIndex})` : " (transactionIndex: undefined)";
270
+ const indexInfo = ` (transactionIndex: ${transactionIndex ?? "undefined"})`;
277
271
  super(`Locking bytecode not found for output: ${outputIdentifier}${indexInfo}`);
278
272
  }
279
273
  };
@@ -293,9 +287,12 @@ var DuplicateTransactionLocktimeError = class extends Error {
293
287
  super(`Transaction locktime is defined in multiple commits: ${commitIdentifiers.join(", ")}`);
294
288
  }
295
289
  };
296
- var TemplateIdentifierMismatchError = class extends Error {
297
- constructor() {
298
- super("Template identifier mismatch");
290
+ /**
291
+ * Error thrown when the provided template's identifier does not match the invitation's template identifier.
292
+ */
293
+ var InvitationTemplateMismatchError = class extends Error {
294
+ constructor(expectedTemplateIdentifier, receivedTemplateIdentifier) {
295
+ super(`Invitation template mismatch in validation, expected templateIdentifier "${expectedTemplateIdentifier}", got "${receivedTemplateIdentifier}"`);
299
296
  }
300
297
  };
301
298
  /**
@@ -378,10 +375,9 @@ var RoleNotDefinedForActionError = class extends Error {
378
375
  /**
379
376
  * Error thrown when a role is not found.
380
377
  */
381
- var RoleNotFoundError = class extends Error {
382
- constructor(roleIdentifier) {
383
- const defaultMessage = "Role not found";
384
- super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
378
+ var TemplateLockingScriptRoleNotFoundError = class extends Error {
379
+ constructor(lockingScriptIdentifier, roleIdentifier) {
380
+ super(`Template locking script role not found, lockingScriptIdentifier "${lockingScriptIdentifier}", roleIdentifier "${roleIdentifier}"`);
385
381
  }
386
382
  };
387
383
  /**
@@ -585,9 +581,9 @@ var InvalidVariableDefinitionError = class extends Error {
585
581
  /**
586
582
  * Error thrown when an output does not have a locking script.
587
583
  */
588
- var OutputLockingScriptNotFoundError = class extends Error {
584
+ var TemplateLockingScriptInOutputNotFoundError = class extends Error {
589
585
  constructor(outputIdentifier) {
590
- super(`Output does not have a locking script: outputIdentifier "${outputIdentifier}"`);
586
+ super(`Template locking script in output not found, outputIdentifier "${outputIdentifier}"`);
591
587
  }
592
588
  };
593
589
  /**
@@ -840,16 +836,15 @@ const convertXOLockingTypeToLibauth = (lockingType) => {
840
836
  */
841
837
  const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutput) => {
842
838
  const { outputIdentifier } = unspentOutput;
843
- const output = template.getOutput(outputIdentifier);
844
- const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);
845
- if (!lockingScriptForOutput.lockingBytecode) throw new LockingScriptNotFoundError(lockingScriptForOutput.lockingBytecode);
846
- template.validateLockingScript(lockingScriptForOutput, output.lockingScript);
839
+ const output = template.getOutputOrThrow(outputIdentifier);
840
+ const lockingScriptForOutput = template.getLockingScriptForOutputOrThrow(outputIdentifier);
841
+ if (lockingScriptForOutput.lockingBytecode === void 0) throw new TemplateLockingScriptInOutputNotFoundError(outputIdentifier);
847
842
  const lockingScriptIdentifier = output.lockingScript;
848
843
  let roleIdentifier = "owner";
849
844
  try {
850
- template.getRole(lockingScriptIdentifier, roleIdentifier);
845
+ template.getRoleOrThrow(lockingScriptIdentifier, roleIdentifier);
851
846
  } catch {
852
- const [firstRoleId] = template.getFirstRole(lockingScriptIdentifier);
847
+ const [firstRoleId] = template.getFirstRoleOrThrow(lockingScriptIdentifier);
853
848
  roleIdentifier = firstRoleId;
854
849
  }
855
850
  const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), roleIdentifier);
@@ -1130,6 +1125,9 @@ var BlockchainMonitor = class {
1130
1125
  electrumEvents.on("OutputFinalized", (_data) => {});
1131
1126
  electrumEvents.on("OutputSpent", (_data) => {});
1132
1127
  electrumEvents.on("AddressUpdate", (_data) => {});
1128
+ electrumEvents.on("ScriptHashUpdate", async (data) => {
1129
+ await this.onScriptHashUpdate(data);
1130
+ });
1133
1131
  this.eventListenersInitialized = true;
1134
1132
  }
1135
1133
  /**
@@ -1151,14 +1149,13 @@ var BlockchainMonitor = class {
1151
1149
  }
1152
1150
  /**
1153
1151
  * Handles script hash update notifications from the electrum protocol.
1154
- * When a script hash update is received, this method finds all associated
1155
- * locking bytecodes and updates their unspent outputs in the store.
1152
+ * When a script hash update is received, this method finds the scriptHash and updates the unspent outputs for it.
1156
1153
  *
1157
- * @param {ScriptHashSubscribeNotification} data - The script hash subscription notification data.
1158
- * @returns {Promise<void>} Resolves when all unspent outputs are updated.
1154
+ * @param {ScriptHashUpdate} data - The script hash update data.
1155
+ * @returns {Promise<void>} Resolves when the unspent outputs are updated.
1159
1156
  */
1160
1157
  async onScriptHashUpdate(data) {
1161
- const [scriptHash] = data.params;
1158
+ const { scriptHash } = data;
1162
1159
  const scriptHashDataList = await this.state.listScriptHashData({ scriptHash });
1163
1160
  const [firstElectrumClient] = electrumClients.values();
1164
1161
  for (const scriptHashData of scriptHashDataList) await updateUnspentOutputsForScriptHashInStore(this.state, scriptHashData.scriptHash, async () => {
@@ -1167,6 +1164,28 @@ var BlockchainMonitor = class {
1167
1164
  }
1168
1165
  };
1169
1166
 
1167
+ //#endregion
1168
+ //#region source/invitation/commit.ts
1169
+ /**
1170
+ * Generates a random 16-byte commit identifier.
1171
+ *
1172
+ * @returns {string} The generated commit identifier as a hex string.
1173
+ */
1174
+ const generateCommitIdentifier = () => {
1175
+ return binToHex(generateRandomBytes(16));
1176
+ };
1177
+ /**
1178
+ * Finds the root commit identifier for a given entity in an invitation. The root commit is
1179
+ * the first commit the entity added to the invitation.
1180
+ *
1181
+ * @param {XOInvitation} invitation The invitation whose commits are searched.
1182
+ * @param {string} entityIdentifier The entity identifier to search for among the invitation commits.
1183
+ * @returns {string | undefined} The root commit identifier if the entity has a commit in the invitation, otherwise undefined.
1184
+ */
1185
+ const findRootCommitIdentifierInInvitation = (invitation, entityIdentifier) => {
1186
+ for (const commit of invitation.commits) if (commit.entityIdentifier === entityIdentifier) return commit.commitIdentifier;
1187
+ };
1188
+
1170
1189
  //#endregion
1171
1190
  //#region source/invitation/builder.ts
1172
1191
  /**
@@ -1247,7 +1266,8 @@ var InvitationBuilder = class InvitationBuilder {
1247
1266
  * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
1248
1267
  */
1249
1268
  validate(template) {
1250
- if (generateTemplateIdentifier(template) !== this.templateIdentifier) throw new TemplateIdentifierMismatchError();
1269
+ const templateIdentifier = generateTemplateIdentifier(template);
1270
+ if (templateIdentifier !== this.templateIdentifier) throw new InvitationTemplateMismatchError(this.templateIdentifier, templateIdentifier);
1251
1271
  const action = new Template(template).getActionOrThrow(this.actionIdentifier);
1252
1272
  const invitation = this.build();
1253
1273
  if (hasInvitationExpired(invitation)) throw new InvitationExpiredError();
@@ -1313,15 +1333,21 @@ var InvitationBuilder = class InvitationBuilder {
1313
1333
  * This is a private helper method that initializes the commit building logic.
1314
1334
  */
1315
1335
  createCommit(params) {
1336
+ let variables;
1337
+ if (params.variables !== void 0 && params.variables.length > 0) variables = params.variables;
1338
+ let inputs;
1339
+ if (params.inputs !== void 0 && params.inputs.length > 0) inputs = params.inputs;
1340
+ let outputs;
1341
+ if (params.outputs !== void 0 && params.outputs.length > 0) outputs = params.outputs;
1316
1342
  const data = {
1317
- variables: params.variables && params.variables.length > 0 ? params.variables : void 0,
1318
- inputs: params.inputs && params.inputs.length > 0 ? params.inputs : void 0,
1319
- outputs: params.outputs && params.outputs.length > 0 ? params.outputs : void 0
1343
+ variables,
1344
+ inputs,
1345
+ outputs
1320
1346
  };
1321
1347
  if (params.transactionVersion !== void 0) data.transactionVersion = params.transactionVersion;
1322
1348
  if (params.transactionLocktime !== void 0) data.transactionLocktime = params.transactionLocktime;
1323
1349
  return {
1324
- commitIdentifier: binToHex(hash256(hexToBin(stringify(data) + params.previousCommitIdentifier + params.expiresAtTimestamp))),
1350
+ commitIdentifier: generateCommitIdentifier(),
1325
1351
  previousCommitIdentifier: params.previousCommitIdentifier,
1326
1352
  data,
1327
1353
  expiresAtTimestamp: params.expiresAtTimestamp
@@ -1338,28 +1364,6 @@ var InvitationBuilder = class InvitationBuilder {
1338
1364
  }
1339
1365
  };
1340
1366
 
1341
- //#endregion
1342
- //#region source/invitation/commit.ts
1343
- /**
1344
- * Generates a random 16-byte commit identifier.
1345
- *
1346
- * @returns {string} The generated commit identifier as a hex string.
1347
- */
1348
- const generateCommitIdentifier = () => {
1349
- return binToHex(generateRandomBytes(16));
1350
- };
1351
- /**
1352
- * Finds the root commit identifier for a given entity in an invitation. The root commit is
1353
- * the first commit the entity added to the invitation.
1354
- *
1355
- * @param {XOInvitation} invitation The invitation whose commits are searched.
1356
- * @param {string} entityIdentifier The entity identifier to search for among the invitation commits.
1357
- * @returns {string | undefined} The root commit identifier if the entity has a commit in the invitation, otherwise undefined.
1358
- */
1359
- const findRootCommitIdentifierInInvitation = (invitation, entityIdentifier) => {
1360
- for (const commit of invitation.commits) if (commit.entityIdentifier === entityIdentifier) return commit.commitIdentifier;
1361
- };
1362
-
1363
1367
  //#endregion
1364
1368
  //#region source/utils/template.ts
1365
1369
  /**
@@ -1374,7 +1378,6 @@ var Template = class {
1374
1378
  * Creates a Template class from a template object.
1375
1379
  */
1376
1380
  constructor(template) {
1377
- if (!template) throw new TemplateNotFoundError();
1378
1381
  this.template = template;
1379
1382
  }
1380
1383
  /**
@@ -1392,128 +1395,113 @@ var Template = class {
1392
1395
  }
1393
1396
  /**
1394
1397
  * Retrieves an output definition by identifier.
1395
- * Step 1 in the flow: template → output
1396
- * @throws {OutputNotFoundError} If the output is not found.
1398
+ * @throws {TemplateOutputNotFoundError} If the output is not found.
1397
1399
  */
1398
- getOutput(outputIdentifier) {
1400
+ getOutputOrThrow(outputIdentifier) {
1399
1401
  const output = this.template.outputs[outputIdentifier];
1400
- if (!output) throw new OutputNotFoundError(outputIdentifier);
1402
+ if (output === void 0) throw new TemplateOutputNotFoundError(outputIdentifier);
1403
+ if (!output.lockingScript) throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);
1401
1404
  return output;
1402
1405
  }
1403
1406
  /**
1404
1407
  * Retrieves the locking script identifier from an output.
1405
- * Step 2 in the flow: output → locking script identifier
1406
- * @throws {OutputNotFoundError} If the output is not found.
1407
- * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.
1408
+ * @throws {TemplateOutputNotFoundError} If the output is not found.
1409
+ * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.
1408
1410
  */
1409
- getLockingScriptIdentifier(outputIdentifier) {
1410
- const output = this.getOutput(outputIdentifier);
1411
- if (!output.lockingScript) throw new LockingScriptNotFoundError(outputIdentifier);
1411
+ getLockingScriptIdentifierOrThrow(outputIdentifier) {
1412
+ const output = this.getOutputOrThrow(outputIdentifier);
1413
+ if (output.lockingScript === void 0) throw new TemplateLockingScriptInOutputNotFoundError(outputIdentifier);
1412
1414
  return output.lockingScript;
1413
1415
  }
1414
1416
  /**
1415
1417
  * Retrieves a locking script definition by identifier.
1416
- * Step 3 in the flow: locking script identifier → locking script
1417
- * @throws {LockingScriptNotFoundError} If the locking script is not found.
1418
+ * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
1418
1419
  */
1419
- getLockingScript(lockingScriptIdentifier) {
1420
+ getLockingScriptOrThrow(lockingScriptIdentifier) {
1420
1421
  const lockingScript = this.template.lockingScripts[lockingScriptIdentifier];
1421
- if (!lockingScript) throw new LockingScriptNotFoundError(lockingScriptIdentifier);
1422
+ if (lockingScript === void 0) throw new TemplateLockingScriptNotFoundError(lockingScriptIdentifier);
1423
+ if (lockingScript.lockingType === void 0) throw new TemplateLockingScriptTypeNotFoundError(lockingScriptIdentifier);
1422
1424
  return lockingScript;
1423
1425
  }
1424
1426
  /**
1425
1427
  * Retrieves the locking script for a given output.
1426
- * Combines steps 1-3: output → locking script identifier → locking script
1427
- * @throws {OutputNotFoundError} If the output is not found.
1428
- * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.
1429
- * @throws {LockingScriptNotFoundError} If the locking script is not found.
1428
+ * @throws {TemplateOutputNotFoundError} If the output is not found.
1429
+ * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.
1430
+ * @throws {TemplateLockingScriptNotFoundError} If the locking script definition is not found.
1430
1431
  */
1431
- getLockingScriptForOutput(outputIdentifier) {
1432
- const lockingScriptIdentifier = this.getLockingScriptIdentifier(outputIdentifier);
1433
- return this.getLockingScript(lockingScriptIdentifier);
1434
- }
1435
- /**
1436
- * Validates that a locking script has required unlocking script and locking type.
1437
- * Step 4 in the flow: validate locking script
1438
- * @param lockingScript - The locking script to validate.
1439
- * @param lockingScriptIdentifier - The identifier of the locking script (for error messages).
1440
- * @throws {LockingScriptTypeNotFoundError} If lockingType is missing.
1441
- */
1442
- validateLockingScript(lockingScript, lockingScriptIdentifier) {
1443
- if (!lockingScript.lockingType) throw new LockingScriptTypeNotFoundError(lockingScriptIdentifier);
1432
+ getLockingScriptForOutputOrThrow(outputIdentifier) {
1433
+ const lockingScriptIdentifier = this.getLockingScriptIdentifierOrThrow(outputIdentifier);
1434
+ return this.getLockingScriptOrThrow(lockingScriptIdentifier);
1444
1435
  }
1445
1436
  /**
1446
1437
  * Retrieves a role within a locking script.
1447
- * Step 5 in the flow: locking script → role
1448
1438
  * @param lockingScriptIdentifier - The locking script identifier.
1449
1439
  * @param roleIdentifier - The role identifier.
1450
- * @throws {LockingScriptNotFoundError} If the locking script is not found.
1451
- * @throws {RoleNotFoundError} If the role is not found.
1440
+ * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
1441
+ * @throws {TemplateLockingScriptRoleNotFoundError} If the role is not found.
1452
1442
  */
1453
- getRole(lockingScriptIdentifier, roleIdentifier) {
1454
- const role = this.getLockingScript(lockingScriptIdentifier).roles?.[roleIdentifier];
1455
- if (!role) throw new RoleNotFoundError(roleIdentifier);
1443
+ getRoleOrThrow(lockingScriptIdentifier, roleIdentifier) {
1444
+ const role = this.getLockingScriptOrThrow(lockingScriptIdentifier).roles?.[roleIdentifier];
1445
+ if (role === void 0) throw new TemplateLockingScriptRoleNotFoundError(lockingScriptIdentifier, roleIdentifier);
1456
1446
  return role;
1457
1447
  }
1458
1448
  /**
1459
1449
  * Retrieves the first available role in a locking script, or throws if none exist.
1460
1450
  * @param lockingScriptIdentifier - The locking script identifier.
1461
1451
  * @returns A tuple of [roleIdentifier, role].
1462
- * @throws {LockingScriptNotFoundError} If the locking script is not found.
1463
- * @throws {RoleNotFoundError} If no roles exist.
1452
+ * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
1453
+ * @throws {TemplateLockingScriptRoleNotFoundError} If no roles exist.
1464
1454
  */
1465
- getFirstRole(lockingScriptIdentifier) {
1466
- const roles = this.getLockingScript(lockingScriptIdentifier).roles ?? {};
1455
+ getFirstRoleOrThrow(lockingScriptIdentifier) {
1456
+ const roles = this.getLockingScriptOrThrow(lockingScriptIdentifier).roles ?? {};
1467
1457
  const roleKeys = Object.keys(roles);
1468
- if (roleKeys.length === 0) throw new RoleNotFoundError();
1458
+ if (roleKeys.length === 0) throw new TemplateLockingScriptRoleNotFoundError(lockingScriptIdentifier, "");
1469
1459
  return [roleKeys[0], roles[roleKeys[0]]];
1470
1460
  }
1471
1461
  /**
1472
1462
  * Retrieves secrets for a locking script.
1473
1463
  * If roleIdentifier is provided, returns secrets from the role's state.
1474
1464
  * Otherwise, returns secrets from the locking script itself.
1475
- * Step 6 in the flow: role → secrets (or locking script → secrets)
1476
1465
  * @param lockingScriptIdentifier - The locking script identifier.
1477
1466
  * @param roleIdentifier - The role identifier (optional, if not provided uses locking script secrets).
1478
1467
  * @returns Array of secret identifiers.
1479
- * @throws {LockingScriptNotFoundError} If the locking script is not found.
1480
- * @throws {RoleNotFoundError} If roleIdentifier is provided but the role is not found.
1468
+ * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
1469
+ * @throws {TemplateLockingScriptRoleNotFoundError} If roleIdentifier is provided but the role is not found.
1481
1470
  */
1482
1471
  getSecrets(lockingScriptIdentifier, roleIdentifier) {
1483
- if (roleIdentifier) return this.getRole(lockingScriptIdentifier, roleIdentifier).state?.secrets ?? [];
1484
- return this.getLockingScript(lockingScriptIdentifier).state?.secrets ?? [];
1472
+ if (roleIdentifier !== void 0) return this.getRoleOrThrow(lockingScriptIdentifier, roleIdentifier).state?.secrets ?? [];
1473
+ return this.getLockingScriptOrThrow(lockingScriptIdentifier).state?.secrets ?? [];
1485
1474
  }
1486
1475
  /**
1487
1476
  * Retrieves an action definition by identifier.
1488
1477
  * @param actionIdentifier - The identifier of the action.
1489
- * @throws {ActionNotFoundError} If the action is not found.
1478
+ * @throws {TemplateActionNotFoundError} If the action is not found.
1490
1479
  */
1491
1480
  getActionOrThrow(actionIdentifier) {
1492
1481
  const action = this.template.actions[actionIdentifier];
1493
- if (!action) throw new ActionNotFoundError(actionIdentifier);
1482
+ if (action === void 0) throw new TemplateActionNotFoundError(actionIdentifier);
1494
1483
  return action;
1495
1484
  }
1496
1485
  /**
1497
1486
  * Retrieves a transaction definition by identifier.
1498
1487
  * @param transactionIdentifier - The identifier of the transaction.
1499
- * @throws {TransactionNotFoundError} If the transaction is not found.
1488
+ * @throws {TemplateTransactionNotFoundError} If the transaction is not found.
1500
1489
  */
1501
- getTransaction(transactionIdentifier) {
1490
+ getTransactionOrThrow(transactionIdentifier) {
1502
1491
  const transaction = this.template.transactions?.[transactionIdentifier];
1503
- if (!transaction) throw new TransactionNotFoundError(transactionIdentifier);
1492
+ if (transaction === void 0) throw new TemplateTransactionNotFoundError(transactionIdentifier);
1504
1493
  return transaction;
1505
1494
  }
1506
1495
  /**
1507
1496
  * Retrieves the transaction for a given action.
1508
- * Flow: action → transaction identifier → transaction
1509
1497
  * @param actionIdentifier - The identifier of the action.
1510
- * @throws {ActionNotFoundError} If the action is not found.
1511
- * @throws {TransactionNotFoundError} If the action doesn't have a transaction or it's not found.
1498
+ * @throws {TemplateActionNotFoundError} If the action is not found.
1499
+ * @throws {TemplateTransactionNotFoundError} If the action has no transaction defined or the transaction is not found.
1512
1500
  */
1513
- getTransactionForAction(actionIdentifier) {
1501
+ getTransactionForActionOrThrow(actionIdentifier) {
1514
1502
  const action = this.getActionOrThrow(actionIdentifier);
1515
- if (!action.transaction) throw new TransactionNotFoundError(action.transaction);
1516
- return this.getTransaction(action.transaction);
1503
+ if (action.transaction === void 0) throw new TemplateTransactionNotFoundError(actionIdentifier);
1504
+ return this.getTransactionOrThrow(action.transaction);
1517
1505
  }
1518
1506
  };
1519
1507
 
@@ -1680,7 +1668,7 @@ const resolveOutputFromTemplate = (output, variables, templateInstance) => {
1680
1668
  if (output.lockingBytecode !== void 0) resolvedOutput.lockingBytecode = typeof output.lockingBytecode === "string" ? hexToBin(output.lockingBytecode) : output.lockingBytecode;
1681
1669
  return resolvedOutput;
1682
1670
  }
1683
- const templateOutput = templateInstance.getOutput(output.outputIdentifier);
1671
+ const templateOutput = templateInstance.getOutputOrThrow(output.outputIdentifier);
1684
1672
  if (resolvedOutput.valueSatoshis === void 0) {
1685
1673
  if (templateOutput.valueSatoshis && isCashAssemblyExpression(templateOutput.valueSatoshis)) {
1686
1674
  const variablesObject = convertCommitVariablesIntoObject(variables);
@@ -1859,7 +1847,7 @@ const listRequirementsFromTemplate = (template, action) => {
1859
1847
  if (roleVariables) roleRequirements[roleIdentifier].variables = roleVariables;
1860
1848
  }
1861
1849
  if (action.transaction) {
1862
- const transactionDefinition = new Template(template).getTransaction(action.transaction);
1850
+ const transactionDefinition = new Template(template).getTransactionOrThrow(action.transaction);
1863
1851
  if (transactionDefinition.roles) for (const [roleIdentifier, transactionRoleRequirement] of Object.entries(transactionDefinition.roles)) {
1864
1852
  if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};
1865
1853
  if (transactionRoleRequirement.inputs) {
@@ -2204,12 +2192,12 @@ var Engine = class Engine {
2204
2192
  /**
2205
2193
  * Constructs a new instance of XO Engine.
2206
2194
  * @private
2207
- * @param {string} seed - The wallet seed.
2208
- * @param {State} store - Store instance.
2195
+ * @param {string} mnemonic - The BIP39 mnemonic to be used for this instance of the engine.
2196
+ * @param {State} state - State instance.
2209
2197
  * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.
2210
2198
  */
2211
- constructor(seed, state, blockchainMonitor) {
2212
- this.crypto = new Crypto(convertMnemonicToSeedBytes(seed));
2199
+ constructor(mnemonic, state, blockchainMonitor) {
2200
+ this.crypto = new Crypto(convertMnemonicToSeedBytes(mnemonic));
2213
2201
  this.state = state;
2214
2202
  this.blockchainMonitor = blockchainMonitor;
2215
2203
  }
@@ -2217,16 +2205,16 @@ var Engine = class Engine {
2217
2205
  * Initializes and creates a new XO Engine instance.
2218
2206
  * Configures the state, initializes the sync server and monitor for app and blockchain events
2219
2207
  *
2220
- * @param {string} seed - Wallet seed used for signing and/or key derivation.
2208
+ * @param {string} mnemonic - BIP39 mnemonic to be used for this instance of the engine.
2221
2209
  * @param {XOEngineOptions} options - Database configuration options.
2222
2210
  * @returns {Promise<Engine>} An initialized Engine instance.
2223
2211
  */
2224
- static async create(seed, options) {
2212
+ static async create(mnemonic, options) {
2225
2213
  await initializeElectrumApplication(options.electrumApplicationIdentifier ?? DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, {
2226
2214
  electrumServers,
2227
2215
  ...options
2228
2216
  });
2229
- const accountHash = binToHex(sha256.hash(utf8ToBin(seed)));
2217
+ const accountHash = binToHex(sha256.hash(utf8ToBin(mnemonic)));
2230
2218
  const stateInstance = new State(await createStorageAdapter({
2231
2219
  storageType: options.storageType ?? DEFAULT_STORAGE_TYPE,
2232
2220
  databasePath: options.databasePath,
@@ -2235,7 +2223,7 @@ var Engine = class Engine {
2235
2223
  }));
2236
2224
  const blockchainMonitor = new BlockchainMonitor(stateInstance);
2237
2225
  blockchainMonitor.initializeEventListeners();
2238
- const engineInstance = new Engine(seed, stateInstance, blockchainMonitor);
2226
+ const engineInstance = new Engine(mnemonic, stateInstance, blockchainMonitor);
2239
2227
  await engineInstance.initializeStateSync();
2240
2228
  return engineInstance;
2241
2229
  }
@@ -2259,7 +2247,7 @@ var Engine = class Engine {
2259
2247
  * @returns {Promise<XOTemplate | undefined>} The template object.
2260
2248
  */
2261
2249
  async getTemplate(templateIdentifier) {
2262
- return await this.state.getTemplate(templateIdentifier);
2250
+ return this.state.getTemplate(templateIdentifier);
2263
2251
  }
2264
2252
  /**
2265
2253
  * Imports a template into the Engine after sanitization and validation.
@@ -2280,7 +2268,7 @@ var Engine = class Engine {
2280
2268
  * @returns {Promise<XOTemplate[]>} The list of imported templates.
2281
2269
  */
2282
2270
  async listImportedTemplates() {
2283
- return await this.state.listTemplates() ?? [];
2271
+ return this.state.listTemplates();
2284
2272
  }
2285
2273
  /**
2286
2274
  * Lists the starting actions available in a specified template.
@@ -2344,7 +2332,10 @@ var Engine = class Engine {
2344
2332
  * Initializes the state sync process.
2345
2333
  * @returns {Promise<void>} Resolves when the state sync is initialized.
2346
2334
  */
2347
- async initializeStateSync() {}
2335
+ async initializeStateSync() {
2336
+ const scriptHashDataList = await this.listScriptHashes();
2337
+ for (const scriptHashData of scriptHashDataList) await this.updateUnspentOutputsForScriptHashInStore(scriptHashData.scriptHash);
2338
+ }
2348
2339
  /**
2349
2340
  * Creates an invitation that can be shared with other entities, user, application, etc.
2350
2341
  * Invitation is the fundamental communication unit in XO, all the interactions done using the
@@ -2355,7 +2346,7 @@ var Engine = class Engine {
2355
2346
  * @param {string} params.actionIdentifier - Identifier for the action to initiate.
2356
2347
  * @returns {Promise<XOInvitation>} A promise that resolves to the constructed invitation.
2357
2348
  * @throws {TemplateNotFoundError} If the template is not found.
2358
- * @throws {ActionNotFoundError} If the action is not found.
2349
+ * @throws {TemplateActionNotFoundError} If the action is not found.
2359
2350
  *
2360
2351
  * TODO: Add all the throws that happen during the execution of the method.
2361
2352
  */
@@ -2386,7 +2377,7 @@ var Engine = class Engine {
2386
2377
  * @param {AcceptInvitationParameters} params - Optional parameters for accepting the invitation.
2387
2378
  * @returns {Promise<XOInvitation>} The updated XOInvitation instance.
2388
2379
  * @throws {TemplateNotFoundError} If the template is not found.
2389
- * @throws {ActionNotFoundError} If the action is not found.
2380
+ * @throws {TemplateActionNotFoundError} If the action is not found.
2390
2381
  * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
2391
2382
  * @throws {InvalidRequirementsError} If the requirements are invalid.
2392
2383
  * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
@@ -2416,92 +2407,72 @@ var Engine = class Engine {
2416
2407
  /**
2417
2408
  * Appends the invitation with the new information.
2418
2409
  *
2419
- * @param {XOInvitation} invitation - The invitation to append.
2410
+ * @param {string} invitationIdentifier - The identifier of the invitation to append. The invitation must already exist in the store.
2420
2411
  * @param {AppendInvitationParameters} params - The parameters to append the invitation with.
2421
2412
  * @returns {Promise<XOInvitation>} The appended invitation.
2413
+ * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
2422
2414
  */
2423
- async appendInvitation(invitation, params) {
2424
- const invitationFromStore = await this.getInvitationOrThrow(invitation.invitationIdentifier);
2425
- const rootCommitIdentifier = findRootCommitIdentifierInInvitation(invitationFromStore, invitationFromStore.entityIdentifier);
2426
- if (rootCommitIdentifier === void 0) throw new RootCommitNotFoundError(invitationFromStore.entityIdentifier);
2427
- const invitationBuilder = InvitationBuilder.fromInvitation(invitation);
2428
- if (params.outputs) for (const output of params.outputs) {
2429
- if (output.mergesWith !== void 0 || output.roleIdentifier !== void 0 || output.lockingBytecode !== void 0) continue;
2430
- output.lockingBytecode = hexToBin(await this.generateLockingBytecodeForDefaultParameters());
2431
- }
2432
- const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2433
- invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),
2434
- invitationIdentifier: invitationBuilder.invitationIdentifier,
2435
- rootCommitIdentifier,
2436
- templateIdentifier: invitationBuilder.templateIdentifier,
2437
- actionIdentifier: invitationBuilder.actionIdentifier
2438
- });
2439
- invitationBuilder.addCommit(signedCommit);
2440
- const inputsForReservation = await this.findOwnResources(params.inputs ?? []);
2441
- if (inputsForReservation.length > 0) await this.reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);
2442
- const updatedInvitation = invitationBuilder.build();
2443
- await this.state.storeInvitation(updatedInvitation.invitationIdentifier, {
2444
- ...updatedInvitation,
2445
- entityIdentifier: invitationFromStore.entityIdentifier
2446
- });
2447
- return updatedInvitation;
2415
+ async appendInvitation(invitationIdentifier, params) {
2416
+ const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
2417
+ return this.applyInvitationAppend(invitationFromStore, params);
2448
2418
  }
2449
2419
  /**
2450
2420
  * Signs the provided invitation once all the resources are reserved and the invitation is complete.
2451
2421
  * This method is used to sign own inputs and provide unlocking data for them, this appends the
2452
2422
  * invitation and adds new commit with unlocking data.
2453
2423
  *
2454
- * @param {XOInvitation} invitation - The invitation to sign.
2424
+ * @param {string} invitationIdentifier - The identifier of the invitation to sign. The invitation must already exist in the store.
2455
2425
  * @returns {Promise<XOInvitation>} Resolves when signing is complete.
2426
+ * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
2456
2427
  *
2457
2428
  * TODO: Add all the throws that happen during the execution of the method.
2458
2429
  */
2459
- async signInvitation(invitation) {
2460
- const invitationFromStore = await this.getInvitationOrThrow(invitation.invitationIdentifier);
2430
+ async signInvitation(invitationIdentifier) {
2431
+ const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
2461
2432
  const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
2462
2433
  const mergedCommit = mergeInvitationCommits(invitationFromStore, template);
2463
- if (!mergedCommit) throw new MergedCommitNotFoundError();
2434
+ if (mergedCommit === void 0) throw new MergedCommitNotFoundError();
2464
2435
  const transactionResult = generateTransaction({
2465
2436
  version: mergedCommit.transactionVersion,
2466
2437
  locktime: mergedCommit.transactionLocktime,
2467
2438
  inputs: mergedCommit.inputs,
2468
2439
  outputs: mergedCommit.outputs
2469
2440
  });
2470
- if (!transactionResult.success) throw new TransactionGenerationFailedError();
2441
+ if (transactionResult.success === false) throw new TransactionGenerationFailedError();
2471
2442
  const unspentOutputs = await this.state.listUnspentOutputsData({ reservedBy: invitationFromStore.invitationIdentifier });
2472
2443
  for (const [index, input] of transactionResult.transaction.inputs.entries()) {
2473
2444
  let unspentOutput;
2474
- for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex && sourceOutput.reservedBy === invitationFromStore.invitationIdentifier) {
2445
+ for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex && sourceOutput.reservedBy) {
2475
2446
  unspentOutput = sourceOutput;
2476
2447
  break;
2477
2448
  }
2478
2449
  if (!unspentOutput) continue;
2479
2450
  const scriptHashData = await this.state.getScriptHashData(unspentOutput.scriptHash);
2480
2451
  if (scriptHashData === void 0) throw new ScriptHashDataNotFoundError(unspentOutput.scriptHash);
2481
- let data;
2482
- if (scriptHashData.derivationSource) {
2483
- if (scriptHashData.derivationSource.lockingType === "standard") {
2452
+ let compilerPrivateKeyRecord;
2453
+ if (scriptHashData.derivationSource !== void 0) {
2454
+ if (scriptHashData.derivationSource.lockingType === "p2pkh") {
2484
2455
  const templateDataForInput = await this.state.getTemplate(scriptHashData.templateIdentifier);
2485
- if (!templateDataForInput) throw new TemplateNotFoundError(scriptHashData.templateIdentifier);
2456
+ if (templateDataForInput === void 0) throw new TemplateNotFoundError(scriptHashData.templateIdentifier);
2486
2457
  const templateInstanceForInput = new Template(templateDataForInput);
2487
- const lockingScriptIdentifier = templateInstanceForInput.getLockingScriptIdentifier(scriptHashData.outputIdentifier);
2458
+ const lockingScriptIdentifier = templateInstanceForInput.getLockingScriptIdentifierOrThrow(scriptHashData.outputIdentifier);
2488
2459
  const secretIdentifiers = templateInstanceForInput.getSecrets(lockingScriptIdentifier, scriptHashData.roleIdentifier);
2489
2460
  const { derivativeIndex } = scriptHashData.derivationSource;
2490
2461
  if (typeof derivativeIndex !== "string") throw new InvalidDerivativeIndexTypeError("string", typeof derivativeIndex);
2491
- data = this.crypto.derivePrivateKeyRecordForCompiler({
2462
+ compilerPrivateKeyRecord = this.crypto.derivePrivateKeyRecordForCompiler({
2492
2463
  compilerKeyIdentifiers: secretIdentifiers,
2493
2464
  templateIdentifier: scriptHashData.templateIdentifier,
2494
2465
  templateKeyDerivationIndex: Number(derivativeIndex)
2495
2466
  });
2496
2467
  }
2497
2468
  }
2498
- if (!data) throw new LockingDataNotFoundError();
2469
+ if (compilerPrivateKeyRecord === void 0) throw new LockingDataNotFoundError();
2499
2470
  const compilerData = await createLibauthCompilerDataFromUnspentOutput(new Template(template), unspentOutput);
2500
2471
  transactionResult.transaction.inputs[index] = {
2501
2472
  ...input,
2502
2473
  unlockingBytecode: {
2503
2474
  ...compilerData,
2504
- data
2475
+ data: compilerPrivateKeyRecord
2505
2476
  }
2506
2477
  };
2507
2478
  }
@@ -2511,47 +2482,51 @@ var Engine = class Engine {
2511
2482
  inputs: transactionResult.transaction.inputs,
2512
2483
  outputs: transactionResult.transaction.outputs
2513
2484
  });
2514
- if (!signedTransaction.success) throw new TransactionGenerationFailedError();
2515
- let extendedInvitation = InvitationBuilder.fromInvitation(invitation).build();
2485
+ if (signedTransaction.success === false) throw new TransactionGenerationFailedError();
2486
+ let currentStoredInvitation = invitationFromStore;
2516
2487
  for (const input of signedTransaction.transaction.inputs.values()) {
2517
2488
  let unspentOutput;
2518
2489
  for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex) {
2519
2490
  unspentOutput = sourceOutput;
2520
2491
  break;
2521
2492
  }
2522
- if (!unspentOutput) throw new UnspentOutputNotFoundError();
2493
+ if (unspentOutput === void 0) throw new UnspentOutputNotFoundError();
2523
2494
  let commitToExtend;
2524
2495
  let indexToExtend;
2525
- for (const commit of extendedInvitation.commits) for (const [index, commitInput] of (commit.data.inputs ?? []).entries()) if (commitInput.outpointTransactionHash && binToHex(commitInput.outpointTransactionHash) === binToHex(input.outpointTransactionHash) && Number(commitInput.outpointIndex) === Number(input.outpointIndex)) {
2496
+ for (const commit of currentStoredInvitation.commits) for (const [index, commitInput] of (commit.data.inputs ?? []).entries()) if (commitInput.outpointTransactionHash && binToHex(commitInput.outpointTransactionHash) === binToHex(input.outpointTransactionHash) && Number(commitInput.outpointIndex) === Number(input.outpointIndex)) {
2526
2497
  commitToExtend = commit;
2527
2498
  indexToExtend = index;
2528
2499
  }
2529
2500
  if (commitToExtend === void 0 || indexToExtend === void 0) throw new CommitNotFoundInInvitationError();
2530
- extendedInvitation = await this.appendInvitation(extendedInvitation, { inputs: [{
2531
- mergesWith: {
2532
- commitIdentifier: commitToExtend.commitIdentifier,
2533
- index: indexToExtend
2534
- },
2535
- unlockingBytecode: input.unlockingBytecode
2536
- }] });
2501
+ currentStoredInvitation = {
2502
+ ...await this.applyInvitationAppend(currentStoredInvitation, { inputs: [{
2503
+ mergesWith: {
2504
+ commitIdentifier: commitToExtend.commitIdentifier,
2505
+ index: indexToExtend
2506
+ },
2507
+ unlockingBytecode: input.unlockingBytecode
2508
+ }] }),
2509
+ entityIdentifier: invitationFromStore.entityIdentifier
2510
+ };
2537
2511
  }
2538
- return extendedInvitation;
2512
+ return currentStoredInvitation;
2539
2513
  }
2540
2514
  /**
2541
2515
  * Executes an action for a given invitation.
2542
- * @param {XOInvitation} invitation - The invitation whose action to execute.
2516
+ * @param {string} invitationIdentifier - The identifier of the invitation whose action to execute.
2517
+ * The invitation must already exist in the store.
2543
2518
  * @param {ExecuteActionParameters} params - Parameters for executing the action.
2544
- * @returns {Promise<void>} Resolves when the action is executed.
2519
+ * @returns {Promise<TransactionHash>} Resolves with the transaction hash when the action is executed.
2520
+ * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
2545
2521
  *
2546
2522
  * TODO: Add all the throws that happen during the execution of the method.
2547
2523
  */
2548
- async executeAction(invitation, params) {
2549
- const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);
2550
- const builder = InvitationBuilder.fromInvitation(invitation).validate(templateFromStore).build();
2551
- const action = new Template(templateFromStore).getActionOrThrow(builder.actionIdentifier);
2552
- const mergedCommit = mergeInvitationCommits(builder, templateFromStore);
2553
- if (!mergedCommit) throw new MergedCommitNotFoundError();
2554
- if (!action.transaction) throw new TransactionNotFoundError();
2524
+ async executeAction(invitationIdentifier, params) {
2525
+ const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
2526
+ const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
2527
+ const mergedCommit = mergeInvitationCommits(invitationFromStore, template);
2528
+ if (mergedCommit === void 0) throw new MergedCommitNotFoundError();
2529
+ if (new Template(template).getActionOrThrow(invitationFromStore.actionIdentifier).transaction === void 0) throw new TemplateTransactionNotFoundError(invitationFromStore.actionIdentifier);
2555
2530
  const resultTransaction = generateTransaction({
2556
2531
  version: mergedCommit.transactionVersion,
2557
2532
  locktime: mergedCommit.transactionLocktime,
@@ -2565,33 +2540,12 @@ var Engine = class Engine {
2565
2540
  return txHash;
2566
2541
  }
2567
2542
  /**
2568
- * Fully validates a given XOInvitation according to template and signature checks.
2569
- *
2570
- * @param {XOInvitation} invitation - The invitation to validate.
2571
- * @returns {Promise<void>} Resolves if invitation is valid.
2572
- * @throws {TemplateNotFoundError} If the template is not found.
2573
- * @throws {ActionNotFoundError} If the action is not found.
2574
- * @throws {InvitationExpiredError} If the invitation has expired.
2575
- * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
2576
- * @throws {InvalidRequirementsError} If the requirements are invalid.
2577
- * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
2578
- */
2579
- async isInvitationValid(invitation) {
2580
- const template = new Template(await this.state.getTemplate(invitation.templateIdentifier));
2581
- try {
2582
- InvitationBuilder.fromInvitation(invitation).validate(template.getTemplate());
2583
- return true;
2584
- } catch {
2585
- return false;
2586
- }
2587
- }
2588
- /**
2589
2543
  * Lists available roles for the given invitation.
2590
2544
  *
2591
2545
  * @param {XOInvitation} invitation - The invitation to examine.
2592
2546
  * @returns {Promise<string[]>} The list of roles that still require data.
2593
2547
  * @throws {TemplateNotFoundError} If the template is not found.
2594
- * @throws {ActionNotFoundError} If the action is not found.
2548
+ * @throws {TemplateActionNotFoundError} If the action is not found.
2595
2549
  */
2596
2550
  async listAvailableRoles(invitation) {
2597
2551
  return listAvailableRolesForInvitation(invitation, new Template(await this.getTemplateOrThrow(invitation.templateIdentifier)).getActionOrThrow(invitation.actionIdentifier));
@@ -2610,12 +2564,14 @@ var Engine = class Engine {
2610
2564
  /**
2611
2565
  * Lists missing requirements for the provided invitation.
2612
2566
  *
2613
- * @param {XOInvitation} invitation - The invitation to analyze.
2567
+ * @param {string} invitationIdentifier - The identifier of the invitation to analyze. The invitation must already exist in the store.
2614
2568
  * @returns {Promise<XOInvitationRequirements>} The missing requirements.
2569
+ * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
2615
2570
  */
2616
- async listMissingRequirements(invitation) {
2617
- const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);
2618
- return listMissingRequirements(invitation, templateFromStore, new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier));
2571
+ async listMissingRequirements(invitationIdentifier) {
2572
+ const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
2573
+ const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
2574
+ return listMissingRequirements(invitationFromStore, template, new Template(template).getActionOrThrow(invitationFromStore.actionIdentifier));
2619
2575
  }
2620
2576
  /**
2621
2577
  * Lists all the unspent outputs.
@@ -2642,7 +2598,7 @@ var Engine = class Engine {
2642
2598
  const sourceOutputIdentifier = options?.outputIdentifier ?? this.defaultOutputIdentifier;
2643
2599
  const rawSourceTemplate = await this.state.getTemplate(sourceTemplateIdentifier);
2644
2600
  if (rawSourceTemplate === void 0) throw new TemplateNotFoundError(sourceTemplateIdentifier);
2645
- new Template(rawSourceTemplate).getOutput(sourceOutputIdentifier);
2601
+ new Template(rawSourceTemplate).getOutputOrThrow(sourceOutputIdentifier);
2646
2602
  const scriptHashDataList = await this.state.listScriptHashData({ templateIdentifier: sourceTemplateIdentifier });
2647
2603
  const unspentOutputs = [];
2648
2604
  for (const scriptHashData of scriptHashDataList) {
@@ -2706,21 +2662,18 @@ var Engine = class Engine {
2706
2662
  * @throws {Error} If any required template, output, or configuration is not found, or if compilation fails.
2707
2663
  */
2708
2664
  async generateLockingBytecode(templateIdentifier, outputIdentifier, roleIdentifier) {
2709
- const template = new Template(await this.state.getTemplate(templateIdentifier));
2710
- const output = template.getOutput(outputIdentifier);
2711
- const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);
2712
- if (!output.lockingScript) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2713
- template.validateLockingScript(lockingScriptForOutput, output.lockingScript);
2714
- const selectedRoleId = roleIdentifier ?? template.getFirstRole(output.lockingScript)[0];
2715
- if (roleIdentifier) template.getRole(output.lockingScript, roleIdentifier);
2665
+ const template = new Template(await this.getTemplateOrThrow(templateIdentifier));
2666
+ const output = template.getOutputOrThrow(outputIdentifier);
2667
+ const lockingScriptForOutput = template.getLockingScriptForOutputOrThrow(outputIdentifier);
2668
+ const selectedRoleId = roleIdentifier ?? template.getFirstRoleOrThrow(output.lockingScript)[0];
2669
+ if (roleIdentifier) template.getRoleOrThrow(output.lockingScript, roleIdentifier);
2716
2670
  const finalRoleIdentifier = selectedRoleId;
2717
2671
  const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), finalRoleIdentifier);
2718
2672
  const scripts = scriptsForLibauthCompiler(template.getTemplate());
2719
2673
  const variables = assignTypeToVariablesForLibauthCompiler(template.getTemplate());
2720
- if (lockingScriptForOutput.unlockingBytecode === void 0 || lockingScriptForOutput.lockingBytecode === void 0) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2674
+ if (lockingScriptForOutput.unlockingBytecode === void 0 || lockingScriptForOutput.lockingBytecode === void 0) throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);
2721
2675
  const unlockingScripts = { [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode };
2722
2676
  const { lockingType } = lockingScriptForOutput;
2723
- if (!lockingType) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2724
2677
  const compiler = createCompilerBch({
2725
2678
  entityOwnership,
2726
2679
  scripts,
@@ -2740,7 +2693,7 @@ var Engine = class Engine {
2740
2693
  };
2741
2694
  break;
2742
2695
  }
2743
- default: throw new LockingScriptTypeNotFoundError(output.lockingScript ?? outputIdentifier);
2696
+ default: throw new TemplateLockingScriptTypeNotFoundError(output.lockingScript ?? outputIdentifier);
2744
2697
  }
2745
2698
  if (!lockingData) throw new LockingDataNotFoundError();
2746
2699
  const scriptId = lockingScriptForOutput.lockingBytecode;
@@ -2764,7 +2717,7 @@ var Engine = class Engine {
2764
2717
  outputIdentifier,
2765
2718
  roleIdentifier: finalRoleIdentifier
2766
2719
  });
2767
- await this.updateUnspentOutputsForScriptHashInStore(lockingBytecode);
2720
+ await this.updateUnspentOutputsForScriptHashInStore(scriptHash);
2768
2721
  return lockingBytecode;
2769
2722
  }
2770
2723
  /**
@@ -2854,6 +2807,42 @@ var Engine = class Engine {
2854
2807
  return inputsForReservation;
2855
2808
  }
2856
2809
  /**
2810
+ * Applies an invitation append operation to a stored invitation. Signs a new commit using the
2811
+ * engine's own entity, persists the updated invitation to the store, and returns the result.
2812
+ *
2813
+ * This is the shared implementation used by both the public {@link appendInvitation} method
2814
+ * and internal callers that already hold the stored invitation in memory.
2815
+ *
2816
+ * @param {StoredInvitation} storedInvitation - The stored invitation to append to.
2817
+ * @param {AppendInvitationParameters} params - The parameters to append.
2818
+ * @returns {Promise<XOInvitation>} The updated invitation after the new commit is applied.
2819
+ */
2820
+ async applyInvitationAppend(storedInvitation, params) {
2821
+ const rootCommitIdentifier = findRootCommitIdentifierInInvitation(storedInvitation, storedInvitation.entityIdentifier);
2822
+ if (rootCommitIdentifier === void 0) throw new RootCommitNotFoundError(storedInvitation.entityIdentifier);
2823
+ if (params.outputs !== void 0) for (const output of params.outputs) {
2824
+ if (output.mergesWith !== void 0 || output.roleIdentifier !== void 0 || output.lockingBytecode !== void 0) continue;
2825
+ output.lockingBytecode = hexToBin(await this.generateLockingBytecodeForDefaultParameters());
2826
+ }
2827
+ const invitationBuilder = InvitationBuilder.fromInvitation(storedInvitation);
2828
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2829
+ invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),
2830
+ invitationIdentifier: invitationBuilder.invitationIdentifier,
2831
+ rootCommitIdentifier,
2832
+ templateIdentifier: invitationBuilder.templateIdentifier,
2833
+ actionIdentifier: invitationBuilder.actionIdentifier
2834
+ });
2835
+ invitationBuilder.addCommit(signedCommit);
2836
+ const inputsForReservation = await this.findOwnResources(params.inputs ?? []);
2837
+ if (inputsForReservation.length > 0) await this.reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);
2838
+ const updatedInvitation = invitationBuilder.build();
2839
+ await this.state.storeInvitation(updatedInvitation.invitationIdentifier, {
2840
+ ...updatedInvitation,
2841
+ entityIdentifier: storedInvitation.entityIdentifier
2842
+ });
2843
+ return updatedInvitation;
2844
+ }
2845
+ /**
2857
2846
  * Reserves utxos and store information in the storage.
2858
2847
  *
2859
2848
  * @param {XOInvitationInput[]} inputs - The inputs to reserve.
@@ -2874,5 +2863,5 @@ var Engine = class Engine {
2874
2863
  };
2875
2864
 
2876
2865
  //#endregion
2877
- export { ActionNotFoundError, BlockchainMonitor, CashAssemblyCompilationFailedError, CashAssemblyVariableNotIntegerError, CircularMergeReferenceError, CommitEntityIdentifierNotFoundError, CommitNotFoundInInvitationError, CommitNotSignedError, CreatedByIdentifierAlreadySetError, CreatedByIdentifierSignatureAlreadySetError, DataNotFoundError, DuplicateTransactionIndexError, DuplicateTransactionLocktimeError, DuplicateTransactionVersionError, ElectrumClientNotFoundError, Engine, InvalidActionError, InvalidCommitSignaturesError, InvalidDataTypeError, InvalidDerivativeIndexTypeError, InvalidEntityIdentifierError, InvalidInputError, InvalidInvitationError, InvalidLockingScriptTypeError, InvalidLockingTypeError, InvalidRequirementsError, InvalidRoleError, InvalidTemplateOutputSatoshisTypeError, InvalidVariableDefinitionError, InvalidVariableTypeError, InvitationAlreadyAcceptedError, InvitationBuilder, InvitationCreatedInFutureError, InvitationExpiredError, InvitationNotAcceptedError, InvitationNotFoundInStoreError, ItemNotFoundInCommitError, LockingBytecodeGenerationFailedError, LockingBytecodeNotFoundForOutputError, LockingDataNotFoundError, LockingScriptNotFoundError, LockingScriptTypeNotFoundError, MergedCommitNotFoundError, MergesWithCommitNotFoundError, MissingRequiredDataError, MissingRequiredFieldError, MissingRequiredRoleForEntityError, MissingRequiredSignatureByEntityError, MissingRequiredVariableError, MultipleRolesForStartingActionError, NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError, OutputLockingScriptNotFoundError, OutputNotFoundError, ParentCommitNotFoundError, ReserveResourcesFailedError, RoleAlreadyAcceptedByAnotherEntityError, RoleCannotStartActionError, RoleNotAvailableToBeAcceptedError, RoleNotDefinedForActionError, RoleNotFoundError, RootCommitNotFoundError, ScriptHashDataNotFoundError, ScriptNotFoundError, SignatureVerificationFailedError, StartingActionNotFoundError, Template, TemplateIdentifierMismatchError, TemplateNotFoundError, TransactionGenerationFailedError, TransactionNotFoundError, UnknownVariableError, UnlockingScriptNotFoundError, UnspentOutputNotFoundError, VariableRequiredError, VariableValidationFailedError, assignTypeToVariablesForLibauthCompiler, compileCashAssemblyEvaluations, compileCashAssemblyString, convertCommitVariablesIntoObject, convertXOLockingTypeToLibauth, createLibauthCompilerDataFromUnspentOutput, decodeCompiledCashAssemblyEvaluation, entityOwnershipForLibauthCompiler, extractCashAssemblyEvaluations, extractVariablesFromEvaluations, findRootCommitIdentifierInInvitation, generateCashAssemblyBytecode, generateCommitIdentifier, generateTemplateIdentifier, hasInvitationExpired, isCashAssemblyExpression, listAvailableRolesForInvitation, listMissingRequirements, listPopulatedRequirementsInInvitation, listRequirementsFromTemplate, mergeInvitationCommits, parseTemplate, scriptsForLibauthCompiler, updateUnspentOutputsForScriptHashInStore, validateInvitationCommits, validateInvitationEntities, validateRoleRequirements };
2866
+ export { BlockchainMonitor, CashAssemblyCompilationFailedError, CashAssemblyVariableNotIntegerError, CircularMergeReferenceError, CommitEntityIdentifierNotFoundError, CommitNotFoundInInvitationError, CommitNotSignedError, CreatedByIdentifierAlreadySetError, CreatedByIdentifierSignatureAlreadySetError, DataNotFoundError, DuplicateTransactionIndexError, DuplicateTransactionLocktimeError, DuplicateTransactionVersionError, ElectrumClientNotFoundError, Engine, InvalidActionError, InvalidCommitSignaturesError, InvalidDataTypeError, InvalidDerivativeIndexTypeError, InvalidEntityIdentifierError, InvalidInputError, InvalidInvitationError, InvalidLockingScriptTypeError, InvalidLockingTypeError, InvalidRequirementsError, InvalidRoleError, InvalidTemplateOutputSatoshisTypeError, InvalidVariableDefinitionError, InvalidVariableTypeError, InvitationAlreadyAcceptedError, InvitationBuilder, InvitationCreatedInFutureError, InvitationExpiredError, InvitationNotAcceptedError, InvitationNotFoundInStoreError, InvitationTemplateMismatchError, ItemNotFoundInCommitError, LockingBytecodeGenerationFailedError, LockingBytecodeNotFoundForOutputError, LockingDataNotFoundError, MergedCommitNotFoundError, MergesWithCommitNotFoundError, MissingRequiredDataError, MissingRequiredFieldError, MissingRequiredRoleForEntityError, MissingRequiredSignatureByEntityError, MissingRequiredVariableError, MultipleRolesForStartingActionError, NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError, ParentCommitNotFoundError, ReserveResourcesFailedError, RoleAlreadyAcceptedByAnotherEntityError, RoleCannotStartActionError, RoleNotAvailableToBeAcceptedError, RoleNotDefinedForActionError, RootCommitNotFoundError, ScriptHashDataNotFoundError, ScriptNotFoundError, SignatureVerificationFailedError, StartingActionNotFoundError, Template, TemplateActionNotFoundError, TemplateLockingScriptInOutputNotFoundError, TemplateLockingScriptNotFoundError, TemplateLockingScriptRoleNotFoundError, TemplateLockingScriptTypeNotFoundError, TemplateNotFoundError, TemplateOutputNotFoundError, TemplateTransactionNotFoundError, TransactionGenerationFailedError, UnknownVariableError, UnlockingScriptNotFoundError, UnspentOutputNotFoundError, VariableRequiredError, VariableValidationFailedError, assignTypeToVariablesForLibauthCompiler, compileCashAssemblyEvaluations, compileCashAssemblyString, convertCommitVariablesIntoObject, convertXOLockingTypeToLibauth, createLibauthCompilerDataFromUnspentOutput, decodeCompiledCashAssemblyEvaluation, entityOwnershipForLibauthCompiler, extractCashAssemblyEvaluations, extractVariablesFromEvaluations, findRootCommitIdentifierInInvitation, generateCashAssemblyBytecode, generateCommitIdentifier, generateTemplateIdentifier, hasInvitationExpired, isCashAssemblyExpression, listAvailableRolesForInvitation, listMissingRequirements, listPopulatedRequirementsInInvitation, listRequirementsFromTemplate, mergeInvitationCommits, parseTemplate, scriptsForLibauthCompiler, updateUnspentOutputsForScriptHashInStore, validateInvitationCommits, validateInvitationEntities, validateRoleRequirements };
2878
2867
  //# sourceMappingURL=index.mjs.map