@xo-cash/engine 0.0.1-development.15965991683 → 0.0.1

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,12 +1,11 @@
1
- import { binToHex, createCompilerBch, encodeTransaction, generateRandomBytes, generateTransaction, hashTransaction, hexToBin } from "@bitauth/libauth";
2
- import { Crypto, buildInvitationCommitSigningPayload, computeAccountHash, convertMnemonicToSeedBytes, verifyInvitationCommitSignature } from "@xo-cash/crypto";
3
- import { COMMIT_IDENTIFIER_BYTE_LENGTH, ExtendedPublicKey, INVITATION_IDENTIFIER_BYTE_LENGTH, TemplateIdentifier } from "@xo-cash/primitives";
4
- import { InvitationNotFoundInStoreError, State, StorageType, TemplateNotFoundInStoreError, UnspentOutputNotFoundInStoreError, UnspentOutputStatus, createStorageAdapter } from "@xo-cash/state";
5
- import { compileCashAssemblyString, generateTemplateIdentifier, generateTemplateIdentifier as generateTemplateIdentifier$1, isCashAssemblyExpression, parseTemplate, parseTemplate as parseTemplate$1, scriptToScriptHash } from "@xo-cash/utils";
1
+ import { bigIntToVmNumber, binToHex, binToUtf8, createCompilerBch, encodeTransaction, generateRandomBytes, generateTransaction, hashTransaction, hexToBin, sha256, utf8ToBin, vmNumberToBigInt } from "@bitauth/libauth";
2
+ import { Crypto, buildInvitationCommitSigningPayload, convertMnemonicToSeedBytes, verifySchnorrSignature } from "@xo-cash/crypto";
3
+ import { State, StorageType, UnspentOutputStatus, createStorageAdapter } from "@xo-cash/state";
4
+ import { generateTemplateIdentifier, generateTemplateIdentifier as generateTemplateIdentifier$1, parseTemplate, parseTemplate as parseTemplate$1, scriptToScriptHash } from "@xo-cash/utils";
6
5
  import { broadcastTransaction, electrumClients, electrumEvents, getChainStatus, initializeElectrumApplication, stopElectrumNetwork } from "@electrum-cash/application";
7
6
  import { fetchScriptHashUnspentTransactionOutputs, subscribeToScriptHashUpdates } from "@electrum-cash/protocol";
8
7
  import { electrumServers } from "@electrum-cash/servers";
9
- import { XOTemplateLockingTypes } from "@xo-cash/types";
8
+ import { PublicKey } from "@xo-cash/primitives";
10
9
 
11
10
  //#region source/errors.ts
12
11
  /**
@@ -26,6 +25,14 @@ var TemplateOutputNotFoundError = class extends Error {
26
25
  }
27
26
  };
28
27
  /**
28
+ * Error thrown when a template is not found.
29
+ */
30
+ var TemplateNotFoundError = class extends Error {
31
+ constructor(templateIdentifier) {
32
+ super(`Template not found, templateIdentifier "${templateIdentifier}"`);
33
+ }
34
+ };
35
+ /**
29
36
  * Error thrown when a locking script is not found in the template.
30
37
  */
31
38
  var TemplateLockingScriptNotFoundError = class extends Error {
@@ -51,27 +58,29 @@ var UnlockingScriptNotFoundError = class extends Error {
51
58
  }
52
59
  };
53
60
  /**
54
- * Error thrown when a transaction is not found in the template.
61
+ * Error thrown when a script is not found in the template.
55
62
  */
56
- var TemplateTransactionNotFoundError = class extends Error {
57
- constructor(transactionIdentifier) {
58
- super(`Template transaction not found, transactionIdentifier "${transactionIdentifier}"`);
63
+ var ScriptNotFoundError = class extends Error {
64
+ constructor(scriptIdentifier) {
65
+ const defaultMessage = "Script not found in template";
66
+ super(scriptIdentifier ? `${defaultMessage}: scriptIdentifier "${scriptIdentifier}"` : defaultMessage);
59
67
  }
60
68
  };
61
69
  /**
62
- * Error thrown when a role is not found on a locking script.
70
+ * Error thrown when a starting action is not found in the template.
63
71
  */
64
- var TemplateLockingScriptRoleNotFoundError = class extends Error {
65
- constructor(lockingScriptIdentifier, roleIdentifier) {
66
- super(`Template locking script role not found, lockingScriptIdentifier "${lockingScriptIdentifier}", roleIdentifier "${roleIdentifier}"`);
72
+ var StartingActionNotFoundError = class extends Error {
73
+ constructor(templateIdentifier) {
74
+ const defaultMessage = "Starting action not found in template";
75
+ super(templateIdentifier ? `${defaultMessage}: templateIdentifier "${templateIdentifier}"` : defaultMessage);
67
76
  }
68
77
  };
69
78
  /**
70
- * Error thrown when an output does not have a locking script.
79
+ * Error thrown when a transaction is not found in the template.
71
80
  */
72
- var TemplateLockingScriptInOutputNotFoundError = class extends Error {
73
- constructor(outputIdentifier) {
74
- super(`Template locking script in output not found, outputIdentifier "${outputIdentifier}"`);
81
+ var TemplateTransactionNotFoundError = class extends Error {
82
+ constructor(transactionIdentifier) {
83
+ super(`Template transaction not found, transactionIdentifier "${transactionIdentifier}"`);
75
84
  }
76
85
  };
77
86
  /**
@@ -132,6 +141,33 @@ var InvalidCommitSignaturesError = class extends Error {
132
141
  }
133
142
  };
134
143
  /**
144
+ * Error thrown when an invitation is not found in the store.
145
+ */
146
+ var InvitationNotFoundInStoreError = class extends Error {
147
+ constructor(invitationIdentifier) {
148
+ const defaultMessage = "Invitation not found in store";
149
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
150
+ }
151
+ };
152
+ /**
153
+ * Error thrown when an invitation has already been accepted.
154
+ */
155
+ var InvitationAlreadyAcceptedError = class extends Error {
156
+ constructor(invitationIdentifier) {
157
+ const defaultMessage = "Invitation already accepted";
158
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
159
+ }
160
+ };
161
+ /**
162
+ * Error thrown when an invitation was created in the future.
163
+ */
164
+ var InvitationCreatedInFutureError = class extends Error {
165
+ constructor(invitationIdentifier) {
166
+ const defaultMessage = "Invitation created in the future";
167
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
168
+ }
169
+ };
170
+ /**
135
171
  * Error thrown when an invitation has expired.
136
172
  */
137
173
  var InvitationExpiredError = class extends Error {
@@ -141,6 +177,24 @@ var InvitationExpiredError = class extends Error {
141
177
  }
142
178
  };
143
179
  /**
180
+ * Error thrown when an invitation has not been accepted.
181
+ */
182
+ var InvitationNotAcceptedError = class extends Error {
183
+ constructor(invitationIdentifier) {
184
+ const defaultMessage = "Invitation not accepted";
185
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
186
+ }
187
+ };
188
+ /**
189
+ * Error thrown when an invitation is invalid.
190
+ */
191
+ var InvalidInvitationError = class extends Error {
192
+ constructor(invitationIdentifier) {
193
+ const defaultMessage = "Invalid invitation";
194
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
195
+ }
196
+ };
197
+ /**
144
198
  * Error thrown when a merged commit is not found.
145
199
  */
146
200
  var MergedCommitNotFoundError = class extends Error {
@@ -158,27 +212,18 @@ var ScriptHashDataNotFoundError = class extends Error {
158
212
  }
159
213
  };
160
214
  /**
161
- * Error thrown when the entity identifier is not found in the invitation.
162
- */
163
- var EntityIdentifierNotFoundInInvitationError = class extends Error {
164
- constructor(invitationIdentifier) {
165
- const defaultMessage = "Entity identifier not found in invitation";
166
- super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
167
- }
168
- };
169
- /**
170
215
  * Error thrown when the root commit for an entity cannot be found in the invitation.
171
216
  */
172
- var RootCommitNotFoundInInvitationError = class extends Error {
173
- constructor(invitationIdentifier) {
217
+ var RootCommitNotFoundError = class extends Error {
218
+ constructor(entityIdentifier) {
174
219
  const defaultMessage = "Root commit not found in invitation";
175
- super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
220
+ super(entityIdentifier ? `${defaultMessage}: entityIdentifier "${entityIdentifier}"` : defaultMessage);
176
221
  }
177
222
  };
178
223
  /**
179
224
  * Error thrown when a parent commit is not found.
180
225
  */
181
- var ParentCommitNotFoundInInvitationError = class extends Error {
226
+ var ParentCommitNotFoundError = class extends Error {
182
227
  constructor(parentCommitIdentifier, commitIdentifier) {
183
228
  super(`Parent commit not found: ${parentCommitIdentifier} (referenced by commit ${commitIdentifier})`);
184
229
  }
@@ -251,6 +296,171 @@ var InvitationTemplateMismatchError = class extends Error {
251
296
  }
252
297
  };
253
298
  /**
299
+ * Error thrown when an unspent output is not found.
300
+ */
301
+ var UnspentOutputNotFoundError = class extends Error {
302
+ constructor(outpointIdentifier) {
303
+ const defaultMessage = "Unspent output not found";
304
+ super(outpointIdentifier ? `${defaultMessage}: outpointIdentifier "${outpointIdentifier}"` : defaultMessage);
305
+ }
306
+ };
307
+ /**
308
+ * Error thrown when a role is invalid.
309
+ */
310
+ var InvalidRoleError = class extends Error {
311
+ constructor(roleIdentifier) {
312
+ const defaultMessage = "Invalid role";
313
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
314
+ }
315
+ };
316
+ /**
317
+ * Error thrown when there are multiple roles for the starting action.
318
+ */
319
+ var MultipleRolesForStartingActionError = class extends Error {
320
+ constructor(actionIdentifier) {
321
+ const defaultMessage = "Multiple roles for starting action";
322
+ super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
323
+ }
324
+ };
325
+ /**
326
+ * Error thrown when no role is specified and multiple roles are available to be accepted.
327
+ */
328
+ var NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError = class extends Error {
329
+ constructor() {
330
+ super("No role specified and multiple roles available to be accepted");
331
+ }
332
+ };
333
+ /**
334
+ * Error thrown when a role has already been accepted by another entity.
335
+ */
336
+ var RoleAlreadyAcceptedByAnotherEntityError = class extends Error {
337
+ constructor(roleIdentifier) {
338
+ const defaultMessage = "Role already accepted by another entity";
339
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
340
+ }
341
+ };
342
+ /**
343
+ * Error thrown when a role cannot start an action.
344
+ */
345
+ var RoleCannotStartActionError = class extends Error {
346
+ constructor(roleIdentifier, actionIdentifier) {
347
+ const defaultMessage = "Role cannot start action";
348
+ if (roleIdentifier && actionIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", actionIdentifier "${actionIdentifier}"`);
349
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
350
+ else if (actionIdentifier) super(`${defaultMessage}: actionIdentifier "${actionIdentifier}"`);
351
+ else super(defaultMessage);
352
+ }
353
+ };
354
+ /**
355
+ * Error thrown when a role is not available to be accepted.
356
+ */
357
+ var RoleNotAvailableToBeAcceptedError = class extends Error {
358
+ constructor(roleIdentifier) {
359
+ const defaultMessage = "Role not available to be accepted";
360
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
361
+ }
362
+ };
363
+ /**
364
+ * Error thrown when a role is not defined for an action.
365
+ */
366
+ var RoleNotDefinedForActionError = class extends Error {
367
+ constructor(roleIdentifier, actionIdentifier) {
368
+ const defaultMessage = "Role not defined for action";
369
+ if (roleIdentifier && actionIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", actionIdentifier "${actionIdentifier}"`);
370
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
371
+ else if (actionIdentifier) super(`${defaultMessage}: actionIdentifier "${actionIdentifier}"`);
372
+ else super(defaultMessage);
373
+ }
374
+ };
375
+ /**
376
+ * Error thrown when a role is not found.
377
+ */
378
+ var TemplateLockingScriptRoleNotFoundError = class extends Error {
379
+ constructor(lockingScriptIdentifier, roleIdentifier) {
380
+ super(`Template locking script role not found, lockingScriptIdentifier "${lockingScriptIdentifier}", roleIdentifier "${roleIdentifier}"`);
381
+ }
382
+ };
383
+ /**
384
+ * Error thrown when a data type is invalid.
385
+ */
386
+ var InvalidDataTypeError = class extends Error {
387
+ constructor() {
388
+ super("Invalid data type");
389
+ }
390
+ };
391
+ /**
392
+ * Error thrown when a variable type is invalid.
393
+ */
394
+ var InvalidVariableTypeError = class extends Error {
395
+ constructor(variableKey, expectedType, actualType) {
396
+ super(`Invalid variable type: variableKey "${variableKey}", expected ${expectedType}, got ${actualType}`);
397
+ }
398
+ };
399
+ /**
400
+ * Error thrown when a required variable is missing.
401
+ */
402
+ var MissingRequiredVariableError = class extends Error {
403
+ constructor(variableNames) {
404
+ const defaultMessage = "Missing required variable";
405
+ if (variableNames && variableNames.length > 0) super(`${defaultMessage}: variableNames [${variableNames.join(", ")}]`);
406
+ else super(defaultMessage);
407
+ }
408
+ };
409
+ /**
410
+ * Error thrown when an unknown variable is provided.
411
+ */
412
+ var UnknownVariableError = class extends Error {
413
+ constructor(variableKey) {
414
+ const defaultMessage = "Unknown variable provided";
415
+ super(variableKey ? `${defaultMessage}: variableKey "${variableKey}"` : defaultMessage);
416
+ }
417
+ };
418
+ /**
419
+ * Error thrown when a variable is required but not provided.
420
+ */
421
+ var VariableRequiredError = class extends Error {
422
+ constructor(variableKey) {
423
+ const defaultMessage = "Variable required";
424
+ super(variableKey ? `${defaultMessage}: variableKey "${variableKey}"` : defaultMessage);
425
+ }
426
+ };
427
+ /**
428
+ * Error thrown when a number variable value is not a valid integer for CashAssembly compilation.
429
+ */
430
+ var CashAssemblyVariableNotIntegerError = class extends Error {
431
+ constructor(variableName, value) {
432
+ super(`CashAssembly variable value is not a valid integer: variableName "${variableName}", got ${value}`);
433
+ }
434
+ };
435
+ /**
436
+ * Error thrown when variable validation fails.
437
+ */
438
+ var VariableValidationFailedError = class extends Error {
439
+ constructor(variableNames) {
440
+ const defaultMessage = "Variable validation failed";
441
+ if (variableNames && variableNames.length > 0) super(`${defaultMessage}: variableNames [${variableNames.join(", ")}]`);
442
+ else super(defaultMessage);
443
+ }
444
+ };
445
+ /**
446
+ * Error thrown when an action is invalid for an invitation.
447
+ */
448
+ var InvalidActionError = class extends Error {
449
+ constructor(actionIdentifier) {
450
+ const defaultMessage = "Invalid action for invitation";
451
+ super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
452
+ }
453
+ };
454
+ /**
455
+ * Error thrown when cash assembly compilation fails.
456
+ */
457
+ var CashAssemblyCompilationFailedError = class extends Error {
458
+ constructor(message) {
459
+ const defaultMessage = "Cash assembly compilation failed";
460
+ super(message ? `${defaultMessage}: ${message}` : defaultMessage);
461
+ }
462
+ };
463
+ /**
254
464
  * Error thrown when locking bytecode generation fails.
255
465
  */
256
466
  var LockingBytecodeGenerationFailedError = class extends Error {
@@ -275,6 +485,30 @@ var TransactionGenerationFailedError = class extends Error {
275
485
  }
276
486
  };
277
487
  /**
488
+ * Error thrown when the created by identifier is already set.
489
+ */
490
+ var CreatedByIdentifierAlreadySetError = class extends Error {
491
+ constructor() {
492
+ super("Created by identifier already set");
493
+ }
494
+ };
495
+ /**
496
+ * Error thrown when the created by identifier signature is already set.
497
+ */
498
+ var CreatedByIdentifierSignatureAlreadySetError = class extends Error {
499
+ constructor() {
500
+ super("Created by identifier signature already set");
501
+ }
502
+ };
503
+ /**
504
+ * Error thrown when data is not found in the template.
505
+ */
506
+ var DataNotFoundError = class extends Error {
507
+ constructor() {
508
+ super("Data not found in template");
509
+ }
510
+ };
511
+ /**
278
512
  * Error thrown when input is invalid.
279
513
  */
280
514
  var InvalidInputError = class extends Error {
@@ -283,6 +517,60 @@ var InvalidInputError = class extends Error {
283
517
  }
284
518
  };
285
519
  /**
520
+ * Error thrown when required data is missing.
521
+ */
522
+ var MissingRequiredDataError = class extends Error {
523
+ constructor() {
524
+ super("Missing required data");
525
+ }
526
+ };
527
+ /**
528
+ * Error thrown when a required field is missing.
529
+ */
530
+ var MissingRequiredFieldError = class extends Error {
531
+ constructor(fieldName) {
532
+ const defaultMessage = "Missing required field";
533
+ super(fieldName ? `${defaultMessage}: fieldName "${fieldName}"` : defaultMessage);
534
+ }
535
+ };
536
+ /**
537
+ * Error thrown when a required role for an entity is missing.
538
+ */
539
+ var MissingRequiredRoleForEntityError = class extends Error {
540
+ constructor(roleIdentifier, entityIdentifier) {
541
+ const defaultMessage = "Missing required role for entity";
542
+ if (roleIdentifier && entityIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", entityIdentifier "${entityIdentifier}"`);
543
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
544
+ else if (entityIdentifier) super(`${defaultMessage}: entityIdentifier "${entityIdentifier}"`);
545
+ else super(defaultMessage);
546
+ }
547
+ };
548
+ /**
549
+ * Error thrown when a required signature by an entity is missing.
550
+ */
551
+ var MissingRequiredSignatureByEntityError = class extends Error {
552
+ constructor(entityIdentifier) {
553
+ const defaultMessage = "Missing required signature by entity";
554
+ super(entityIdentifier ? `${defaultMessage}: entityIdentifier "${entityIdentifier}"` : defaultMessage);
555
+ }
556
+ };
557
+ /**
558
+ * Error thrown when resource reservation fails.
559
+ */
560
+ var ReserveResourcesFailedError = class extends Error {
561
+ constructor() {
562
+ super("Failed to reserve resources");
563
+ }
564
+ };
565
+ /**
566
+ * Error thrown when signature verification fails.
567
+ */
568
+ var SignatureVerificationFailedError = class extends Error {
569
+ constructor() {
570
+ super("Signature verification failed");
571
+ }
572
+ };
573
+ /**
286
574
  * Error thrown when a variable definition is invalid.
287
575
  */
288
576
  var InvalidVariableDefinitionError = class extends Error {
@@ -291,6 +579,14 @@ var InvalidVariableDefinitionError = class extends Error {
291
579
  }
292
580
  };
293
581
  /**
582
+ * Error thrown when an output does not have a locking script.
583
+ */
584
+ var TemplateLockingScriptInOutputNotFoundError = class extends Error {
585
+ constructor(outputIdentifier) {
586
+ super(`Template locking script in output not found, outputIdentifier "${outputIdentifier}"`);
587
+ }
588
+ };
589
+ /**
294
590
  * Error thrown when a locking script has an invalid type.
295
591
  */
296
592
  var InvalidLockingScriptTypeError = class extends Error {
@@ -307,37 +603,165 @@ var InvalidLockingTypeError = class extends Error {
307
603
  }
308
604
  };
309
605
  /**
310
- * Error thrown when an electrum client is not found.
606
+ * Error thrown when a derivative index has an invalid type.
311
607
  */
312
- var ElectrumClientNotFoundError = class extends Error {
313
- constructor() {
314
- super("No electrum client found");
608
+ var InvalidDerivativeIndexTypeError = class extends Error {
609
+ constructor(expectedType, actualType) {
610
+ super(`Invalid derivativeIndex type: expected ${expectedType}, got ${actualType}`);
315
611
  }
316
612
  };
317
613
  /**
318
- * Error thrown when fallback locking parameters are missing for locking bytecode generation.
614
+ * Error thrown when a template output valueSatoshis has an invalid type for CashAssembly expression.
319
615
  */
320
- var FallbackLockingParametersMissingError = class extends Error {
321
- constructor() {
322
- super("Fallback locking parameters are missing for locking bytecode generation. Call Engine.updateFallbackLockingParameters(...) when other lockingbytecode generation policies are unavailable.");
616
+ var InvalidTemplateOutputSatoshisTypeError = class extends Error {
617
+ constructor(actualType) {
618
+ super(`Template output valueSatoshis must be a string for CashAssembly expression, got ${actualType}`);
323
619
  }
324
620
  };
325
621
  /**
326
- * Error thrown when a derivative index is required for a p2pkh locking type.
622
+ * Error thrown when an electrum client is not found.
327
623
  */
328
- var P2PKHDerivativeIndexMissingError = class extends Error {
624
+ var ElectrumClientNotFoundError = class extends Error {
329
625
  constructor() {
330
- super("Derivative index is required for p2pkh locking type");
626
+ super("No electrum client found");
331
627
  }
332
628
  };
333
629
 
630
+ //#endregion
631
+ //#region source/defaults.ts
632
+ /**
633
+ * When an entity opts to participate in an invitation, it reserves resources (e.g., UTXOs)
634
+ * that would otherwise be available to other invitations. To prevent resources from remaining
635
+ * locked indefinitely, each reservation requires an expiration time, after which the resources
636
+ * can be released.
637
+ *
638
+ * By default, the expiration time is set to 1 hour.
639
+ */
640
+ const DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS = 3600 * 1e3;
641
+ /**
642
+ * The default storage backend is IndexedDB.
643
+ */
644
+ const DEFAULT_STORAGE_TYPE = StorageType.INDEXEDDB;
645
+ /**
646
+ * The default sequence number is 0, which disables relative locktime on the input.
647
+ */
648
+ const DEFAULT_SEQUENCE_NUMBER = 0;
649
+ /**
650
+ * The default locktime is 0, which means the transaction is valid in any block and has no absolute locktime constraint.
651
+ */
652
+ const DEFAULT_LOCKTIME = 0;
653
+ /**
654
+ * The default transaction version is 2.
655
+ */
656
+ const DEFAULT_VERSION = 2;
657
+ /**
658
+ * An empty unlocking bytecode used as a placeholder for inputs (unlockingBytecode) within an invitation.
659
+ * This placeholder is used when the entities responsible for signing those inputs
660
+ * have not yet provided their signatures for the resulting transaction.
661
+ *
662
+ * Using a placeholder unlocking bytecode enables the engine to construct transaction structures for the
663
+ * libauth compiler when working on template actions, even before all participant signatures are available.
664
+ * This is especially helpful when invitation commits are merged, as it allows the transaction to be built and it's
665
+ * parts can be validated before all unlocking scripts have been provided.
666
+ */
667
+ const PLACEHOLDER_UNLOCKING_BYTECODE = new Uint8Array(0);
668
+ /**
669
+ * The default electrum application identifier.
670
+ */
671
+ const DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER = "xo";
672
+ /**
673
+ * Detects whether a string is a pure CashAssembly expression.
674
+ *
675
+ * CashAssembly expressions look like `$(<variable>)` or `$(<a> <b>)`. This pattern checks
676
+ * that the entire string is one such expression and nothing else. It will not match if
677
+ * there is other text surrounding the expression.
678
+ *
679
+ * For example:
680
+ * `$(<fee>)` matches (a full expression)
681
+ * `OP_DUP $(<fee>)` does not match (extra text before it)
682
+ * `$()` does not match (empty expression)
683
+ */
684
+ const CASHASSEMBLY_EXPRESSION_PATTERN = /^\$\([^)]+\)$/;
685
+ /**
686
+ * Finds all CashAssembly evaluations embedded in a larger string.
687
+ *
688
+ * An evaluation looks like `$(...)`, for example `$(<fee>)` or `$(<a> <b>)`. This pattern
689
+ * locates every occurrence in the input and returns them all (global flag `g`).
690
+ * Empty evaluations `$()` are intentionally excluded because they reference no variables.
691
+ *
692
+ * For example, scanning `"OP_DUP <$(<pubkeyHash>)> OP_HASH160 $(<fee>)"` would return
693
+ * `['$(<pubkeyHash>)', '$(<fee>)']`.
694
+ */
695
+ const CASHASSEMBLY_EVALUATION_PATTERN = /\$\([^)]+\)/g;
696
+ /**
697
+ * Extracts variable names from angle-bracket references inside a CashAssembly evaluation.
698
+ *
699
+ * Inside an evaluation like `$(<pubkeyHash> <fee>)`, variables are referenced as `<name>`.
700
+ * This pattern captures the name between the brackets. The global flag `g` allows iterating
701
+ * over every variable reference in a single evaluation string.
702
+ *
703
+ * For example, running this against `$(<pubkeyHash> <fee>)` would return the variable names
704
+ * `["pubkeyHash", "fee"]`.
705
+ */
706
+ const CASHASSEMBLY_VARIABLE_PATTERN = /<([^>]+)>/g;
707
+ /**
708
+ * Identifies CashAssembly literal tokens that appear inside angle-bracket push statements.
709
+ *
710
+ * Inside an evaluation, not everything between `<` and `>` is a variable name. Literals are
711
+ * also valid push contents: numeric literals (e.g. `<0>`, `<32>`), hex literals (`<0x02>`),
712
+ * binary literals (`<0b1010>`), and string literals (`<"minting">`, `<'hello'>`). This pattern
713
+ * matches any captured token that starts with a digit or a quote character.
714
+ */
715
+ const CASHASSEMBLY_LITERAL_TOKEN_PATTERN = /^[0-9"']/;
716
+
334
717
  //#endregion
335
718
  //#region source/utils/libauth-utils.ts
336
719
  /**
720
+ * Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.
721
+ * Returns libauth result or error string.
722
+ *
723
+ * @param compiler - The libauth compiler.
724
+ * @param evaluation - The specific evaluation string to compile.
725
+ * @param variables - A record mapping variable names to their values.
726
+ * @returns Bytecode result object on success, otherwise an error string.
727
+ */
728
+ const generateCashAssemblyBytecode = (compiler, evaluation, variables) => {
729
+ const variableNames = extractVariablesFromEvaluations([evaluation]);
730
+ const missingVariables = variableNames.filter((name) => !Object.hasOwn(variables, name));
731
+ if (missingVariables.length > 0) throw new MissingRequiredVariableError(missingVariables);
732
+ const bytecode = {};
733
+ for (const variableName of variableNames) {
734
+ const value = variables[variableName];
735
+ if (!(value instanceof Uint8Array)) throw new InvalidVariableTypeError(variableName, "Uint8Array", typeof value);
736
+ bytecode[variableName] = value;
737
+ }
738
+ const compiledBytecode = compiler.generateBytecode({
739
+ data: { bytecode },
740
+ scriptId: evaluation
741
+ });
742
+ if (!compiledBytecode.success) throw new CashAssemblyCompilationFailedError("errors" in compiledBytecode ? JSON.stringify(compiledBytecode.errors) : JSON.stringify(compiledBytecode));
743
+ return compiledBytecode.bytecode;
744
+ };
745
+ /**
746
+ * Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.
747
+ *
748
+ * @param evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)'])
749
+ * @returns A Libauth compiler instance for use with these evaluations.
750
+ */
751
+ const compileCashAssemblyEvaluations = (evaluations) => {
752
+ const scripts = {};
753
+ for (const evaluation of evaluations) scripts[evaluation] = evaluation;
754
+ const variableNames = extractVariablesFromEvaluations(evaluations);
755
+ return createCompilerBch({
756
+ scripts,
757
+ variables: Object.fromEntries(variableNames.map((variableName) => [variableName, { type: "WalletData" }]))
758
+ });
759
+ };
760
+ /**
337
761
  * Creates a map of variable identifiers to role identifiers for the libauth compiler configuration.
338
762
  *
339
- * @param {XOTemplate} template - The template used to gather the variable identifiers.
340
- * @param {XOTemplateRoleIdentifier} role - The role identifier to assign to the variables.
763
+ * @param template - The template used to gather the variable identifiers.
764
+ * @param role - The role identifier to assign to the variables.
341
765
  * @returns {Record<string, string>} A map of variable identifiers to role identifiers.
342
766
  */
343
767
  const entityOwnershipForLibauthCompiler = (template, role) => {
@@ -349,7 +773,7 @@ const entityOwnershipForLibauthCompiler = (template, role) => {
349
773
  /**
350
774
  * Creates a map of script identifiers to script definitions for the libauth compiler configuration.
351
775
  *
352
- * @param {XOTemplate} template - The template used to gather the scripts.
776
+ * @param template - The template used to gather the scripts.
353
777
  * @returns {CompilerConfiguration['scripts']} A map of script identifiers to script definitions.
354
778
  */
355
779
  const scriptsForLibauthCompiler = (template) => {
@@ -361,8 +785,8 @@ const scriptsForLibauthCompiler = (template) => {
361
785
  /**
362
786
  * Converts template variables into libauth variables with types.
363
787
  *
364
- * @param {XOTemplate} template - The template to assign types to the variables.
365
- * @returns {CompilerConfiguration['variables']} Variables mapped for the libauth compiler.
788
+ * @param template - The template to assign types to the variables.
789
+ * @returns CompilerConfiguration['variables']
366
790
  */
367
791
  const assignTypeToVariablesForLibauthCompiler = (template) => {
368
792
  const variablesWithTypes = {};
@@ -371,6 +795,7 @@ const assignTypeToVariablesForLibauthCompiler = (template) => {
371
795
  if (!variableDefinition || typeof variableDefinition !== "object") throw new InvalidVariableDefinitionError(variableIdentifier);
372
796
  let variableType;
373
797
  if ("hint" in variableDefinition) if (variableDefinition.hint === "private_key") variableType = "Key";
798
+ else if (variableDefinition.hint === "script") variableType = "AddressData";
374
799
  else variableType = "WalletData";
375
800
  else variableType = "WalletData";
376
801
  variablesWithTypes[variableIdentifier] = {
@@ -391,8 +816,8 @@ const XO_LOCKING_TYPE_TO_LIBAUTH_MAP = {
391
816
  /**
392
817
  * Converts an XO template locking type to the corresponding libauth compiler locking script type.
393
818
  *
394
- * @param {XOTemplateLockingType} lockingType - The XO template locking type to convert.
395
- * @returns {NonNullable<CompilerConfiguration['lockingScriptTypes']>[string]} The corresponding libauth compiler locking script type.
819
+ * @param lockingType - The XO template locking type to convert.
820
+ * @returns The corresponding libauth compiler locking script type string.
396
821
  */
397
822
  const convertXOLockingTypeToLibauth = (lockingType) => {
398
823
  return XO_LOCKING_TYPE_TO_LIBAUTH_MAP[lockingType];
@@ -400,12 +825,17 @@ const convertXOLockingTypeToLibauth = (lockingType) => {
400
825
  /**
401
826
  * Creates the libauth compatible compiler data for a unspent output.
402
827
  *
403
- * @param {Template} template - The template used to generate the compiler data for.
404
- * @param {UnspentOutputData} unspentOutput - The unspent output to create the compiler data for.
405
- * @param {XOTemplateOutputIdentifier} outputIdentifier - The template output identifier for the unspent output.
406
- * @returns {Promise<{ compiler: CompilerBch; script: string; valueSatoshis: bigint; }>} The compiler data for the unspent output.
407
- */
408
- const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutput, outputIdentifier) => {
828
+ * @param template - The template used to generate the compiler data for.
829
+ * @param unspentOutput - The unspent output to create the compiler data for.
830
+ * @returns The compiler data for the unspent output.
831
+ * @returns {Promise<{
832
+ * compiler: CompilerBch;
833
+ * script: string;
834
+ * valueSatoshis: bigint;
835
+ * }>} The compiler data for the unspent output.
836
+ */
837
+ const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutput) => {
838
+ const { outputIdentifier } = unspentOutput;
409
839
  const output = template.getOutputOrThrow(outputIdentifier);
410
840
  const lockingScriptForOutput = template.getLockingScriptForOutputOrThrow(outputIdentifier);
411
841
  if (lockingScriptForOutput.lockingBytecode === void 0) throw new TemplateLockingScriptInOutputNotFoundError(outputIdentifier);
@@ -440,6 +870,151 @@ const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutpu
440
870
  };
441
871
  };
442
872
 
873
+ //#endregion
874
+ //#region source/utils/cashassembly.ts
875
+ /**
876
+ * Utilities for parsing, extracting, and compiling CashAssembly expressions.
877
+ *
878
+ * CashAssembly is the scripting language used by Bitauth templates to describe Bitcoin Cash
879
+ * locking and unlocking scripts.
880
+ *
881
+ * ## Syntax
882
+ *
883
+ * `<expression>` — a push statement. Compiles the contents and pushes the result onto the VM stack.
884
+ * `<someKey.public_key>` pushes the 33-byte compressed public key. `<1>` pushes the integer 1.
885
+ *
886
+ * `$(<expression>)` — an evaluation. Runs the inner script in the VM and inserts the top stack
887
+ * item as VM bytecode.
888
+ * `$(<someKey.public_key> OP_HASH160)` inserts the HASH160 of the public key.
889
+ *
890
+ * `<$(<expression>)>` — a push of an evaluation result. Combines the two above: evaluates first,
891
+ * then pushes. Example: P2PKH locking script:
892
+ * `OP_DUP OP_HASH160 <$(<someKey.public_key> OP_HASH160)> OP_EQUALVERIFY OP_CHECKSIG`.
893
+ *
894
+ * `variableId.operation` — a variable with a compiler-resolved operation. `someKey.public_key`
895
+ * produces the public key bytes. `someKey.schnorr_signature.all_outputs` produces a Schnorr
896
+ * signature.
897
+ *
898
+ * Opcodes (`OP_DUP`, `OP_HASH160`, etc.) are inserted as their bytecode equivalent directly.
899
+ *
900
+ * ## Name resolution priority
901
+ *
902
+ * When the compiler encounters an identifier it resolves it in this order:
903
+ * 1. Opcode — always wins. Naming a variable or script `OP_ADD` will not shadow it.
904
+ * 2. Variable — shadows scripts of the same name.
905
+ * 3. Script — the script's bytecode.
906
+ *
907
+ * NOTE: In future development of the XO, there will be XO_CODE taking the highest priority.
908
+ *
909
+ * @see playground/examples/cashassembly-evaluations.js for runnable examples covering all syntax forms,
910
+ * VM evaluation, and name resolution priority.
911
+ */
912
+ /**
913
+ * Checks if the expression is a CashAssembly expression.
914
+ *
915
+ * @param expression - The expression to check.
916
+ * @returns True if the expression is a CashAssembly expression, false otherwise.
917
+ */
918
+ const isCashAssemblyExpression = (expression) => {
919
+ return typeof expression === "string" && CASHASSEMBLY_EXPRESSION_PATTERN.test(expression);
920
+ };
921
+ /**
922
+ * Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.
923
+ *
924
+ * @param text - The input string to scan for CashAssembly evaluations.
925
+ * @returns An array of evaluation strings found in the input.
926
+ *
927
+ * @example
928
+ * extractCashAssemblyEvaluations("OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)");
929
+ * // returns ['$(<foo>)', '$(<bar>)']
930
+ */
931
+ const extractCashAssemblyEvaluations = (text) => {
932
+ return text.match(CASHASSEMBLY_EVALUATION_PATTERN) ?? [];
933
+ };
934
+ /**
935
+ * Extracts unique variable identifiers enclosed in angle brackets from each evaluation string.
936
+ *
937
+ * CashAssembly literal tokens such as hex bytes, numbers, and quoted strings are excluded.
938
+ * For example, `<0x02>` and `<"minting">` are not returned.
939
+ *
940
+ * @param evaluations - An array of evaluation strings from which to extract variable names.
941
+ * @returns An array of variable names
942
+ */
943
+ const extractVariablesFromEvaluations = (evaluations) => {
944
+ const uniqueVariables = /* @__PURE__ */ new Set();
945
+ for (const evaluation of evaluations) for (const match of evaluation.matchAll(CASHASSEMBLY_VARIABLE_PATTERN)) {
946
+ const extractedIdentifier = match[1];
947
+ if (CASHASSEMBLY_LITERAL_TOKEN_PATTERN.test(extractedIdentifier)) continue;
948
+ uniqueVariables.add(extractedIdentifier);
949
+ }
950
+ return [...uniqueVariables];
951
+ };
952
+ /**
953
+ * Converts a variable value to its byte representation.
954
+ *
955
+ * @param value - The variable value to convert.
956
+ * @param variableName - The name of the variable, used in error messages.
957
+ * @returns The byte representation of the value.
958
+ * @throws {CashAssemblyVariableNotIntegerError} If a number value is not a valid integer.
959
+ */
960
+ const convertVariableToBytes = (value, variableName) => {
961
+ if (value instanceof Uint8Array) return value;
962
+ if (typeof value === "bigint") return bigIntToVmNumber(value);
963
+ if (typeof value === "number") {
964
+ if (!Number.isInteger(value)) throw new CashAssemblyVariableNotIntegerError(variableName, value);
965
+ return bigIntToVmNumber(BigInt(value));
966
+ }
967
+ if (typeof value === "boolean") return new Uint8Array(value ? [1] : []);
968
+ return utf8ToBin(value);
969
+ };
970
+ /**
971
+ * Decodes compiled CashAssembly evaluation bytes into a string representation.
972
+ *
973
+ * 'evaluationDecodeMode' determines how the evaluation bytes are interpreted and presented.
974
+ * Choose based on what the evaluation is expected to produce:
975
+ * `bigint` for numeric values like satoshis, `utf8` for text labels, `hex` for binary data such
976
+ * as hashes, and `boolean` to represent boolean values.
977
+ *
978
+ * @param compiledResult - The compiled evaluation bytecode.
979
+ * @param evaluationDecodeMode - The decode mode used to convert bytes to text.
980
+ * @returns The decoded value as a string suitable for inline replacement.
981
+ */
982
+ const decodeCompiledCashAssemblyEvaluation = (compiledResult, evaluationDecodeMode = "utf8") => {
983
+ if (evaluationDecodeMode === "uint8array") return String(compiledResult);
984
+ if (evaluationDecodeMode === "boolean") return compiledResult.length === 0 ? "false" : "true";
985
+ if (evaluationDecodeMode === "hex") return binToHex(compiledResult);
986
+ if (evaluationDecodeMode === "bigint") {
987
+ const vmNumberResult = vmNumberToBigInt(compiledResult);
988
+ if (typeof vmNumberResult === "bigint") return vmNumberResult.toString();
989
+ }
990
+ return binToUtf8(compiledResult);
991
+ };
992
+ /**
993
+ * Compiles all CashAssembly evaluations in a text string and replaces each evaluation
994
+ * with a decoded string representation.
995
+ *
996
+ * @param cashAssemblyText - The string with CashAssembly evaluations.
997
+ * @param variables - Object mapping variable names to values for compilation.
998
+ * @param evaluationDecodeMode - The decode mode used after each evaluation is compiled.
999
+ * @returns Compiled text with all evaluations replaced by decoded string values.
1000
+ * @throws VariableValidationFailedError when a required variable is not present in the variables map.
1001
+ */
1002
+ const compileCashAssemblyString = (parameters) => {
1003
+ const { cashAssemblyText, variables, evaluationDecodeMode = "utf8" } = parameters;
1004
+ let compiledText = cashAssemblyText;
1005
+ const evaluations = extractCashAssemblyEvaluations(cashAssemblyText);
1006
+ for (const evaluation of evaluations) {
1007
+ const variableNames = extractVariablesFromEvaluations([evaluation]);
1008
+ const missingVariables = variableNames.filter((variableName) => !Object.hasOwn(variables, variableName));
1009
+ if (missingVariables.length > 0) throw new VariableValidationFailedError(missingVariables);
1010
+ const convertedVariables = {};
1011
+ for (const variableName of variableNames) convertedVariables[variableName] = convertVariableToBytes(variables[variableName], variableName);
1012
+ const decodedResult = decodeCompiledCashAssemblyEvaluation(generateCashAssemblyBytecode(compileCashAssemblyEvaluations([evaluation]), evaluation, convertedVariables), evaluationDecodeMode);
1013
+ compiledText = compiledText.replace(evaluation, decodedResult);
1014
+ }
1015
+ return compiledText;
1016
+ };
1017
+
443
1018
  //#endregion
444
1019
  //#region source/utils/store-utils.ts
445
1020
  /**
@@ -452,11 +1027,10 @@ const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutpu
452
1027
  * 4. Adds any new unspent outputs found on the blockchain but missing from the state to the state.
453
1028
  * 5. Removes any unspent outputs present in the state but no longer in the blockchain.
454
1029
  *
455
- * @param {State} state - The State instance to use for data operations.
456
- * @param {string} scriptHash - The script hash for which to update the stored unspent outputs.
457
- * @param {(scriptHash: string) => Promise<ScriptHashListUnspentResponse>} fetchUnspentOutputsCallback
458
- * Callback to fetch unspent outputs from the blockchain.
459
- * @throws {ScriptHashDataNotFoundError} If the script hash is not found in the state.
1030
+ * @param state - The State instance to use for data operations.
1031
+ * @param scriptHash - The script hash for which to update the stored unspent outputs.
1032
+ * @param fetchUnspentOutputsCallback - Callback function to fetch unspent outputs from the blockchain.
1033
+ * @throws If the script hash is not found in the state.
460
1034
  */
461
1035
  const updateUnspentOutputsForScriptHashInStore = async (state, scriptHash, fetchUnspentOutputsCallback) => {
462
1036
  const scriptHashData = await state.getScriptHashData(scriptHash);
@@ -483,6 +1057,7 @@ const updateUnspentOutputsForScriptHashInStore = async (state, scriptHash, fetch
483
1057
  selectable: true,
484
1058
  privacy: false,
485
1059
  templateIdentifier: scriptHashData.templateIdentifier,
1060
+ outputIdentifier: scriptHashData.outputIdentifier,
486
1061
  outpointIndex: unspentOutput.tx_pos,
487
1062
  outpointTransactionHash: unspentOutput.tx_hash,
488
1063
  minedAtHeight: unspentOutput.height,
@@ -506,18 +1081,18 @@ var BlockchainMonitor = class {
506
1081
  /**
507
1082
  * The state instance for data persistence.
508
1083
  */
509
- #state;
1084
+ state;
510
1085
  /**
511
1086
  * Flag indicating whether event listeners have been initialized.
512
1087
  */
513
- #eventListenersInitialized = false;
1088
+ eventListenersInitialized = false;
514
1089
  /**
515
1090
  * Creates a new instance of BlockchainMonitor.
516
1091
  *
517
1092
  * @param {State} state - The State instance for data persistence.
518
1093
  */
519
1094
  constructor(state) {
520
- this.#state = state;
1095
+ this.state = state;
521
1096
  }
522
1097
  /**
523
1098
  * Initializes event listeners for electrum application events.
@@ -529,7 +1104,7 @@ var BlockchainMonitor = class {
529
1104
  * @returns {void}
530
1105
  */
531
1106
  initializeEventListeners() {
532
- if (this.#eventListenersInitialized) return;
1107
+ if (this.eventListenersInitialized) return;
533
1108
  electrumEvents.on("SystemFailure", (_error) => {
534
1109
  this.stop().catch(() => {});
535
1110
  });
@@ -553,7 +1128,7 @@ var BlockchainMonitor = class {
553
1128
  electrumEvents.on("ScriptHashUpdate", async (data) => {
554
1129
  await this.onScriptHashUpdate(data);
555
1130
  });
556
- this.#eventListenersInitialized = true;
1131
+ this.eventListenersInitialized = true;
557
1132
  }
558
1133
  /**
559
1134
  * Stops the blockchain monitor and releases resources.
@@ -561,7 +1136,7 @@ var BlockchainMonitor = class {
561
1136
  */
562
1137
  async stop() {
563
1138
  await stopElectrumNetwork();
564
- this.#eventListenersInitialized = false;
1139
+ this.eventListenersInitialized = false;
565
1140
  }
566
1141
  /**
567
1142
  * Handles the creation of a new unspent output by storing it in the state.
@@ -570,7 +1145,7 @@ var BlockchainMonitor = class {
570
1145
  * @returns {Promise<void>} Resolves when the unspent output data is stored.
571
1146
  */
572
1147
  async handleUnspentOutputCreated(data) {
573
- await this.#state.storeUnspentOutputData(data);
1148
+ await this.state.storeUnspentOutputData(data);
574
1149
  }
575
1150
  /**
576
1151
  * Handles script hash update notifications from the electrum protocol.
@@ -581,74 +1156,31 @@ var BlockchainMonitor = class {
581
1156
  */
582
1157
  async onScriptHashUpdate(data) {
583
1158
  const { scriptHash } = data;
584
- const scriptHashDataList = await this.#state.listScriptHashData({ scriptHash });
1159
+ const scriptHashDataList = await this.state.listScriptHashData({ scriptHash });
585
1160
  const [firstElectrumClient] = electrumClients.values();
586
- for (const scriptHashData of scriptHashDataList) await updateUnspentOutputsForScriptHashInStore(this.#state, scriptHashData.scriptHash, async () => {
1161
+ for (const scriptHashData of scriptHashDataList) await updateUnspentOutputsForScriptHashInStore(this.state, scriptHashData.scriptHash, async () => {
587
1162
  return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scriptHashData.scriptHash);
588
1163
  });
589
1164
  }
590
1165
  };
591
1166
 
592
- //#endregion
593
- //#region source/defaults.ts
594
- /**
595
- * When an entity opts to participate in an invitation, it reserves resources (e.g., UTXOs)
596
- * that would otherwise be available to other invitations. To prevent resources from remaining
597
- * locked indefinitely, each reservation requires an expiration time, after which the resources
598
- * can be released.
599
- *
600
- * By default, the expiration time is set to 1 hour.
601
- */
602
- const DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS = 3600 * 1e3;
603
- /**
604
- * The default storage backend is IndexedDB.
605
- */
606
- const DEFAULT_STORAGE_TYPE = StorageType.INDEXEDDB;
607
- /**
608
- * The default sequence number is 0, which disables relative locktime on the input.
609
- */
610
- const DEFAULT_SEQUENCE_NUMBER = 0;
611
- /**
612
- * The default locktime is 0, which means the transaction is valid in any block and has no absolute locktime constraint.
613
- */
614
- const DEFAULT_LOCKTIME = 0;
615
- /**
616
- * The default transaction version is 2.
617
- */
618
- const DEFAULT_VERSION = 2;
619
- /**
620
- * An empty unlocking bytecode used as a placeholder for inputs (unlockingBytecode) within an invitation.
621
- * This placeholder is used when the entities responsible for signing those inputs
622
- * have not yet provided their signatures for the resulting transaction.
623
- *
624
- * Using a placeholder unlocking bytecode enables the engine to construct transaction structures for the
625
- * libauth compiler when working on template actions, even before all participant signatures are available.
626
- * This is especially helpful when invitation commits are merged, as it allows the transaction to be built and it's
627
- * parts can be validated before all unlocking scripts have been provided.
628
- */
629
- const PLACEHOLDER_UNLOCKING_BYTECODE = new Uint8Array(0);
630
- /**
631
- * The default electrum application identifier.
632
- */
633
- const DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER = "xo";
634
-
635
1167
  //#endregion
636
1168
  //#region source/invitation/commit.ts
637
1169
  /**
638
- * Generates a random commit identifier.
1170
+ * Generates a random 16-byte commit identifier.
639
1171
  *
640
- * @returns {XOInvitationCommitIdentifier} The generated commit identifier as a hex string.
1172
+ * @returns {string} The generated commit identifier as a hex string.
641
1173
  */
642
1174
  const generateCommitIdentifier = () => {
643
- return binToHex(generateRandomBytes(COMMIT_IDENTIFIER_BYTE_LENGTH));
1175
+ return binToHex(generateRandomBytes(16));
644
1176
  };
645
1177
  /**
646
1178
  * Finds the root commit identifier for a given entity in an invitation. The root commit is
647
1179
  * the first commit the entity added to the invitation.
648
1180
  *
649
- * @param {XOInvitation} invitation - The invitation whose commits are searched.
650
- * @param {XOInvitationEntityIdentifier} entityIdentifier - The entity identifier to search for among the invitation commits.
651
- * @returns {XOInvitationCommitIdentifier | undefined} The root commit identifier if the entity has a commit in the invitation, otherwise undefined.
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.
652
1184
  */
653
1185
  const findRootCommitIdentifierInInvitation = (invitation, entityIdentifier) => {
654
1186
  for (const commit of invitation.commits) if (commit.entityIdentifier === entityIdentifier) return commit.commitIdentifier;
@@ -680,27 +1212,26 @@ var InvitationBuilder = class InvitationBuilder {
680
1212
  * The timestamp when the invitation is created.
681
1213
  *
682
1214
  */
683
- #createdAtTimestamp;
1215
+ createdAtTimestamp;
684
1216
  /**
685
1217
  * The commits in the invitation.
686
1218
  */
687
- #commits;
1219
+ commits;
688
1220
  /**
689
1221
  * Create a new InvitationBuilder.
690
- * @param {InvitationCreationParameters} invitation - Context for invitation creation.
1222
+ * @param invitation Context for invitation creation.
691
1223
  */
692
1224
  constructor(invitation) {
693
1225
  const { templateIdentifier, actionIdentifier } = invitation;
694
1226
  this.templateIdentifier = templateIdentifier;
695
1227
  this.actionIdentifier = actionIdentifier;
696
- this.#commits = [];
697
- this.invitationIdentifier = binToHex(generateRandomBytes(INVITATION_IDENTIFIER_BYTE_LENGTH));
698
- this.#createdAtTimestamp = Date.now();
1228
+ this.commits = [];
1229
+ this.invitationIdentifier = binToHex(generateRandomBytes(16));
1230
+ this.createdAtTimestamp = Date.now();
699
1231
  }
700
1232
  /**
701
1233
  * Create a builder from an existing invitation.
702
- * @param {XOInvitation} invitation - An existing invitation.
703
- * @returns {InvitationBuilder} A builder initialized from the invitation.
1234
+ * @param invitation An existing XOInvitation.
704
1235
  */
705
1236
  static fromInvitation(invitation) {
706
1237
  const builder = new InvitationBuilder({
@@ -708,28 +1239,27 @@ var InvitationBuilder = class InvitationBuilder {
708
1239
  actionIdentifier: invitation.actionIdentifier
709
1240
  });
710
1241
  builder.invitationIdentifier = invitation.invitationIdentifier;
711
- builder.#createdAtTimestamp = invitation.createdAtTimestamp;
712
- builder.#commits = [...invitation.commits];
1242
+ builder.createdAtTimestamp = invitation.createdAtTimestamp;
1243
+ builder.commits = [...invitation.commits];
713
1244
  return builder;
714
1245
  }
715
1246
  /**
716
- * Build the invitation object to be shared.
717
- * @returns {XOInvitation} The built invitation.
1247
+ * Build the XOInvitation object to be shared.
1248
+ * @returns The built XOInvitation.
718
1249
  */
719
1250
  build() {
720
1251
  return {
721
1252
  invitationIdentifier: this.invitationIdentifier,
722
1253
  templateIdentifier: this.templateIdentifier,
723
1254
  actionIdentifier: this.actionIdentifier,
724
- createdAtTimestamp: this.#createdAtTimestamp,
725
- commits: this.#commits
1255
+ createdAtTimestamp: this.createdAtTimestamp,
1256
+ commits: this.commits
726
1257
  };
727
1258
  }
728
1259
  /**
729
- * Fully validates a given invitation.
1260
+ * Fully validates a given XOInvitation.
730
1261
  *
731
- * @param {XOTemplate} template - The template to validate against.
732
- * @returns {this} The builder instance after validation.
1262
+ * @param template - The template to validate against.
733
1263
  * @throws {InvitationExpiredError} If the invitation has expired.
734
1264
  * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
735
1265
  * @throws {InvalidRequirementsError} If the requirements are invalid.
@@ -748,50 +1278,47 @@ var InvitationBuilder = class InvitationBuilder {
748
1278
  }
749
1279
  /**
750
1280
  * Add a commit to the invitation.
751
- * @param {XOInvitationCommit} commit - The commit to add.
752
- * @returns {this} The builder instance.
753
- * @throws {CommitNotSignedError} If the commit has no signature.
754
- * @throws {CommitEntityIdentifierNotFoundError} If the commit has no entity identifier.
1281
+ * @param commit The commit to add.
1282
+ * @returns The builder instance.
755
1283
  */
756
1284
  addCommit(commit) {
757
1285
  if (!commit.signature) throw new CommitNotSignedError(commit.commitIdentifier);
758
1286
  if (!commit.entityIdentifier) throw new CommitEntityIdentifierNotFoundError(commit.commitIdentifier);
759
- this.#commits.push(commit);
1287
+ this.commits.push(commit);
760
1288
  return this;
761
1289
  }
762
1290
  /**
763
- * Returns the commit identifier of the last commit in the invitation.
764
- * @returns {XOInvitationCommitIdentifier | undefined} The last commit identifier, or undefined if there are no commits.
1291
+ * Returns the commitIdentifier of the last commit in the invitation.
1292
+ * @returns The commitIdentifier as a string, or undefined if there are no commits.
765
1293
  */
766
1294
  getLastCommitIdentifier() {
767
- return this.#commits[this.#commits.length - 1]?.commitIdentifier;
1295
+ return this.commits[this.commits.length - 1]?.commitIdentifier;
768
1296
  }
769
1297
  /**
770
- * Returns the last commit in the invitation.
771
- * @returns {XOInvitationCommit | undefined} The last commit, or undefined if there are no commits.
1298
+ * Returns the last InvitationCommit in the invitation.
1299
+ * @returns The last InvitationCommit object, or undefined if there are no commits.
772
1300
  */
773
1301
  getLastCommit() {
774
- return this.#commits[this.#commits.length - 1];
1302
+ return this.commits[this.commits.length - 1];
775
1303
  }
776
1304
  /**
777
1305
  * Creates an unsigned commit without adding it to the invitation.
778
1306
  * This allows for atomic commit creation with signature.
779
1307
  *
780
- * @param {object} params - Parameters for creating the commit.
781
- * @param {XOInvitationInput[]} [params.inputs] - Optional array of inputs to add.
782
- * @param {XOInvitationOutput[]} [params.outputs] - Optional array of outputs to add.
783
- * @param {XOInvitationVariable[]} [params.variables] - Optional array of variables to add.
784
- * @param {number} [params.transactionVersion] - Optional transaction version.
785
- * @param {number} [params.transactionLocktime] - Optional transaction locktime.
786
- * @param {number} [params.expiresAtTimestamp] - Optional expiration timestamp.
787
- * Defaults to now plus {@link DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS}.
788
- * @returns {Omit<XOInvitationCommit, 'signature' | 'entityIdentifier'>} The unsigned commit without signature.
1308
+ * @param params - Parameters for creating the commit
1309
+ * @param params.inputs - Optional array of inputs to add
1310
+ * @param params.outputs - Optional array of outputs to add
1311
+ * @param params.variables - Optional array of variables to add
1312
+ * @param params.transactionVersion - Optional transaction version
1313
+ * @param params.transactionLocktime - Optional transaction locktime
1314
+ * @param params.expiresAtTimestamp - Optional expiration timestamp (defaults to now + DEFAULT_COMMIT_EXPIRATION_IN_MILLISECONDS)
1315
+ * @returns The unsigned commit (without signature)
789
1316
  */
790
1317
  createUnsignedCommit(params) {
791
1318
  const { inputs, outputs, variables, transactionVersion, transactionLocktime, expiresAtTimestamp } = params;
792
- if (inputs) this.#validateMergesWithReferences(inputs);
793
- if (outputs) this.#validateMergesWithReferences(outputs);
794
- return this.#createCommit({
1319
+ if (inputs) this.validateMergesWithReferences(inputs);
1320
+ if (outputs) this.validateMergesWithReferences(outputs);
1321
+ return this.createCommit({
795
1322
  previousCommitIdentifier: this.getLastCommitIdentifier(),
796
1323
  inputs,
797
1324
  outputs,
@@ -805,7 +1332,7 @@ var InvitationBuilder = class InvitationBuilder {
805
1332
  * Creates a new commit from the provided data.
806
1333
  * This is a private helper method that initializes the commit building logic.
807
1334
  */
808
- #createCommit(params) {
1335
+ createCommit(params) {
809
1336
  let variables;
810
1337
  if (params.variables !== void 0 && params.variables.length > 0) variables = params.variables;
811
1338
  let inputs;
@@ -822,7 +1349,6 @@ var InvitationBuilder = class InvitationBuilder {
822
1349
  return {
823
1350
  commitIdentifier: generateCommitIdentifier(),
824
1351
  previousCommitIdentifier: params.previousCommitIdentifier,
825
- createdAtTimestamp: Date.now(),
826
1352
  data,
827
1353
  expiresAtTimestamp: params.expiresAtTimestamp
828
1354
  };
@@ -831,9 +1357,9 @@ var InvitationBuilder = class InvitationBuilder {
831
1357
  * Validates mergesWith references for inputs and outputs.
832
1358
  * @private
833
1359
  */
834
- #validateMergesWithReferences(items) {
1360
+ validateMergesWithReferences(items) {
835
1361
  for (const item of items) if (item.mergesWith) {
836
- if (!this.#commits.find((commit) => commit.commitIdentifier === item.mergesWith?.commitIdentifier)) throw new ParentCommitNotFoundInInvitationError(item.mergesWith.commitIdentifier, this.invitationIdentifier);
1362
+ if (!this.commits.find((commit) => commit.commitIdentifier === item.mergesWith?.commitIdentifier)) throw new ParentCommitNotFoundError(item.mergesWith.commitIdentifier, this.invitationIdentifier);
837
1363
  }
838
1364
  }
839
1365
  };
@@ -847,42 +1373,38 @@ var Template = class {
847
1373
  /**
848
1374
  * The template object.
849
1375
  */
850
- #template;
1376
+ template;
851
1377
  /**
852
1378
  * Creates a Template class from a template object.
853
1379
  */
854
1380
  constructor(template) {
855
- this.#template = template;
1381
+ this.template = template;
856
1382
  }
857
1383
  /**
858
1384
  * Gets the underlying template object.
859
1385
  */
860
1386
  getTemplate() {
861
- return this.#template;
1387
+ return this.template;
862
1388
  }
863
1389
  /**
864
1390
  * Gets the starting actions for the template.
865
1391
  * @returns {Array<XOTemplateActionIntent>} The list of starting actions.
866
1392
  */
867
1393
  getStartingActions() {
868
- return this.#template.start ?? [];
1394
+ return this.template.start ?? [];
869
1395
  }
870
1396
  /**
871
1397
  * Retrieves an output definition by identifier.
872
- * @param {XOTemplateOutputIdentifier} outputIdentifier - The output identifier.
873
- * @returns {XOTemplateOutput} The output definition associated with the specified output identifier.
874
1398
  * @throws {TemplateOutputNotFoundError} If the output is not found.
875
1399
  */
876
1400
  getOutputOrThrow(outputIdentifier) {
877
- const output = this.#template.outputs[outputIdentifier];
1401
+ const output = this.template.outputs[outputIdentifier];
878
1402
  if (output === void 0) throw new TemplateOutputNotFoundError(outputIdentifier);
879
1403
  if (!output.lockingScript) throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);
880
1404
  return output;
881
1405
  }
882
1406
  /**
883
1407
  * Retrieves the locking script identifier from an output.
884
- * @param {XOTemplateOutputIdentifier} outputIdentifier - The output identifier.
885
- * @returns {XOTemplateLockingScriptIdentifier} The locking script identifier associated with the specified output.
886
1408
  * @throws {TemplateOutputNotFoundError} If the output is not found.
887
1409
  * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.
888
1410
  */
@@ -893,20 +1415,16 @@ var Template = class {
893
1415
  }
894
1416
  /**
895
1417
  * Retrieves a locking script definition by identifier.
896
- * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - The locking script identifier.
897
- * @returns {XOTemplateLockingScript} The locking script definition associated with the specified locking script identifier.
898
1418
  * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
899
1419
  */
900
1420
  getLockingScriptOrThrow(lockingScriptIdentifier) {
901
- const lockingScript = this.#template.lockingScripts[lockingScriptIdentifier];
1421
+ const lockingScript = this.template.lockingScripts[lockingScriptIdentifier];
902
1422
  if (lockingScript === void 0) throw new TemplateLockingScriptNotFoundError(lockingScriptIdentifier);
903
1423
  if (lockingScript.lockingType === void 0) throw new TemplateLockingScriptTypeNotFoundError(lockingScriptIdentifier);
904
1424
  return lockingScript;
905
1425
  }
906
1426
  /**
907
1427
  * Retrieves the locking script for a given output.
908
- * @param {XOTemplateOutputIdentifier} outputIdentifier - The output identifier.
909
- * @returns {XOTemplateLockingScript} The locking script definition associated with the specified output.
910
1428
  * @throws {TemplateOutputNotFoundError} If the output is not found.
911
1429
  * @throws {TemplateLockingScriptInOutputNotFoundError} If the output has no locking script reference.
912
1430
  * @throws {TemplateLockingScriptNotFoundError} If the locking script definition is not found.
@@ -917,9 +1435,8 @@ var Template = class {
917
1435
  }
918
1436
  /**
919
1437
  * Retrieves a role within a locking script.
920
- * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - The locking script identifier.
921
- * @param {XOTemplateRoleIdentifier} roleIdentifier - The role identifier.
922
- * @returns {XOTemplateLockingScriptRole} The role definition associated with the specified locking script and role identifiers.
1438
+ * @param lockingScriptIdentifier - The locking script identifier.
1439
+ * @param roleIdentifier - The role identifier.
923
1440
  * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
924
1441
  * @throws {TemplateLockingScriptRoleNotFoundError} If the role is not found.
925
1442
  */
@@ -930,9 +1447,8 @@ var Template = class {
930
1447
  }
931
1448
  /**
932
1449
  * Retrieves the first available role in a locking script, or throws if none exist.
933
- * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - The locking script identifier.
934
- * @returns {[XOTemplateRoleIdentifier, XOTemplateLockingScriptRole]} The first available role identifier and role definition
935
- * for the specified locking script.
1450
+ * @param lockingScriptIdentifier - The locking script identifier.
1451
+ * @returns A tuple of [roleIdentifier, role].
936
1452
  * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
937
1453
  * @throws {TemplateLockingScriptRoleNotFoundError} If no roles exist.
938
1454
  */
@@ -943,12 +1459,12 @@ var Template = class {
943
1459
  return [roleKeys[0], roles[roleKeys[0]]];
944
1460
  }
945
1461
  /**
946
- * Retrieves the secret identifiers tracked for a locking script or one of its roles.
947
- * If roleIdentifier is provided, returns the secret identifiers tracked for that role within the locking script.
948
- * Otherwise, returns the secret identifiers tracked at the locking script level.
949
- * @param {XOTemplateLockingScriptIdentifier} lockingScriptIdentifier - The locking script identifier.
950
- * @param {XOTemplateRoleIdentifier} [roleIdentifier] - The role identifier. When omitted, locking script secrets are used.
951
- * @returns {string[]} Array of secret identifiers.
1462
+ * Retrieves secrets for a locking script.
1463
+ * If roleIdentifier is provided, returns secrets from the role's state.
1464
+ * Otherwise, returns secrets from the locking script itself.
1465
+ * @param lockingScriptIdentifier - The locking script identifier.
1466
+ * @param roleIdentifier - The role identifier (optional, if not provided uses locking script secrets).
1467
+ * @returns Array of secret identifiers.
952
1468
  * @throws {TemplateLockingScriptNotFoundError} If the locking script is not found.
953
1469
  * @throws {TemplateLockingScriptRoleNotFoundError} If roleIdentifier is provided but the role is not found.
954
1470
  */
@@ -958,30 +1474,27 @@ var Template = class {
958
1474
  }
959
1475
  /**
960
1476
  * Retrieves an action definition by identifier.
961
- * @param {XOTemplateActionIdentifier} actionIdentifier - The identifier of the action.
962
- * @returns {XOTemplateAction} The action definition associated with the specified action identifier.
1477
+ * @param actionIdentifier - The identifier of the action.
963
1478
  * @throws {TemplateActionNotFoundError} If the action is not found.
964
1479
  */
965
1480
  getActionOrThrow(actionIdentifier) {
966
- const action = this.#template.actions[actionIdentifier];
1481
+ const action = this.template.actions[actionIdentifier];
967
1482
  if (action === void 0) throw new TemplateActionNotFoundError(actionIdentifier);
968
1483
  return action;
969
1484
  }
970
1485
  /**
971
1486
  * Retrieves a transaction definition by identifier.
972
- * @param {XOTemplateTransactionIdentifier} transactionIdentifier - The identifier of the transaction.
973
- * @returns {XOTemplateTransaction} The transaction definition associated with the specified transaction identifier.
1487
+ * @param transactionIdentifier - The identifier of the transaction.
974
1488
  * @throws {TemplateTransactionNotFoundError} If the transaction is not found.
975
1489
  */
976
1490
  getTransactionOrThrow(transactionIdentifier) {
977
- const transaction = this.#template.transactions?.[transactionIdentifier];
1491
+ const transaction = this.template.transactions?.[transactionIdentifier];
978
1492
  if (transaction === void 0) throw new TemplateTransactionNotFoundError(transactionIdentifier);
979
1493
  return transaction;
980
1494
  }
981
1495
  /**
982
1496
  * Retrieves the transaction for a given action.
983
- * @param {XOTemplateActionIdentifier} actionIdentifier - The identifier of the action.
984
- * @returns {XOTemplateTransaction} The transaction definition associated with the specified action.
1497
+ * @param actionIdentifier - The identifier of the action.
985
1498
  * @throws {TemplateActionNotFoundError} If the action is not found.
986
1499
  * @throws {TemplateTransactionNotFoundError} If the action has no transaction defined or the transaction is not found.
987
1500
  */
@@ -1017,8 +1530,8 @@ var Template = class {
1017
1530
  * Converts an array of XOInvitationVariable objects into an object,
1018
1531
  * where each key is the variable's identifier and the value is the variable's value.
1019
1532
  *
1020
- * @param {XOInvitationVariable[]} variables - Array of invitation variables to convert.
1021
- * @returns {Record<string, XOInvitationVariableValue>} An object mapping each variable identifier to its corresponding value.
1533
+ * @param variables - Array of XOInvitationVariable objects to convert.
1534
+ * @returns An object mapping each variable identifier to its corresponding value.
1022
1535
  */
1023
1536
  const convertCommitVariablesIntoObject = (variables) => {
1024
1537
  const variablesObject = {};
@@ -1029,7 +1542,7 @@ const convertCommitVariablesIntoObject = (variables) => {
1029
1542
  * Validates that all commit references exist.
1030
1543
  */
1031
1544
  const validateCommitReferences = (commits, commitsMap) => {
1032
- for (const commit of commits) if (commit.previousCommitIdentifier && !commitsMap.has(commit.previousCommitIdentifier)) throw new ParentCommitNotFoundInInvitationError(commit.previousCommitIdentifier, commit.commitIdentifier);
1545
+ for (const commit of commits) if (commit.previousCommitIdentifier && !commitsMap.has(commit.previousCommitIdentifier)) throw new ParentCommitNotFoundError(commit.previousCommitIdentifier, commit.commitIdentifier);
1033
1546
  };
1034
1547
  /**
1035
1548
  * Merges simple data types (variables, transactionVersion, transactionLocktime).
@@ -1079,15 +1592,15 @@ const mergeItemsWithMergesWith = (context) => {
1079
1592
  const resolveItemMerges = (item, currentCommitIdentifier, visitedPath = /* @__PURE__ */ new Set()) => {
1080
1593
  const mergedItem = { ...item };
1081
1594
  if (item.mergesWith) {
1082
- const mergeKey = `${item.mergesWith.commitIdentifier}:${item.mergesWith.itemIndex}`;
1595
+ const mergeKey = `${item.mergesWith.commitIdentifier}:${item.mergesWith.index}`;
1083
1596
  if (visitedPath.has(mergeKey)) throw new CircularMergeReferenceError(itemType, mergeKey, currentCommitIdentifier);
1084
1597
  visitedPath.add(mergeKey);
1085
1598
  const mergesWithCommit = commitsMap.get(item.mergesWith.commitIdentifier);
1086
1599
  if (!mergesWithCommit) throw new MergesWithCommitNotFoundError(item.mergesWith.commitIdentifier, currentCommitIdentifier);
1087
1600
  const parentItems = getItemsFromCommit(mergesWithCommit);
1088
1601
  if (parentItems) {
1089
- const parentItem = parentItems[item.mergesWith.itemIndex];
1090
- if (!parentItem) throw new ItemNotFoundInCommitError(itemType, item.mergesWith.itemIndex, item.mergesWith.commitIdentifier);
1602
+ const parentItem = parentItems[item.mergesWith.index];
1603
+ if (!parentItem) throw new ItemNotFoundInCommitError(itemType, item.mergesWith.index, item.mergesWith.commitIdentifier);
1091
1604
  visitedCommits.add(item.mergesWith.commitIdentifier);
1092
1605
  const resolvedParent = resolveItemMerges(parentItem, item.mergesWith.commitIdentifier, visitedPath);
1093
1606
  Object.assign(mergedItem, resolvedParent);
@@ -1162,8 +1675,7 @@ const resolveOutputFromTemplate = (output, variables, templateInstance) => {
1162
1675
  const compiledResult = compileCashAssemblyString({
1163
1676
  cashAssemblyText: templateOutput.valueSatoshis,
1164
1677
  variables: variablesObject,
1165
- evaluationDecodeMode: "bigint",
1166
- templateVariables: templateInstance.getTemplate().variables
1678
+ evaluationDecodeMode: "bigint"
1167
1679
  });
1168
1680
  resolvedOutput.valueSatoshis = BigInt(compiledResult);
1169
1681
  }
@@ -1174,8 +1686,7 @@ const resolveOutputFromTemplate = (output, variables, templateInstance) => {
1174
1686
  resolvedOutput.lockingBytecode = hexToBin(compileCashAssemblyString({
1175
1687
  cashAssemblyText: templateOutput.lockingScript,
1176
1688
  variables: variablesObject,
1177
- evaluationDecodeMode: "hex",
1178
- templateVariables: templateInstance.getTemplate().variables
1689
+ evaluationDecodeMode: "hex"
1179
1690
  }));
1180
1691
  }
1181
1692
  }
@@ -1217,9 +1728,9 @@ const mergeOutputs = (commits, commitsMap, template, variables) => {
1217
1728
  /**
1218
1729
  * Merges invitation commits and transforms it into MergedInvitation structure.
1219
1730
  *
1220
- * @param {XOInvitation} invitation - The invitation containing commits to merge.
1221
- * @param {XOTemplate} template - The template used for resolving output identifiers.
1222
- * @returns {MergedInvitation | null} Merged invitation structure, or null if no commits exist.
1731
+ * @param invitation - The invitation containing commits to merge.
1732
+ * @param template - The template used for resolving output identifiers.
1733
+ * @returns MergedInvitation structure, or null if no commits exist.
1223
1734
  * @throws {Error} If merge conflicts or missing references are detected.
1224
1735
  */
1225
1736
  const mergeInvitationCommits = (invitation, template) => {
@@ -1251,8 +1762,8 @@ const INVITATION_REQUIREMENT_FIELD_NAMES = [
1251
1762
  ];
1252
1763
  /**
1253
1764
  * Checks if a role requirement has any items of the specified types.
1254
- * @param {InvitationRoleRequirementIdentifierLists} roleRequirement - The role requirement object to check for any populated requirement fields.
1255
- * @returns {boolean} True if the role has any requirements (variables, inputs, or outputs), false otherwise.
1765
+ * @param roleRequirement - The role requirement object to check for any populated requirement fields.
1766
+ * @returns `true` if the role has any requirements (variables, inputs, or outputs), `false` otherwise.
1256
1767
  */
1257
1768
  const hasRoleRequirements = (roleRequirement) => {
1258
1769
  return INVITATION_REQUIREMENT_FIELD_NAMES.some((requirementFieldName) => {
@@ -1263,8 +1774,8 @@ const hasRoleRequirements = (roleRequirement) => {
1263
1774
  /**
1264
1775
  * Filters role requirements to only include those with actual populated requirements.
1265
1776
  * Removes any roles that have no variables, inputs, or outputs defined.
1266
- * @param {RoleRequirementIdentifierMap} roleRequirements - Record mapping role identifiers to their requirement objects.
1267
- * @returns {RoleRequirementIdentifierMap} Filtered record containing only roles that have at least one requirement field populated.
1777
+ * @param roleRequirements - Record mapping role identifiers to their requirement objects.
1778
+ * @returns Filtered record containing only roles that have at least one requirement field populated.
1268
1779
  */
1269
1780
  const filterRolesWithRequirements = (roleRequirements) => {
1270
1781
  const filteredRoleRequirements = {};
@@ -1273,9 +1784,9 @@ const filterRolesWithRequirements = (roleRequirements) => {
1273
1784
  };
1274
1785
  /**
1275
1786
  * Finds requirement identifiers that are required but not yet populated.
1276
- * @param {string[]} [requiredIdentifiers] - Array of requirement identifiers that are expected.
1277
- * @param {string[]} [populatedIdentifiers] - Array of requirement identifiers that have already been provided.
1278
- * @returns {string[]} Array of identifiers that are required but missing from the populated list.
1787
+ * @param requiredIdentifiers - Array of requirement identifiers that are expected/required.
1788
+ * @param populatedIdentifiers - Array of requirement identifiers that have already been provided.
1789
+ * @returns Array of identifiers that are required but missing from the populated list.
1279
1790
  */
1280
1791
  const findMissingRequirementIdentifiers = (requiredIdentifiers = [], populatedIdentifiers = []) => {
1281
1792
  return requiredIdentifiers.filter((identifier) => !populatedIdentifiers.includes(identifier));
@@ -1283,13 +1794,11 @@ const findMissingRequirementIdentifiers = (requiredIdentifiers = [], populatedId
1283
1794
  /**
1284
1795
  * Processes and identifies missing requirements by comparing template requirements with populated requirements.
1285
1796
  * Analyzes both top-level requirements and role-specific requirements to determine what is still needed.
1286
- * @param {InvitationRequirementIdentifierLists} requirementsFromTemplate - Requirements expected from the template definition.
1287
- * @param {InvitationRequirementIdentifierLists} populatedRequirements - Requirements that have already been populated in the invitation.
1288
- * @returns {{
1289
- * missingRequirements: InvitationRequirementIdentifierLists,
1290
- * missingRoleRequirements: Record<string, InvitationRoleRequirementIdentifierLists>,
1291
- * }}
1292
- * Missing top-level requirements and role-specific missing requirements keyed by role identifier.
1797
+ * @param requirementsFromTemplate - Requirements expected from the template definition.
1798
+ * @param populatedRequirements - Requirements that have already been populated in the invitation.
1799
+ * @returns Object containing:
1800
+ * - `missingRequirements`: Top-level missing requirements (variables, inputs, outputs).
1801
+ * - `missingRoleRequirements`: Record of role-specific missing requirements keyed by role identifier.
1293
1802
  */
1294
1803
  const processMissingRequirements = (requirementsFromTemplate, populatedRequirements) => {
1295
1804
  const missingRequirements = {};
@@ -1318,9 +1827,9 @@ const processMissingRequirements = (requirementsFromTemplate, populatedRequireme
1318
1827
  * Analyzes the template action to determine what variables, inputs, outputs, and role-specific
1319
1828
  * requirements are needed to fulfill the action.
1320
1829
  *
1321
- * @param {XOTemplate} template - The template.
1322
- * @param {XOTemplateAction} action - The action that has requirements.
1323
- * @returns {InvitationRequirementIdentifierLists} An object containing all the requirements.
1830
+ * @param template - The template.
1831
+ * @param action - The action that has requirements.
1832
+ * @returns {XOInvitationRequirements} An object containing all the requirements.
1324
1833
  */
1325
1834
  const listRequirementsFromTemplate = (template, action) => {
1326
1835
  const generalRequirements = {};
@@ -1371,9 +1880,9 @@ const listRequirementsFromTemplate = (template, action) => {
1371
1880
  *
1372
1881
  * TODO: Determine how an Authorized Entity will get into the invitation process.
1373
1882
  *
1374
- * @param {XOInvitation} invitation - The invitation to examine.
1375
- * @param {XOTemplateRoleIdentifier} roleIdentifier - The role identifier to count filled slots for.
1376
- * @returns {number} The number of unique entities that have contributed data for the specified role.
1883
+ * @param invitation - The invitation to examine.
1884
+ * @param roleIdentifier - The role identifier to count filled slots for.
1885
+ * @returns The number of unique entities that have contributed data for the specified role.
1377
1886
  */
1378
1887
  const countFilledSlotsForRole = (invitation, roleIdentifier) => {
1379
1888
  const entityIdentifiers = /* @__PURE__ */ new Set();
@@ -1400,13 +1909,10 @@ const countFilledSlotsForRole = (invitation, roleIdentifier) => {
1400
1909
  * Variables are added to either top-level requirements or role-specific requirements based on
1401
1910
  * whether they have a role identifier. This can be customized independently as variable handling evolves.
1402
1911
  *
1403
- * @param {XOInvitationVariable[]} variables - Array of invitation variables to extract identifiers from.
1404
- * @param {InvitationRequirementIdentifierLists} generalRequirements - Requirements object to add top-level variable identifiers to.
1405
- * @param {RoleRequirementIdentifierMap} roleRequirements - Role requirements map for role-specific variable identifiers.
1406
- * @returns {{
1407
- * generalRequirements: InvitationRequirementIdentifierLists,
1408
- * roleRequirements: RoleRequirementIdentifierMap,
1409
- * }} Updated requirements objects.
1912
+ * @param variables - Array of invitation variables to extract identifiers from.
1913
+ * @param generalRequirements - Requirements object to add top-level variable identifiers to.
1914
+ * @param roleRequirements - Record of role requirements to add role-specific variable identifiers to.
1915
+ * @returns Updated requirements objects.
1410
1916
  */
1411
1917
  const addVariableIdentifiers = (variables, generalRequirements, roleRequirements) => {
1412
1918
  const updatedGeneralRequirements = { ...generalRequirements };
@@ -1433,13 +1939,10 @@ const addVariableIdentifiers = (variables, generalRequirements, roleRequirements
1433
1939
  * Inputs are added to either top-level requirements or role-specific requirements based on
1434
1940
  * whether they have a role identifier.
1435
1941
  *
1436
- * @param {XOInvitationInput[]} inputs - Array of invitation inputs to extract identifiers from.
1437
- * @param {InvitationRequirementIdentifierLists} generalRequirements - Requirements object to add top-level input identifiers to.
1438
- * @param {RoleRequirementIdentifierMap} roleRequirements - Role requirements map for role-specific input identifiers.
1439
- * @returns {{
1440
- * generalRequirements: InvitationRequirementIdentifierLists,
1441
- * roleRequirements: RoleRequirementIdentifierMap,
1442
- * }} Updated requirements objects.
1942
+ * @param inputs - Array of invitation inputs to extract identifiers from.
1943
+ * @param generalRequirements - Requirements object to add top-level input identifiers to.
1944
+ * @param roleRequirements - Record of role requirements to add role-specific input identifiers to.
1945
+ * @returns Updated requirements objects.
1443
1946
  */
1444
1947
  const addInputIdentifiers = (inputs, generalRequirements, roleRequirements) => {
1445
1948
  const updatedGeneralRequirements = { ...generalRequirements };
@@ -1466,13 +1969,10 @@ const addInputIdentifiers = (inputs, generalRequirements, roleRequirements) => {
1466
1969
  * Outputs are added to either top-level requirements or role-specific requirements based on
1467
1970
  * whether they have a role identifier. This can be customized independently as output handling evolves.
1468
1971
  *
1469
- * @param {XOInvitationOutput[]} outputs - Array of invitation outputs to extract identifiers from.
1470
- * @param {InvitationRequirementIdentifierLists} generalRequirements - Requirements object to add top-level output identifiers to.
1471
- * @param {RoleRequirementIdentifierMap} roleRequirements - Role requirements map for role-specific output identifiers.
1472
- * @returns {{
1473
- * generalRequirements: InvitationRequirementIdentifierLists,
1474
- * roleRequirements: RoleRequirementIdentifierMap,
1475
- * }} Updated requirements objects.
1972
+ * @param outputs - Array of invitation outputs to extract identifiers from.
1973
+ * @param generalRequirements - Requirements object to add top-level output identifiers to.
1974
+ * @param roleRequirements - Record of role requirements to add role-specific output identifiers to.
1975
+ * @returns Updated requirements objects.
1476
1976
  */
1477
1977
  const addOutputIdentifiers = (outputs, generalRequirements, roleRequirements) => {
1478
1978
  const updatedGeneralRequirements = { ...generalRequirements };
@@ -1499,8 +1999,8 @@ const addOutputIdentifiers = (outputs, generalRequirements, roleRequirements) =>
1499
1999
  * Extracts variable, input, and output identifiers from all commits in the invitation and
1500
2000
  * organizes them into top-level and role-specific requirements.
1501
2001
  *
1502
- * @param {XOInvitation} invitation - The invitation object to analyze for populated requirements.
1503
- * @returns {InvitationRequirementIdentifierLists} An object containing all populated requirements found in the invitation's commits,
2002
+ * @param invitation - The invitation object to analyze for populated requirements.
2003
+ * @returns An object containing all populated requirements found in the invitation's commits,
1504
2004
  * including top-level requirements and role-specific requirements. Only includes roles
1505
2005
  * that have at least one requirement populated.
1506
2006
  */
@@ -1537,10 +2037,10 @@ const listPopulatedRequirementsInInvitation = (invitation) => {
1537
2037
  *
1538
2038
  * Logic: `missing_requirements = requirements_from_template - populated_requirements_in_invitation`
1539
2039
  *
1540
- * @param {XOInvitation} invitation - The invitation object to check for missing requirements.
1541
- * @param {XOTemplate} template - The template defining what requirements are expected.
1542
- * @param {XOTemplateAction} action - The template action being analyzed to determine required requirements.
1543
- * @returns {InvitationRequirementIdentifierLists} An object containing all missing requirements, including top-level missing requirements
2040
+ * @param invitation - The invitation object to check for missing requirements.
2041
+ * @param template - The template defining what requirements are expected.
2042
+ * @param action - The template action being analyzed to determine required requirements.
2043
+ * @returns An object containing all missing requirements, including top-level missing requirements
1544
2044
  * and role-specific missing requirements. Only includes roles that have at least one missing requirement.
1545
2045
  */
1546
2046
  const listMissingRequirements = (invitation, template, action) => {
@@ -1555,9 +2055,10 @@ const listMissingRequirements = (invitation, template, action) => {
1555
2055
  * A role is considered available if the number of distinct entities that have filled it
1556
2056
  * is less than the role's maximum slot count. If max is undefined, the role has unlimited capacity.
1557
2057
  *
1558
- * @param {XOInvitation} invitation - The invitation object to check for available roles.
1559
- * @param {XOTemplateAction} action - The template action being analyzed to determine which roles are expected.
1560
- * @returns {XOTemplateRoleIdentifier[]} Role identifiers for roles that can still accept participants.
2058
+ * @param invitation - The invitation object to check for available roles.
2059
+ * @param template - The template defining the invitation structure and requirements.
2060
+ * @param action - The template action being analyzed to determine which roles are expected.
2061
+ * @returns Array of role identifier strings representing roles that can still accept participants.
1561
2062
  * Returns an empty array if no roles are defined in the action.
1562
2063
  */
1563
2064
  const listAvailableRolesForInvitation = (invitation, action) => {
@@ -1578,8 +2079,8 @@ const listAvailableRolesForInvitation = (invitation, action) => {
1578
2079
  /**
1579
2080
  * Validates that the invitation has not expired for any of the commits.
1580
2081
  *
1581
- * @param {XOInvitation} invitation - The invitation containing creation and expiration timestamps.
1582
- * @returns {boolean} True if the invitation is expired, false if it is valid.
2082
+ * @param invitation - The XOInvitation object containing creation and expiration timestamps.
2083
+ * @returns True if the invitation is expired, false if it is valid.
1583
2084
  */
1584
2085
  const hasInvitationExpired = (invitation) => {
1585
2086
  const { commits } = invitation;
@@ -1587,16 +2088,16 @@ const hasInvitationExpired = (invitation) => {
1587
2088
  return commits.some((commit) => commit.expiresAtTimestamp < now);
1588
2089
  };
1589
2090
  /**
1590
- * Validates that all entity identifiers in the invitation are valid extended public keys.
2091
+ * Validates that all entity identifiers in the invitation are valid public keys.
1591
2092
  * Extracts unique entity identifiers from all commits.
1592
2093
  *
1593
- * @param {XOInvitation} invitation - The invitation to validate.
1594
- * @returns {boolean} True if all entities are valid, false otherwise.
2094
+ * @param invitation - The invitation to validate.
2095
+ * @returns True if all entities are valid, false otherwise.
1595
2096
  */
1596
2097
  const validateInvitationEntities = (invitation) => {
1597
2098
  const entityIdentifiers = new Set(invitation.commits.map((commit) => commit.entityIdentifier));
1598
2099
  for (const entityIdentifier of entityIdentifiers) try {
1599
- new ExtendedPublicKey(entityIdentifier);
2100
+ new PublicKey(entityIdentifier);
1600
2101
  } catch {
1601
2102
  return false;
1602
2103
  }
@@ -1605,10 +2106,10 @@ const validateInvitationEntities = (invitation) => {
1605
2106
  /**
1606
2107
  * Validates that all provided requirements in the invitation were expected by the template.
1607
2108
  *
1608
- * @param {XOInvitation} invitation - The invitation to validate.
1609
- * @param {XOTemplate} template - The template to validate against.
1610
- * @param {XOTemplateAction} action - The action to validate against.
1611
- * @returns {boolean} True if all requirements are expected, false otherwise.
2109
+ * @param invitation - The invitation to validate.
2110
+ * @param template - The template to validate against.
2111
+ * @param action - The action to validate against.
2112
+ * @returns True if all requirements are expected, false otherwise.
1612
2113
  */
1613
2114
  const validateRoleRequirements = (invitation, template, action) => {
1614
2115
  const expectedRequirementsByTemplate = listRequirementsFromTemplate(template, action);
@@ -1638,12 +2139,13 @@ const validateRoleRequirements = (invitation, template, action) => {
1638
2139
  * Validates commit signatures.
1639
2140
  * Signature signs: stringify(data) + templateIdentifier + actionIdentifier + invitationIdentifier + commitIdentifier + previousCommitIdentifier
1640
2141
  *
1641
- * @param {XOInvitation} invitation - The invitation containing commits to validate.
1642
- * @returns {boolean} True if all commit signatures are valid, false otherwise.
2142
+ * @param invitation - The invitation containing commits to validate.
2143
+ * @returns True if all commit signatures are valid, false otherwise.
1643
2144
  */
1644
2145
  const validateInvitationCommits = (invitation) => {
1645
2146
  const { templateIdentifier, actionIdentifier, invitationIdentifier, commits } = invitation;
1646
2147
  for (const commit of commits) {
2148
+ const entityPublicKey = commit.entityIdentifier;
1647
2149
  const commitSigningPayload = buildInvitationCommitSigningPayload({
1648
2150
  data: commit.data,
1649
2151
  templateIdentifier,
@@ -1652,12 +2154,7 @@ const validateInvitationCommits = (invitation) => {
1652
2154
  commitIdentifier: commit.commitIdentifier,
1653
2155
  previousCommitIdentifier: commit.previousCommitIdentifier
1654
2156
  });
1655
- if (!verifyInvitationCommitSignature({
1656
- signature: commit.signature,
1657
- entityIdentifier: commit.entityIdentifier,
1658
- commitIdentifier: commit.commitIdentifier,
1659
- message: commitSigningPayload
1660
- })) return false;
2157
+ if (!verifySchnorrSignature(commit.signature, entityPublicKey, commitSigningPayload)) return false;
1661
2158
  }
1662
2159
  return true;
1663
2160
  };
@@ -1671,15 +2168,27 @@ var Engine = class Engine {
1671
2168
  /**
1672
2169
  * The crypto instance.
1673
2170
  */
1674
- #crypto;
2171
+ crypto;
1675
2172
  /**
1676
2173
  * The state instance.
1677
2174
  */
1678
- #state;
2175
+ state;
1679
2176
  /**
1680
2177
  * The blockchain monitor instance.
1681
2178
  */
1682
- #blockchainMonitor;
2179
+ blockchainMonitor;
2180
+ /**
2181
+ * The default template identifier.
2182
+ */
2183
+ defaultTemplateIdentifier;
2184
+ /**
2185
+ * The default role identifier.
2186
+ */
2187
+ defaultRoleIdentifier;
2188
+ /**
2189
+ * The default output identifier.
2190
+ */
2191
+ defaultOutputIdentifier;
1683
2192
  /**
1684
2193
  * Constructs a new instance of XO Engine.
1685
2194
  * @private
@@ -1688,9 +2197,9 @@ var Engine = class Engine {
1688
2197
  * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.
1689
2198
  */
1690
2199
  constructor(mnemonic, state, blockchainMonitor) {
1691
- this.#crypto = new Crypto(convertMnemonicToSeedBytes(mnemonic));
1692
- this.#state = state;
1693
- this.#blockchainMonitor = blockchainMonitor;
2200
+ this.crypto = new Crypto(convertMnemonicToSeedBytes(mnemonic));
2201
+ this.state = state;
2202
+ this.blockchainMonitor = blockchainMonitor;
1694
2203
  }
1695
2204
  /**
1696
2205
  * Initializes and creates a new XO Engine instance.
@@ -1705,7 +2214,7 @@ var Engine = class Engine {
1705
2214
  electrumServers,
1706
2215
  ...options
1707
2216
  });
1708
- const accountHash = computeAccountHash(mnemonic);
2217
+ const accountHash = binToHex(sha256.hash(utf8ToBin(mnemonic)));
1709
2218
  const stateInstance = new State(await createStorageAdapter({
1710
2219
  storageType: options.storageType ?? DEFAULT_STORAGE_TYPE,
1711
2220
  databasePath: options.databasePath,
@@ -1723,7 +2232,7 @@ var Engine = class Engine {
1723
2232
  * @returns {Promise<void>} Resolves when the engine is stopped.
1724
2233
  */
1725
2234
  async stop() {
1726
- await this.#blockchainMonitor.stop();
2235
+ await this.blockchainMonitor.stop();
1727
2236
  }
1728
2237
  /**
1729
2238
  * Retrieves the current chain status from the electrum application.
@@ -1734,21 +2243,21 @@ var Engine = class Engine {
1734
2243
  }
1735
2244
  /**
1736
2245
  * Retrieves a template by its identifier from the state.
1737
- * @param {XOTemplateIdentifier} templateIdentifier - Template identifier.
2246
+ * @param {string} templateIdentifier - Template identifier.
1738
2247
  * @returns {Promise<XOTemplate | undefined>} The template object.
1739
2248
  */
1740
2249
  async getTemplate(templateIdentifier) {
1741
- return this.#state.getTemplate(templateIdentifier);
2250
+ return this.state.getTemplate(templateIdentifier);
1742
2251
  }
1743
2252
  /**
1744
2253
  * Imports a template into the Engine after sanitization and validation.
1745
2254
  * @param {string | XOTemplate} untrustedJsonOrObject - JSON or object containing the untrusted template to import.
1746
- * @returns {Promise<{ template: XOTemplate; templateIdentifier: XOTemplateIdentifier }>} The imported template and its identifier.
2255
+ * @returns {Promise<void>} Resolves when the template is imported.
1747
2256
  * @throws {TemplateImportFailedError} If the template is invalid.
1748
2257
  */
1749
2258
  async importTemplate(untrustedJsonOrObject) {
1750
2259
  const template = parseTemplate$1(untrustedJsonOrObject);
1751
- await this.#state.storeTemplate(template);
2260
+ await this.state.storeTemplate(template);
1752
2261
  return {
1753
2262
  template,
1754
2263
  templateIdentifier: generateTemplateIdentifier$1(template)
@@ -1759,11 +2268,11 @@ var Engine = class Engine {
1759
2268
  * @returns {Promise<XOTemplate[]>} The list of imported templates.
1760
2269
  */
1761
2270
  async listImportedTemplates() {
1762
- return this.#state.listTemplates();
2271
+ return this.state.listTemplates();
1763
2272
  }
1764
2273
  /**
1765
2274
  * Lists the starting actions available in a specified template.
1766
- * @param {XOTemplateIdentifier} templateIdentifier - Template identifier.
2275
+ * @param {string} templateIdentifier - Template identifier.
1767
2276
  * @returns {Promise<Array<XOTemplateActionIntent>>} The list of starting actions.
1768
2277
  */
1769
2278
  async listStartingActions(templateIdentifier) {
@@ -1774,7 +2283,7 @@ var Engine = class Engine {
1774
2283
  *
1775
2284
  * TODO: Make this an private/internal method.
1776
2285
  *
1777
- * @param {XOTemplateIdentifier} templateIdentifier - Template identifier.
2286
+ * @param {string} templateIdentifier - Template identifier.
1778
2287
  * @returns {Promise<void>} Resolves when the unspent outputs are updated.
1779
2288
  */
1780
2289
  async updateUnspentOutputsForTemplate(templateIdentifier) {
@@ -1787,7 +2296,7 @@ var Engine = class Engine {
1787
2296
  * TODO: Make this a private/internal method. We may change how/where this is defined in the future.
1788
2297
  * We'd like to ensure events are propagated to the sync server with an ACK and that the states match between remote and local.
1789
2298
  *
1790
- * @param {XOTemplateIdentifier} templateIdentifier - Template identifier.
2299
+ * @param {string} templateIdentifier - Template identifier.
1791
2300
  * @returns {Promise<void>} Resolves when the script hashes are subscribed.
1792
2301
  */
1793
2302
  async subscribeToScriptHashForTemplate(templateIdentifier) {
@@ -1797,27 +2306,22 @@ var Engine = class Engine {
1797
2306
  for (const scriptHashData of scriptHashDataList) await subscribeToScriptHashUpdates(firstElectrumClient, scriptHashData.scriptHash);
1798
2307
  }
1799
2308
  /**
1800
- * Sets the fallback locking parameters used for change and locking bytecode generation.
2309
+ * TENTATIVE METHOD: DEFAULT LOCKING STRATEGY UNKNOWN
1801
2310
  *
1802
- * Resolution order is override, then template defaults, then these fallbacks.
1803
- * If generation is required and no fallback exists, {@link FallbackLockingParametersMissingError} is thrown.
2311
+ * Sets the default locking parameters (template, output, and role identifiers) for the engine.
2312
+ * TODO: The default identifiers exist as the strategy on how to create the change and default
2313
+ * unlocking conditions are unclear. This is likely to change in the future.
1804
2314
  *
1805
- * @param {FallbackLockingParameters} fallbackLockingParameters - Template, output, and role identifiers set together.
1806
- * @returns {Promise<void>} Resolves when the fallback parameters have been set.
1807
- * @throws {TemplateIdentifierInvalidInputTypeError} If the template identifier input type is invalid.
1808
- * @throws {TemplateIdentifierByteLengthInvalidError} If the template identifier byte length is invalid.
1809
- * @throws {TemplateIdentifierHexLengthInvalidError} If the template identifier hex length is invalid.
1810
- * @throws {TemplateIdentifierHexFormatInvalidError} If the template identifier hex format is invalid.
1811
- * @throws {TemplateIdentifierAllZeroesError} If the template identifier is all zeroes.
1812
- * @throws {TemplateIdentifierMaximumError} If the template identifier is all 0xFF bytes.
1813
- */
1814
- async updateFallbackLockingParameters(fallbackLockingParameters) {
1815
- const templateIdentifier = new TemplateIdentifier(fallbackLockingParameters.templateIdentifier).toHex();
1816
- return this.#state.updateWalletSettings({ fallbackLockingParameters: {
1817
- templateIdentifier,
1818
- outputIdentifier: fallbackLockingParameters.outputIdentifier,
1819
- roleIdentifier: fallbackLockingParameters.roleIdentifier
1820
- } });
2315
+ * @param {string} templateIdentifier - The identifier of the template to use as default.
2316
+ * @param {string} outputIdentifier - The identifier of the output within the specified template.
2317
+ * @param {string} roleIdentifier - The identifier of the role to use as default for this output.
2318
+ * @returns {Promise<void>} Resolves when the default parameters have been successfully set.
2319
+ * @throws {Error} If the template or output cannot be found.
2320
+ */
2321
+ async setDefaultLockingParameters(templateIdentifier, outputIdentifier, roleIdentifier) {
2322
+ this.defaultTemplateIdentifier = templateIdentifier;
2323
+ this.defaultOutputIdentifier = outputIdentifier;
2324
+ this.defaultRoleIdentifier = roleIdentifier;
1821
2325
  }
1822
2326
  /**
1823
2327
  * TODO: Implement this.
@@ -1838,10 +2342,10 @@ var Engine = class Engine {
1838
2342
  * xo template are done using invitations.
1839
2343
  *
1840
2344
  * @param {InvitationCreationParameters} params - The parameters for invitation creation.
1841
- * @param {XOTemplateIdentifier} params.templateIdentifier - Identifier for the template to use.
1842
- * @param {XOTemplateActionIdentifier} params.actionIdentifier - Identifier for the action to initiate.
2345
+ * @param {string} params.templateIdentifier - Identifier for the template to use.
2346
+ * @param {string} params.actionIdentifier - Identifier for the action to initiate.
1843
2347
  * @returns {Promise<XOInvitation>} A promise that resolves to the constructed invitation.
1844
- * @throws {TemplateNotFoundInStoreError} If the template is not found.
2348
+ * @throws {TemplateNotFoundError} If the template is not found.
1845
2349
  * @throws {TemplateActionNotFoundError} If the action is not found.
1846
2350
  *
1847
2351
  * TODO: Add all the throws that happen during the execution of the method.
@@ -1851,7 +2355,7 @@ var Engine = class Engine {
1851
2355
  const invitationBuilder = new InvitationBuilder(params);
1852
2356
  const invitationCommit = invitationBuilder.createUnsignedCommit({});
1853
2357
  const rootCommitIdentifier = invitationCommit.commitIdentifier;
1854
- const signedCommit = this.#crypto.signInvitationCommitWithSchnorr({
2358
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
1855
2359
  invitationCommit,
1856
2360
  invitationIdentifier: invitationBuilder.invitationIdentifier,
1857
2361
  rootCommitIdentifier,
@@ -1860,7 +2364,7 @@ var Engine = class Engine {
1860
2364
  });
1861
2365
  invitationBuilder.addCommit(signedCommit);
1862
2366
  const invitation = invitationBuilder.build();
1863
- await this.#state.storeNewInvitation(invitation.invitationIdentifier, {
2367
+ await this.state.storeInvitation(invitation.invitationIdentifier, {
1864
2368
  ...invitation,
1865
2369
  entityIdentifier: signedCommit.entityIdentifier
1866
2370
  });
@@ -1872,7 +2376,7 @@ var Engine = class Engine {
1872
2376
  * @param {XOInvitation} invitation - The invitation to be accepted.
1873
2377
  * @param {AcceptInvitationParameters} params - Optional parameters for accepting the invitation.
1874
2378
  * @returns {Promise<XOInvitation>} The updated XOInvitation instance.
1875
- * @throws {TemplateNotFoundInStoreError} If the template is not found.
2379
+ * @throws {TemplateNotFoundError} If the template is not found.
1876
2380
  * @throws {TemplateActionNotFoundError} If the action is not found.
1877
2381
  * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
1878
2382
  * @throws {InvalidRequirementsError} If the requirements are invalid.
@@ -1880,12 +2384,12 @@ var Engine = class Engine {
1880
2384
  */
1881
2385
  async acceptInvitation(invitation, params) {
1882
2386
  new Template(await this.getTemplateOrThrow(invitation.templateIdentifier)).getActionOrThrow(invitation.actionIdentifier);
1883
- const invitationFromStore = await this.#state.getInvitation(invitation.invitationIdentifier);
2387
+ const invitationFromStore = await this.state.getInvitation(invitation.invitationIdentifier);
1884
2388
  if (invitationFromStore !== void 0) return invitationFromStore;
1885
2389
  const invitationBuilder = InvitationBuilder.fromInvitation(invitation);
1886
2390
  const invitationCommit = invitationBuilder.createUnsignedCommit({ ...params });
1887
2391
  const rootCommitIdentifier = invitationCommit.commitIdentifier;
1888
- const signedCommit = this.#crypto.signInvitationCommitWithSchnorr({
2392
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
1889
2393
  invitationCommit,
1890
2394
  invitationIdentifier: invitationBuilder.invitationIdentifier,
1891
2395
  rootCommitIdentifier,
@@ -1894,7 +2398,7 @@ var Engine = class Engine {
1894
2398
  });
1895
2399
  invitationBuilder.addCommit(signedCommit);
1896
2400
  const acceptedInvitation = invitationBuilder.build();
1897
- await this.#state.storeNewInvitation(acceptedInvitation.invitationIdentifier, {
2401
+ await this.state.storeInvitation(acceptedInvitation.invitationIdentifier, {
1898
2402
  ...acceptedInvitation,
1899
2403
  entityIdentifier: signedCommit.entityIdentifier
1900
2404
  });
@@ -1903,23 +2407,21 @@ var Engine = class Engine {
1903
2407
  /**
1904
2408
  * Appends the invitation with the new information.
1905
2409
  *
1906
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to append.
1907
- * The invitation must already exist in the store.
2410
+ * @param {string} invitationIdentifier - The identifier of the invitation to append. The invitation must already exist in the store.
1908
2411
  * @param {AppendInvitationParameters} params - The parameters to append the invitation with.
1909
2412
  * @returns {Promise<XOInvitation>} The appended invitation.
1910
2413
  * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
1911
2414
  */
1912
2415
  async appendInvitation(invitationIdentifier, params) {
1913
2416
  const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
1914
- return this.#applyInvitationAppend(invitationFromStore, params);
2417
+ return this.applyInvitationAppend(invitationFromStore, params);
1915
2418
  }
1916
2419
  /**
1917
2420
  * Signs the provided invitation once all the resources are reserved and the invitation is complete.
1918
2421
  * This method is used to sign own inputs and provide unlocking data for them, this appends the
1919
2422
  * invitation and adds new commit with unlocking data.
1920
2423
  *
1921
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to sign.
1922
- * The invitation must already exist in the store.
2424
+ * @param {string} invitationIdentifier - The identifier of the invitation to sign. The invitation must already exist in the store.
1923
2425
  * @returns {Promise<XOInvitation>} Resolves when signing is complete.
1924
2426
  * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
1925
2427
  *
@@ -1929,7 +2431,7 @@ var Engine = class Engine {
1929
2431
  const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
1930
2432
  const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
1931
2433
  const mergedCommit = mergeInvitationCommits(invitationFromStore, template);
1932
- if (mergedCommit === null) throw new MergedCommitNotFoundError();
2434
+ if (mergedCommit === void 0) throw new MergedCommitNotFoundError();
1933
2435
  const transactionResult = generateTransaction({
1934
2436
  version: mergedCommit.transactionVersion,
1935
2437
  locktime: mergedCommit.transactionLocktime,
@@ -1937,7 +2439,7 @@ var Engine = class Engine {
1937
2439
  outputs: mergedCommit.outputs
1938
2440
  });
1939
2441
  if (transactionResult.success === false) throw new TransactionGenerationFailedError();
1940
- const unspentOutputs = await this.#state.listUnspentOutputsData({ reservedBy: invitationFromStore.invitationIdentifier });
2442
+ const unspentOutputs = await this.state.listUnspentOutputsData({ reservedBy: invitationFromStore.invitationIdentifier });
1941
2443
  for (const [index, input] of transactionResult.transaction.inputs.entries()) {
1942
2444
  let unspentOutput;
1943
2445
  for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex && sourceOutput.reservedBy) {
@@ -1945,28 +2447,27 @@ var Engine = class Engine {
1945
2447
  break;
1946
2448
  }
1947
2449
  if (!unspentOutput) continue;
1948
- const scriptHashData = await this.#state.getScriptHashData(unspentOutput.scriptHash);
2450
+ const scriptHashData = await this.state.getScriptHashData(unspentOutput.scriptHash);
1949
2451
  if (scriptHashData === void 0) throw new ScriptHashDataNotFoundError(unspentOutput.scriptHash);
1950
2452
  let compilerPrivateKeyRecord;
1951
- if (scriptHashData.secrets !== void 0) {
1952
- const derivedSecretRecord = Object.values(scriptHashData.secrets).find((secretRecord) => secretRecord.derivativeIndex !== void 0);
1953
- if (derivedSecretRecord?.lockingType === XOTemplateLockingTypes.P2PKH) {
1954
- const templateDataForInput = await this.#state.getTemplate(scriptHashData.templateIdentifier);
1955
- if (templateDataForInput === void 0) throw new TemplateNotFoundInStoreError(scriptHashData.templateIdentifier);
2453
+ if (scriptHashData.derivationSource !== void 0) {
2454
+ if (scriptHashData.derivationSource.lockingType === "p2pkh") {
2455
+ const templateDataForInput = await this.state.getTemplate(scriptHashData.templateIdentifier);
2456
+ if (templateDataForInput === void 0) throw new TemplateNotFoundError(scriptHashData.templateIdentifier);
1956
2457
  const templateInstanceForInput = new Template(templateDataForInput);
1957
2458
  const lockingScriptIdentifier = templateInstanceForInput.getLockingScriptIdentifierOrThrow(scriptHashData.outputIdentifier);
1958
2459
  const secretIdentifiers = templateInstanceForInput.getSecrets(lockingScriptIdentifier, scriptHashData.roleIdentifier);
1959
- const { derivativeIndex } = derivedSecretRecord;
1960
- if (derivativeIndex === void 0) throw new P2PKHDerivativeIndexMissingError();
1961
- compilerPrivateKeyRecord = this.#crypto.derivePrivateKeyRecordForCompiler({
2460
+ const { derivativeIndex } = scriptHashData.derivationSource;
2461
+ if (typeof derivativeIndex !== "string") throw new InvalidDerivativeIndexTypeError("string", typeof derivativeIndex);
2462
+ compilerPrivateKeyRecord = this.crypto.derivePrivateKeyRecordForCompiler({
1962
2463
  compilerKeyIdentifiers: secretIdentifiers,
1963
2464
  templateIdentifier: scriptHashData.templateIdentifier,
1964
- templateKeyDerivationIndex: derivativeIndex
2465
+ templateKeyDerivationIndex: Number(derivativeIndex)
1965
2466
  });
1966
2467
  }
1967
2468
  }
1968
2469
  if (compilerPrivateKeyRecord === void 0) throw new LockingDataNotFoundError();
1969
- const compilerData = await createLibauthCompilerDataFromUnspentOutput(new Template(template), unspentOutput, scriptHashData.outputIdentifier);
2470
+ const compilerData = await createLibauthCompilerDataFromUnspentOutput(new Template(template), unspentOutput);
1970
2471
  transactionResult.transaction.inputs[index] = {
1971
2472
  ...input,
1972
2473
  unlockingBytecode: {
@@ -1989,7 +2490,7 @@ var Engine = class Engine {
1989
2490
  unspentOutput = sourceOutput;
1990
2491
  break;
1991
2492
  }
1992
- if (unspentOutput === void 0) throw new UnspentOutputNotFoundInStoreError(`${binToHex(input.outpointTransactionHash)}:${String(input.outpointIndex)}`);
2493
+ if (unspentOutput === void 0) throw new UnspentOutputNotFoundError();
1993
2494
  let commitToExtend;
1994
2495
  let indexToExtend;
1995
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)) {
@@ -1998,10 +2499,10 @@ var Engine = class Engine {
1998
2499
  }
1999
2500
  if (commitToExtend === void 0 || indexToExtend === void 0) throw new CommitNotFoundInInvitationError();
2000
2501
  currentStoredInvitation = {
2001
- ...await this.#applyInvitationAppend(currentStoredInvitation, { inputs: [{
2502
+ ...await this.applyInvitationAppend(currentStoredInvitation, { inputs: [{
2002
2503
  mergesWith: {
2003
2504
  commitIdentifier: commitToExtend.commitIdentifier,
2004
- itemIndex: indexToExtend
2505
+ index: indexToExtend
2005
2506
  },
2006
2507
  unlockingBytecode: input.unlockingBytecode
2007
2508
  }] }),
@@ -2012,7 +2513,7 @@ var Engine = class Engine {
2012
2513
  }
2013
2514
  /**
2014
2515
  * Executes an action for a given invitation.
2015
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation whose action to execute.
2516
+ * @param {string} invitationIdentifier - The identifier of the invitation whose action to execute.
2016
2517
  * The invitation must already exist in the store.
2017
2518
  * @param {ExecuteActionParameters} params - Parameters for executing the action.
2018
2519
  * @returns {Promise<TransactionHash>} Resolves with the transaction hash when the action is executed.
@@ -2024,7 +2525,7 @@ var Engine = class Engine {
2024
2525
  const invitationFromStore = await this.getInvitationOrThrow(invitationIdentifier);
2025
2526
  const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
2026
2527
  const mergedCommit = mergeInvitationCommits(invitationFromStore, template);
2027
- if (mergedCommit === null) throw new MergedCommitNotFoundError();
2528
+ if (mergedCommit === void 0) throw new MergedCommitNotFoundError();
2028
2529
  if (new Template(template).getActionOrThrow(invitationFromStore.actionIdentifier).transaction === void 0) throw new TemplateTransactionNotFoundError(invitationFromStore.actionIdentifier);
2029
2530
  const resultTransaction = generateTransaction({
2030
2531
  version: mergedCommit.transactionVersion,
@@ -2042,8 +2543,8 @@ var Engine = class Engine {
2042
2543
  * Lists available roles for the given invitation.
2043
2544
  *
2044
2545
  * @param {XOInvitation} invitation - The invitation to examine.
2045
- * @returns {Promise<XOTemplateRoleIdentifier[]>} The list of roles that still require data.
2046
- * @throws {TemplateNotFoundInStoreError} If the template is not found.
2546
+ * @returns {Promise<string[]>} The list of roles that still require data.
2547
+ * @throws {TemplateNotFoundError} If the template is not found.
2047
2548
  * @throws {TemplateActionNotFoundError} If the action is not found.
2048
2549
  */
2049
2550
  async listAvailableRoles(invitation) {
@@ -2053,7 +2554,7 @@ var Engine = class Engine {
2053
2554
  * Lists requirements for the provided invitation.
2054
2555
  *
2055
2556
  * @param {XOInvitation} invitation - The invitation to analyze requirements for.
2056
- * @returns {Promise<InvitationRequirementIdentifierLists>} The requirements information.
2557
+ * @returns {Promise<XOInvitationRequirements>} The requirements information.
2057
2558
  *
2058
2559
  */
2059
2560
  async listRequirements(invitation) {
@@ -2063,9 +2564,8 @@ var Engine = class Engine {
2063
2564
  /**
2064
2565
  * Lists missing requirements for the provided invitation.
2065
2566
  *
2066
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation to analyze.
2067
- * The invitation must already exist in the store.
2068
- * @returns {Promise<InvitationRequirementIdentifierLists>} The missing requirements.
2567
+ * @param {string} invitationIdentifier - The identifier of the invitation to analyze. The invitation must already exist in the store.
2568
+ * @returns {Promise<XOInvitationRequirements>} The missing requirements.
2069
2569
  * @throws {InvitationNotFoundInStoreError} If the invitation is not found in the store.
2070
2570
  */
2071
2571
  async listMissingRequirements(invitationIdentifier) {
@@ -2079,7 +2579,7 @@ var Engine = class Engine {
2079
2579
  * @returns {Promise<UnspentOutputData[]>} The list of unspent outputs.
2080
2580
  */
2081
2581
  async listUnspentOutputsData() {
2082
- return this.#state.listUnspentOutputsData();
2582
+ return this.state.listUnspentOutputsData();
2083
2583
  }
2084
2584
  /**
2085
2585
  * Finds suitable resources for an invitation.
@@ -2090,30 +2590,19 @@ var Engine = class Engine {
2090
2590
  * @param {XOInvitation} invitation - The invitation to find resources for.
2091
2591
  * @param {GetSpendableResourcesParameters} options - Parameters for finding suitable resources.
2092
2592
  * @returns {Promise<{ unspentOutputs: UnspentOutputData[] }>} The list of suitable resources.
2093
- * @throws {FallbackLockingParametersMissingError} If options are omitted and fallback locking parameters are unset.
2094
2593
  */
2095
2594
  async getSpendableResources(invitation, options) {
2096
2595
  const { templateIdentifier } = invitation;
2097
- if (await this.#state.getTemplate(templateIdentifier) === void 0) throw new TemplateNotFoundInStoreError(templateIdentifier);
2098
- let sourceTemplateIdentifier;
2099
- let sourceOutputIdentifier;
2100
- if (options !== void 0) {
2101
- sourceTemplateIdentifier = options.templateIdentifier;
2102
- sourceOutputIdentifier = options.outputIdentifier;
2103
- } else {
2104
- const walletSettings = await this.#state.getWalletSettings();
2105
- if (walletSettings.fallbackLockingParameters !== void 0) {
2106
- sourceTemplateIdentifier = walletSettings.fallbackLockingParameters.templateIdentifier;
2107
- sourceOutputIdentifier = walletSettings.fallbackLockingParameters.outputIdentifier;
2108
- } else throw new FallbackLockingParametersMissingError();
2109
- }
2110
- const rawSourceTemplate = await this.#state.getTemplate(sourceTemplateIdentifier);
2111
- if (rawSourceTemplate === void 0) throw new TemplateNotFoundInStoreError(sourceTemplateIdentifier);
2596
+ if (await this.state.getTemplate(templateIdentifier) === void 0) throw new TemplateNotFoundError(templateIdentifier);
2597
+ const sourceTemplateIdentifier = options?.templateIdentifier ?? this.defaultTemplateIdentifier;
2598
+ const sourceOutputIdentifier = options?.outputIdentifier ?? this.defaultOutputIdentifier;
2599
+ const rawSourceTemplate = await this.state.getTemplate(sourceTemplateIdentifier);
2600
+ if (rawSourceTemplate === void 0) throw new TemplateNotFoundError(sourceTemplateIdentifier);
2112
2601
  new Template(rawSourceTemplate).getOutputOrThrow(sourceOutputIdentifier);
2113
- const scriptHashDataList = await this.#state.listScriptHashData({ templateIdentifier: sourceTemplateIdentifier });
2602
+ const scriptHashDataList = await this.state.listScriptHashData({ templateIdentifier: sourceTemplateIdentifier });
2114
2603
  const unspentOutputs = [];
2115
2604
  for (const scriptHashData of scriptHashDataList) {
2116
- const outputsByScriptHash = await this.#state.listUnspentOutputsData({ scriptHash: scriptHashData.scriptHash });
2605
+ const outputsByScriptHash = await this.state.listUnspentOutputsData({ scriptHash: scriptHashData.scriptHash });
2117
2606
  const unspentOutputsByScriptHash = [];
2118
2607
  for (const output of outputsByScriptHash) if (output.reservedBy === void 0) unspentOutputsByScriptHash.push(output);
2119
2608
  unspentOutputs.push(...unspentOutputsByScriptHash);
@@ -2123,11 +2612,11 @@ var Engine = class Engine {
2123
2612
  /**
2124
2613
  * Retrieves a list of script hash data stored for a given template identifier.
2125
2614
  *
2126
- * @param {XOTemplateIdentifier} templateIdentifier - The identifier of the template.
2615
+ * @param {string} templateIdentifier - The identifier of the template.
2127
2616
  * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.
2128
2617
  */
2129
2618
  async listScriptHashesForTemplate(templateIdentifier) {
2130
- return this.#state.listScriptHashData({ templateIdentifier });
2619
+ return this.state.listScriptHashData({ templateIdentifier });
2131
2620
  }
2132
2621
  /**
2133
2622
  * Gets all the script hashes from all the templates.
@@ -2135,7 +2624,7 @@ var Engine = class Engine {
2135
2624
  * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.
2136
2625
  */
2137
2626
  async listScriptHashes() {
2138
- const scriptHashDataPromises = (await this.#state.listTemplates()).map((template) => generateTemplateIdentifier$1(template)).map((templateIdentifier) => this.listScriptHashesForTemplate(templateIdentifier));
2627
+ const scriptHashDataPromises = (await this.state.listTemplates()).map((template) => generateTemplateIdentifier$1(template)).map((templateIdentifier) => this.listScriptHashesForTemplate(templateIdentifier));
2139
2628
  return (await Promise.all(scriptHashDataPromises)).flat();
2140
2629
  }
2141
2630
  /**
@@ -2166,9 +2655,9 @@ var Engine = class Engine {
2166
2655
  * TODO: If important to make this process faster, consider emitting an event and pushing process to the event loop.
2167
2656
  * TODO: Encrypt the new information, update the encrypted state servers.
2168
2657
  *
2169
- * @param {XOTemplateIdentifier} templateIdentifier - Identifier of the template.
2170
- * @param {XOTemplateOutputIdentifier} outputIdentifier - Identifier of the output (from the template).
2171
- * @param {XOTemplateRoleIdentifier} roleIdentifier - Role identifier (corresponding to a role in the output's script).
2658
+ * @param {string} templateIdentifier - Identifier of the template.
2659
+ * @param {string} outputIdentifier - Identifier of the output (from the template).
2660
+ * @param {string} roleIdentifier - Role identifier (corresponding to a role in the output's script).
2172
2661
  * @returns {Promise<string>} The generated locking bytecode as a hexadecimal string.
2173
2662
  * @throws {Error} If any required template, output, or configuration is not found, or if compilation fails.
2174
2663
  */
@@ -2185,7 +2674,6 @@ var Engine = class Engine {
2185
2674
  if (lockingScriptForOutput.unlockingBytecode === void 0 || lockingScriptForOutput.lockingBytecode === void 0) throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);
2186
2675
  const unlockingScripts = { [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode };
2187
2676
  const { lockingType } = lockingScriptForOutput;
2188
- if (lockingType === void 0) throw new TemplateLockingScriptTypeNotFoundError(outputIdentifier);
2189
2677
  const compiler = createCompilerBch({
2190
2678
  entityOwnership,
2191
2679
  scripts,
@@ -2193,18 +2681,16 @@ var Engine = class Engine {
2193
2681
  unlockingScripts,
2194
2682
  lockingScriptTypes: { lock: convertXOLockingTypeToLibauth(lockingType) }
2195
2683
  });
2684
+ let lockingBytecodeMetadata = { lockingType: lockingScriptForOutput.lockingType };
2196
2685
  let lockingData;
2197
- let scriptHashSecrets;
2198
2686
  switch (lockingScriptForOutput.lockingType) {
2199
- case XOTemplateLockingTypes.P2PKH: {
2200
- const { lockingData: standardLockingData, derivativeIndex: standardDerivativeIndex, secretIdentifiers } = await this.generateLockingDataForStandardP2PKH(templateIdentifier, finalRoleIdentifier, lockingScriptForOutput);
2687
+ case "p2pkh": {
2688
+ const { lockingData: standardLockingData, derivativeIndex: standardDerivativeIndex } = await this.generateLockingDataForStandardP2PKH(templateIdentifier, outputIdentifier, finalRoleIdentifier, lockingScriptForOutput);
2201
2689
  lockingData = standardLockingData;
2202
- const secrets = {};
2203
- for (const secretIdentifier of secretIdentifiers) secrets[secretIdentifier] = {
2204
- lockingType: lockingScriptForOutput.lockingType,
2690
+ lockingBytecodeMetadata = {
2691
+ ...lockingBytecodeMetadata,
2205
2692
  derivativeIndex: standardDerivativeIndex
2206
2693
  };
2207
- scriptHashSecrets = secrets;
2208
2694
  break;
2209
2695
  }
2210
2696
  default: throw new TemplateLockingScriptTypeNotFoundError(output.lockingScript ?? outputIdentifier);
@@ -2218,14 +2704,14 @@ var Engine = class Engine {
2218
2704
  if (!resultLockingBytecode.success) throw new LockingBytecodeGenerationFailedError();
2219
2705
  const lockingBytecode = binToHex(resultLockingBytecode.bytecode);
2220
2706
  const scriptHash = scriptToScriptHash(hexToBin(lockingBytecode));
2221
- const existingScriptHashData = await this.#state.getScriptHashData(scriptHash);
2707
+ const existingScriptHashData = await this.state.getScriptHashData(scriptHash);
2222
2708
  if (existingScriptHashData) return existingScriptHashData.lockingBytecode;
2223
2709
  const [firstElectrumClient] = electrumClients.values();
2224
2710
  if (!firstElectrumClient) throw new ElectrumClientNotFoundError();
2225
2711
  await subscribeToScriptHashUpdates(firstElectrumClient, scriptHash);
2226
- await this.#state.storeScriptHashData({
2712
+ await this.state.storeScriptHashData({
2227
2713
  lockingBytecode,
2228
- secrets: scriptHashSecrets,
2714
+ derivationSource: lockingBytecodeMetadata,
2229
2715
  scriptHash,
2230
2716
  templateIdentifier,
2231
2717
  outputIdentifier,
@@ -2235,52 +2721,49 @@ var Engine = class Engine {
2235
2721
  return lockingBytecode;
2236
2722
  }
2237
2723
  /**
2238
- * Generates a locking bytecode using the engine's fallback locking parameters.
2724
+ * Generates a locking bytecode using the engine's default template, output, and role identifiers.
2239
2725
  *
2240
- * @returns {Promise<string>} The generated locking bytecode as a hexadecimal string.
2241
- * @throws {FallbackLockingParametersMissingError} If fallback locking parameters have not been set.
2726
+ * @returns A promise that resolves to the generated locking bytecode as a string.
2242
2727
  */
2243
- async generateLockingBytecodeFromFallbackParameters() {
2244
- const walletSettings = await this.#state.getWalletSettings();
2245
- if (walletSettings.fallbackLockingParameters === void 0) throw new FallbackLockingParametersMissingError();
2246
- return this.generateLockingBytecode(walletSettings.fallbackLockingParameters.templateIdentifier, walletSettings.fallbackLockingParameters.outputIdentifier, walletSettings.fallbackLockingParameters.roleIdentifier);
2728
+ async generateLockingBytecodeForDefaultParameters() {
2729
+ return this.generateLockingBytecode(this.defaultTemplateIdentifier, this.defaultOutputIdentifier, this.defaultRoleIdentifier);
2247
2730
  }
2248
2731
  /**
2249
2732
  * Generate locking data and derivative index for P2PKH.
2250
2733
  */
2251
- async generateLockingDataForStandardP2PKH(templateIdentifier, roleIdentifier, lockingScriptForOutput) {
2252
- const derivativeIndex = await this.#state.generateNextDerivativeIndex(templateIdentifier);
2734
+ async generateLockingDataForStandardP2PKH(templateIdentifier, outputIdentifier, roleIdentifier, lockingScriptForOutput) {
2735
+ const lastDerivativeIndex = await this.state.getLastDerivativeIndexForP2PKH(templateIdentifier, outputIdentifier);
2736
+ const derivativeIndex = lastDerivativeIndex === null ? "0" : (parseInt(lastDerivativeIndex, 10) + 1).toString();
2253
2737
  const privateKeyIdentifiers = (lockingScriptForOutput.roles?.[roleIdentifier])?.state?.secrets ?? [];
2254
2738
  return {
2255
- lockingData: this.#crypto.derivePrivateKeyRecordForCompiler({
2739
+ lockingData: this.crypto.derivePrivateKeyRecordForCompiler({
2256
2740
  compilerKeyIdentifiers: privateKeyIdentifiers,
2257
2741
  templateIdentifier,
2258
- templateKeyDerivationIndex: derivativeIndex
2742
+ templateKeyDerivationIndex: Number(derivativeIndex)
2259
2743
  }),
2260
- derivativeIndex,
2261
- secretIdentifiers: privateKeyIdentifiers
2744
+ derivativeIndex
2262
2745
  };
2263
2746
  }
2264
2747
  /**
2265
2748
  * Fetches a stored invitation by identifier
2266
2749
  *
2267
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier to look up.
2750
+ * @param {string} invitationIdentifier - The identifier to look up.
2268
2751
  * @returns {Promise<StoredInvitation | undefined>} The stored invitation, or undefined.
2269
2752
  */
2270
2753
  async getInvitationOrThrow(invitationIdentifier) {
2271
- const invitation = await this.#state.getInvitation(invitationIdentifier);
2754
+ const invitation = await this.state.getInvitation(invitationIdentifier);
2272
2755
  if (invitation === void 0) throw new InvitationNotFoundInStoreError(invitationIdentifier);
2273
2756
  return invitation;
2274
2757
  }
2275
2758
  /**
2276
2759
  * Fetches a stored template by identifier
2277
2760
  *
2278
- * @param {XOTemplateIdentifier} templateIdentifier - The identifier to look up.
2761
+ * @param {string} templateIdentifier - The identifier to look up.
2279
2762
  * @returns {Promise<XOTemplate>} The stored template.
2280
2763
  */
2281
2764
  async getTemplateOrThrow(templateIdentifier) {
2282
- const template = await this.#state.getTemplate(templateIdentifier);
2283
- if (template === void 0) throw new TemplateNotFoundInStoreError(templateIdentifier);
2765
+ const template = await this.state.getTemplate(templateIdentifier);
2766
+ if (template === void 0) throw new TemplateNotFoundError(templateIdentifier);
2284
2767
  return template;
2285
2768
  }
2286
2769
  /**
@@ -2294,13 +2777,13 @@ var Engine = class Engine {
2294
2777
  * 5. Adds any new unspent outputs found on the blockchain but missing from the store to the store.
2295
2778
  * 6. Removes any unspent outputs present in the store but no longer in the blockchain.
2296
2779
  *
2297
- * @param {string} scriptHash - The script hash for which to update the stored unspent outputs.
2298
- * @throws {ScriptHashDataNotFoundError} If the script hash is not found in the store.
2780
+ * @param scriptHash - The script hash for which to update the stored unspent outputs.
2781
+ * @throws If the script hash is not found in the store.
2299
2782
  */
2300
2783
  async updateUnspentOutputsForScriptHashInStore(scriptHash) {
2301
2784
  const [firstElectrumClient] = electrumClients.values();
2302
2785
  if (!firstElectrumClient) throw new ElectrumClientNotFoundError();
2303
- await updateUnspentOutputsForScriptHashInStore(this.#state, scriptHash, async (scripthash) => {
2786
+ await updateUnspentOutputsForScriptHashInStore(this.state, scriptHash, async (scripthash) => {
2304
2787
  return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scripthash);
2305
2788
  });
2306
2789
  }
@@ -2312,7 +2795,7 @@ var Engine = class Engine {
2312
2795
  * @param {XOInvitationInput[]} inputs - The inputs to find resources for.
2313
2796
  * @returns {Promise<XOInvitationInput[]>} The list of own inputs for reservation.
2314
2797
  */
2315
- async #findOwnResources(inputs) {
2798
+ async findOwnResources(inputs) {
2316
2799
  const inputsForReservation = [];
2317
2800
  if (inputs) for (const input of inputs) {
2318
2801
  if (input.mergesWith) continue;
@@ -2334,16 +2817,15 @@ var Engine = class Engine {
2334
2817
  * @param {AppendInvitationParameters} params - The parameters to append.
2335
2818
  * @returns {Promise<XOInvitation>} The updated invitation after the new commit is applied.
2336
2819
  */
2337
- async #applyInvitationAppend(storedInvitation, params) {
2338
- if (storedInvitation.entityIdentifier === void 0) throw new EntityIdentifierNotFoundInInvitationError(storedInvitation.invitationIdentifier);
2820
+ async applyInvitationAppend(storedInvitation, params) {
2339
2821
  const rootCommitIdentifier = findRootCommitIdentifierInInvitation(storedInvitation, storedInvitation.entityIdentifier);
2340
- if (rootCommitIdentifier === void 0) throw new RootCommitNotFoundInInvitationError(storedInvitation.invitationIdentifier);
2822
+ if (rootCommitIdentifier === void 0) throw new RootCommitNotFoundError(storedInvitation.entityIdentifier);
2341
2823
  if (params.outputs !== void 0) for (const output of params.outputs) {
2342
2824
  if (output.mergesWith !== void 0 || output.roleIdentifier !== void 0 || output.lockingBytecode !== void 0) continue;
2343
- output.lockingBytecode = hexToBin(await this.generateLockingBytecodeFromFallbackParameters());
2825
+ output.lockingBytecode = hexToBin(await this.generateLockingBytecodeForDefaultParameters());
2344
2826
  }
2345
2827
  const invitationBuilder = InvitationBuilder.fromInvitation(storedInvitation);
2346
- const signedCommit = this.#crypto.signInvitationCommitWithSchnorr({
2828
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2347
2829
  invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),
2348
2830
  invitationIdentifier: invitationBuilder.invitationIdentifier,
2349
2831
  rootCommitIdentifier,
@@ -2351,20 +2833,23 @@ var Engine = class Engine {
2351
2833
  actionIdentifier: invitationBuilder.actionIdentifier
2352
2834
  });
2353
2835
  invitationBuilder.addCommit(signedCommit);
2354
- const inputsForReservation = await this.#findOwnResources(params.inputs ?? []);
2355
- if (inputsForReservation.length > 0) await this.#reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);
2836
+ const inputsForReservation = await this.findOwnResources(params.inputs ?? []);
2837
+ if (inputsForReservation.length > 0) await this.reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);
2356
2838
  const updatedInvitation = invitationBuilder.build();
2357
- await this.#state.updateInvitation(updatedInvitation.invitationIdentifier, updatedInvitation);
2839
+ await this.state.storeInvitation(updatedInvitation.invitationIdentifier, {
2840
+ ...updatedInvitation,
2841
+ entityIdentifier: storedInvitation.entityIdentifier
2842
+ });
2358
2843
  return updatedInvitation;
2359
2844
  }
2360
2845
  /**
2361
2846
  * Reserves utxos and store information in the storage.
2362
2847
  *
2363
2848
  * @param {XOInvitationInput[]} inputs - The inputs to reserve.
2364
- * @param {XOInvitationIdentifier} invitationIdentifier - The identifier of the invitation for which the resources are being reserved.
2849
+ * @param {string} invitationIdentifier - The identifier of the invitation for which the resources are being reserved.
2365
2850
  * @returns {Promise<void>} Resolves when the reservation is complete.
2366
2851
  */
2367
- async #reserveResources(inputs, invitationIdentifier) {
2852
+ async reserveResources(inputs, invitationIdentifier) {
2368
2853
  const outpoints = [];
2369
2854
  for (const input of inputs) {
2370
2855
  if (!input.outpointTransactionHash || input.outpointIndex === void 0) throw new InvalidInputError();
@@ -2373,10 +2858,10 @@ var Engine = class Engine {
2373
2858
  outpointIndex: input.outpointIndex
2374
2859
  });
2375
2860
  }
2376
- await this.#state.executeBulkUnspentOutputReservation(outpoints, true, invitationIdentifier);
2861
+ await this.state.executeBulkUnspentOutputReservation(outpoints, true, invitationIdentifier);
2377
2862
  }
2378
2863
  };
2379
2864
 
2380
2865
  //#endregion
2381
- export { BlockchainMonitor, CircularMergeReferenceError, CommitEntityIdentifierNotFoundError, CommitNotFoundInInvitationError, CommitNotSignedError, DuplicateTransactionIndexError, DuplicateTransactionLocktimeError, DuplicateTransactionVersionError, ElectrumClientNotFoundError, Engine, EntityIdentifierNotFoundInInvitationError, FallbackLockingParametersMissingError, InvalidCommitSignaturesError, InvalidEntityIdentifierError, InvalidInputError, InvalidLockingScriptTypeError, InvalidLockingTypeError, InvalidRequirementsError, InvalidVariableDefinitionError, InvitationBuilder, InvitationExpiredError, InvitationTemplateMismatchError, ItemNotFoundInCommitError, LockingBytecodeGenerationFailedError, LockingBytecodeNotFoundForOutputError, LockingDataNotFoundError, MergedCommitNotFoundError, MergesWithCommitNotFoundError, P2PKHDerivativeIndexMissingError, ParentCommitNotFoundInInvitationError, RootCommitNotFoundInInvitationError, ScriptHashDataNotFoundError, Template, TemplateActionNotFoundError, TemplateLockingScriptInOutputNotFoundError, TemplateLockingScriptNotFoundError, TemplateLockingScriptRoleNotFoundError, TemplateLockingScriptTypeNotFoundError, TemplateOutputNotFoundError, TemplateTransactionNotFoundError, TransactionGenerationFailedError, UnlockingScriptNotFoundError, assignTypeToVariablesForLibauthCompiler, convertCommitVariablesIntoObject, convertXOLockingTypeToLibauth, createLibauthCompilerDataFromUnspentOutput, entityOwnershipForLibauthCompiler, findRootCommitIdentifierInInvitation, generateCommitIdentifier, generateTemplateIdentifier, hasInvitationExpired, 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 };
2382
2867
  //# sourceMappingURL=index.mjs.map