@xo-cash/engine 0.0.1-development.14109350676

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 ADDED
@@ -0,0 +1,2724 @@
1
+ import { binToHex, createCompilerBch, encodeTransaction, generateRandomBytes, generateTransaction, hash256, hashTransaction, hexToBin, sha256, stringify, utf8ToBin } 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";
5
+ import { broadcastTransaction, electrumClients, electrumEvents, getChainStatus, initializeElectrumApplication, stopElectrumNetwork } from "@electrum-cash/application";
6
+ import { fetchScriptHashUnspentTransactionOutputs, subscribeToScriptHashUpdates } from "@electrum-cash/protocol";
7
+ import { electrumServers } from "@electrum-cash/servers";
8
+ import { PublicKey } from "@xo-cash/primitives";
9
+
10
+ //#region source/errors.ts
11
+ /**
12
+ * Error thrown when an action is not found in the template.
13
+ */
14
+ var ActionNotFoundError = class extends Error {
15
+ constructor(actionIdentifier) {
16
+ const defaultMessage = "Action not found in template";
17
+ super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
18
+ }
19
+ };
20
+ /**
21
+ * Error thrown when an output is not found in the template.
22
+ */
23
+ var OutputNotFoundError = class extends Error {
24
+ constructor(outputIdentifier) {
25
+ const defaultMessage = "Output not found in template";
26
+ super(outputIdentifier ? `${defaultMessage}: outputIdentifier "${outputIdentifier}"` : defaultMessage);
27
+ }
28
+ };
29
+ /**
30
+ * Error thrown when a template is not found.
31
+ */
32
+ var TemplateNotFoundError = class extends Error {
33
+ constructor(templateIdentifier) {
34
+ const defaultMessage = "Template not found";
35
+ super(templateIdentifier ? `${defaultMessage}: templateIdentifier "${templateIdentifier}"` : defaultMessage);
36
+ }
37
+ };
38
+ /**
39
+ * Error thrown when a locking script is not found in the template.
40
+ */
41
+ var LockingScriptNotFoundError = class extends Error {
42
+ constructor(lockingScriptIdentifier) {
43
+ const defaultMessage = "Locking script not found in template";
44
+ super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier "${lockingScriptIdentifier}"` : defaultMessage);
45
+ }
46
+ };
47
+ /**
48
+ * Error thrown when a locking script type is not found in the template.
49
+ */
50
+ var LockingScriptTypeNotFoundError = class extends Error {
51
+ constructor(lockingScriptIdentifier) {
52
+ const defaultMessage = "Locking script type not found in template";
53
+ super(lockingScriptIdentifier ? `${defaultMessage}: lockingScriptIdentifier "${lockingScriptIdentifier}"` : defaultMessage);
54
+ }
55
+ };
56
+ /**
57
+ * Error thrown when a lockscript is not found in the template.
58
+ */
59
+ var LockscriptNotFoundError = class extends Error {
60
+ constructor(lockscriptIdentifier) {
61
+ const defaultMessage = "Lockscript not found in template";
62
+ super(lockscriptIdentifier ? `${defaultMessage}: lockscriptIdentifier "${lockscriptIdentifier}"` : defaultMessage);
63
+ }
64
+ };
65
+ /**
66
+ * Error thrown when an unlocking script is not found in the template.
67
+ */
68
+ var UnlockingScriptNotFoundError = class extends Error {
69
+ constructor(unlockingScriptIdentifier) {
70
+ const defaultMessage = "Unlocking script not found in template";
71
+ super(unlockingScriptIdentifier ? `${defaultMessage}: unlockingScriptIdentifier "${unlockingScriptIdentifier}"` : defaultMessage);
72
+ }
73
+ };
74
+ /**
75
+ * Error thrown when a script is not found in the template.
76
+ */
77
+ var ScriptNotFoundError = class extends Error {
78
+ constructor(scriptIdentifier) {
79
+ const defaultMessage = "Script not found in template";
80
+ super(scriptIdentifier ? `${defaultMessage}: scriptIdentifier "${scriptIdentifier}"` : defaultMessage);
81
+ }
82
+ };
83
+ /**
84
+ * Error thrown when a starting action is not found in the template.
85
+ */
86
+ var StartingActionNotFoundError = class extends Error {
87
+ constructor(templateIdentifier) {
88
+ const defaultMessage = "Starting action not found in template";
89
+ super(templateIdentifier ? `${defaultMessage}: templateIdentifier "${templateIdentifier}"` : defaultMessage);
90
+ }
91
+ };
92
+ /**
93
+ * Error thrown when a transaction is not found in the template.
94
+ */
95
+ var TransactionNotFoundError = class extends Error {
96
+ constructor(transactionIdentifier) {
97
+ const defaultMessage = "Transaction not found in template";
98
+ super(transactionIdentifier ? `${defaultMessage}: transactionIdentifier "${transactionIdentifier}"` : defaultMessage);
99
+ }
100
+ };
101
+ /**
102
+ * Error thrown when a commit entity identifier is not found.
103
+ */
104
+ var CommitEntityIdentifierNotFoundError = class extends Error {
105
+ constructor(commitIdentifier) {
106
+ const defaultMessage = "Commit entity identifier not found";
107
+ super(commitIdentifier ? `${defaultMessage}: commitIdentifier "${commitIdentifier}"` : defaultMessage);
108
+ }
109
+ };
110
+ /**
111
+ * Error thrown when a commit is not signed.
112
+ */
113
+ var CommitNotSignedError = class extends Error {
114
+ constructor(commitIdentifier) {
115
+ const defaultMessage = "Commit not signed";
116
+ super(commitIdentifier ? `${defaultMessage}: commitIdentifier "${commitIdentifier}"` : defaultMessage);
117
+ }
118
+ };
119
+ /**
120
+ * Error thrown when a commit is not found in the invitation.
121
+ */
122
+ var CommitNotFoundInInvitationError = class extends Error {
123
+ constructor(commitIdentifier) {
124
+ const defaultMessage = "Commit not found in invitation";
125
+ super(commitIdentifier ? `${defaultMessage}: commitIdentifier "${commitIdentifier}"` : defaultMessage);
126
+ }
127
+ };
128
+ /**
129
+ * Error thrown when one or more entity identifiers are invalid.
130
+ */
131
+ var InvalidEntityIdentifierError = class extends Error {
132
+ constructor(entityIdentifiers) {
133
+ const defaultMessage = "One or more entity identifiers are invalid";
134
+ if (entityIdentifiers && entityIdentifiers.length > 0) super(`${defaultMessage}: entityIdentifiers [${entityIdentifiers.join(", ")}]`);
135
+ else super(defaultMessage);
136
+ }
137
+ };
138
+ /**
139
+ * Error thrown when one or more provided requirements were not expected by the template.
140
+ */
141
+ var InvalidRequirementsError = class extends Error {
142
+ constructor(requirementIdentifiers) {
143
+ const defaultMessage = "One or more provided requirements were not expected by the template";
144
+ if (requirementIdentifiers && requirementIdentifiers.length > 0) super(`${defaultMessage}: requirementIdentifiers [${requirementIdentifiers.join(", ")}]`);
145
+ else super(defaultMessage);
146
+ }
147
+ };
148
+ /**
149
+ * Error thrown when one or more commit signatures are invalid.
150
+ */
151
+ var InvalidCommitSignaturesError = class extends Error {
152
+ constructor(commitIdentifiers) {
153
+ const defaultMessage = "One or more commit signatures are invalid";
154
+ if (commitIdentifiers && commitIdentifiers.length > 0) super(`${defaultMessage}: commitIdentifiers [${commitIdentifiers.join(", ")}]`);
155
+ else super(defaultMessage);
156
+ }
157
+ };
158
+ /**
159
+ * Error thrown when an invitation is not found in the store.
160
+ */
161
+ var InvitationNotFoundInStoreError = class extends Error {
162
+ constructor(invitationIdentifier) {
163
+ const defaultMessage = "Invitation not found in store";
164
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
165
+ }
166
+ };
167
+ /**
168
+ * Error thrown when an invitation has already been accepted.
169
+ */
170
+ var InvitationAlreadyAcceptedError = class extends Error {
171
+ constructor(invitationIdentifier) {
172
+ const defaultMessage = "Invitation already accepted";
173
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
174
+ }
175
+ };
176
+ /**
177
+ * Error thrown when an invitation was created in the future.
178
+ */
179
+ var InvitationCreatedInFutureError = class extends Error {
180
+ constructor(invitationIdentifier) {
181
+ const defaultMessage = "Invitation created in the future";
182
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
183
+ }
184
+ };
185
+ /**
186
+ * Error thrown when an invitation has expired.
187
+ */
188
+ var InvitationExpiredError = class extends Error {
189
+ constructor(invitationIdentifier) {
190
+ const defaultMessage = "Invitation expired";
191
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
192
+ }
193
+ };
194
+ /**
195
+ * Error thrown when an invitation has not been accepted.
196
+ */
197
+ var InvitationNotAcceptedError = class extends Error {
198
+ constructor(invitationIdentifier) {
199
+ const defaultMessage = "Invitation not accepted";
200
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
201
+ }
202
+ };
203
+ /**
204
+ * Error thrown when an invitation is invalid.
205
+ */
206
+ var InvalidInvitationError = class extends Error {
207
+ constructor(invitationIdentifier) {
208
+ const defaultMessage = "Invalid invitation";
209
+ super(invitationIdentifier ? `${defaultMessage}: invitationIdentifier "${invitationIdentifier}"` : defaultMessage);
210
+ }
211
+ };
212
+ /**
213
+ * Error thrown when a merged commit is not found.
214
+ */
215
+ var MergedCommitNotFoundError = class extends Error {
216
+ constructor() {
217
+ super("Merged commit not found");
218
+ }
219
+ };
220
+ /**
221
+ * Error thrown when the script hash data record for a given script hash is not found in the store.
222
+ */
223
+ var ScriptHashDataNotFoundError = class extends Error {
224
+ constructor(scriptHash) {
225
+ const defaultMessage = "Script hash data not found in store";
226
+ super(scriptHash ? `${defaultMessage}: scriptHash "${scriptHash}"` : defaultMessage);
227
+ }
228
+ };
229
+ /**
230
+ * Error thrown when the root commit for an entity cannot be found in the invitation.
231
+ */
232
+ var RootCommitNotFoundError = class extends Error {
233
+ constructor(entityIdentifier) {
234
+ const defaultMessage = "Root commit not found in invitation";
235
+ super(entityIdentifier ? `${defaultMessage}: entityIdentifier "${entityIdentifier}"` : defaultMessage);
236
+ }
237
+ };
238
+ /**
239
+ * Error thrown when a parent commit is not found.
240
+ */
241
+ var ParentCommitNotFoundError = class extends Error {
242
+ constructor(parentCommitIdentifier, commitIdentifier) {
243
+ super(`Parent commit not found: ${parentCommitIdentifier} (referenced by commit ${commitIdentifier})`);
244
+ }
245
+ };
246
+ /**
247
+ * Error thrown when duplicate transactionIndex values are found.
248
+ */
249
+ var DuplicateTransactionIndexError = class extends Error {
250
+ constructor(itemType, duplicateIndices) {
251
+ const uniqueDuplicates = [...new Set(duplicateIndices)];
252
+ super(`Duplicate ${itemType} transactionIndex values found: ${uniqueDuplicates.join(", ")}`);
253
+ }
254
+ };
255
+ /**
256
+ * Error thrown when a circular merge reference is detected.
257
+ */
258
+ var CircularMergeReferenceError = class extends Error {
259
+ constructor(itemType, mergeKey, commitIdentifier) {
260
+ super(`Circular merge reference detected for ${itemType}: ${mergeKey} (in commit ${commitIdentifier})`);
261
+ }
262
+ };
263
+ /**
264
+ * Error thrown when a mergesWith commit is not found.
265
+ */
266
+ var MergesWithCommitNotFoundError = class extends Error {
267
+ constructor(mergesWithCommitIdentifier, currentCommitIdentifier) {
268
+ super(`Merges with commit not found: ${mergesWithCommitIdentifier} (referenced by commit ${currentCommitIdentifier})`);
269
+ }
270
+ };
271
+ /**
272
+ * Error thrown when an item at a specific index is not found in a commit.
273
+ */
274
+ var ItemNotFoundInCommitError = class extends Error {
275
+ constructor(itemType, index, commitIdentifier) {
276
+ const capitalizedType = itemType.charAt(0).toUpperCase() + itemType.slice(1);
277
+ super(`${capitalizedType} at index ${index} not found in commit ${commitIdentifier}`);
278
+ }
279
+ };
280
+ /**
281
+ * Error thrown when locking bytecode is not found for an output.
282
+ */
283
+ var LockingBytecodeNotFoundForOutputError = class extends Error {
284
+ constructor(outputIdentifier, transactionIndex) {
285
+ const indexInfo = transactionIndex !== void 0 ? ` (transactionIndex: ${transactionIndex})` : " (transactionIndex: undefined)";
286
+ super(`Locking bytecode not found for output: ${outputIdentifier}${indexInfo}`);
287
+ }
288
+ };
289
+ /**
290
+ * Error thrown when transaction version is defined multiple times in commits.
291
+ */
292
+ var DuplicateTransactionVersionError = class extends Error {
293
+ constructor(commitIdentifiers) {
294
+ super(`Transaction version is defined in multiple commits: ${commitIdentifiers.join(", ")}`);
295
+ }
296
+ };
297
+ /**
298
+ * Error thrown when transaction locktime is defined multiple times in commits.
299
+ */
300
+ var DuplicateTransactionLocktimeError = class extends Error {
301
+ constructor(commitIdentifiers) {
302
+ super(`Transaction locktime is defined in multiple commits: ${commitIdentifiers.join(", ")}`);
303
+ }
304
+ };
305
+ var TemplateIdentifierMismatchError = class extends Error {
306
+ constructor() {
307
+ super("Template identifier mismatch");
308
+ }
309
+ };
310
+ /**
311
+ * Error thrown when an unspent output is not found.
312
+ */
313
+ var UnspentOutputNotFoundError = class extends Error {
314
+ constructor(outpointIdentifier) {
315
+ const defaultMessage = "Unspent output not found";
316
+ super(outpointIdentifier ? `${defaultMessage}: outpointIdentifier "${outpointIdentifier}"` : defaultMessage);
317
+ }
318
+ };
319
+ /**
320
+ * Error thrown when a role is invalid.
321
+ */
322
+ var InvalidRoleError = class extends Error {
323
+ constructor(roleIdentifier) {
324
+ const defaultMessage = "Invalid role";
325
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
326
+ }
327
+ };
328
+ /**
329
+ * Error thrown when there are multiple roles for the starting action.
330
+ */
331
+ var MultipleRolesForStartingActionError = class extends Error {
332
+ constructor(actionIdentifier) {
333
+ const defaultMessage = "Multiple roles for starting action";
334
+ super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
335
+ }
336
+ };
337
+ /**
338
+ * Error thrown when no role is specified and multiple roles are available to be accepted.
339
+ */
340
+ var NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError = class extends Error {
341
+ constructor() {
342
+ super("No role specified and multiple roles available to be accepted");
343
+ }
344
+ };
345
+ /**
346
+ * Error thrown when a role has already been accepted by another entity.
347
+ */
348
+ var RoleAlreadyAcceptedByAnotherEntityError = class extends Error {
349
+ constructor(roleIdentifier) {
350
+ const defaultMessage = "Role already accepted by another entity";
351
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
352
+ }
353
+ };
354
+ /**
355
+ * Error thrown when a role cannot start an action.
356
+ */
357
+ var RoleCannotStartActionError = class extends Error {
358
+ constructor(roleIdentifier, actionIdentifier) {
359
+ const defaultMessage = "Role cannot start action";
360
+ if (roleIdentifier && actionIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", actionIdentifier "${actionIdentifier}"`);
361
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
362
+ else if (actionIdentifier) super(`${defaultMessage}: actionIdentifier "${actionIdentifier}"`);
363
+ else super(defaultMessage);
364
+ }
365
+ };
366
+ /**
367
+ * Error thrown when a role is not available to be accepted.
368
+ */
369
+ var RoleNotAvailableToBeAcceptedError = class extends Error {
370
+ constructor(roleIdentifier) {
371
+ const defaultMessage = "Role not available to be accepted";
372
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
373
+ }
374
+ };
375
+ /**
376
+ * Error thrown when a role is not defined for an action.
377
+ */
378
+ var RoleNotDefinedForActionError = class extends Error {
379
+ constructor(roleIdentifier, actionIdentifier) {
380
+ const defaultMessage = "Role not defined for action";
381
+ if (roleIdentifier && actionIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", actionIdentifier "${actionIdentifier}"`);
382
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
383
+ else if (actionIdentifier) super(`${defaultMessage}: actionIdentifier "${actionIdentifier}"`);
384
+ else super(defaultMessage);
385
+ }
386
+ };
387
+ /**
388
+ * Error thrown when a role is not found.
389
+ */
390
+ var RoleNotFoundError = class extends Error {
391
+ constructor(roleIdentifier) {
392
+ const defaultMessage = "Role not found";
393
+ super(roleIdentifier ? `${defaultMessage}: roleIdentifier "${roleIdentifier}"` : defaultMessage);
394
+ }
395
+ };
396
+ /**
397
+ * Error thrown when a data type is invalid.
398
+ */
399
+ var InvalidDataTypeError = class extends Error {
400
+ constructor() {
401
+ super("Invalid data type");
402
+ }
403
+ };
404
+ /**
405
+ * Error thrown when a variable type is invalid.
406
+ */
407
+ var InvalidVariableTypeError = class extends Error {
408
+ constructor(variableKey, expectedType, actualType) {
409
+ super(`Invalid variable type: variableKey "${variableKey}", expected ${expectedType}, got ${actualType}`);
410
+ }
411
+ };
412
+ /**
413
+ * Error thrown when a required variable is missing.
414
+ */
415
+ var MissingRequiredVariableError = class extends Error {
416
+ constructor(variableNames) {
417
+ const defaultMessage = "Missing required variable";
418
+ if (variableNames && variableNames.length > 0) super(`${defaultMessage}: variableNames [${variableNames.join(", ")}]`);
419
+ else super(defaultMessage);
420
+ }
421
+ };
422
+ /**
423
+ * Error thrown when an unknown variable is provided.
424
+ */
425
+ var UnknownVariableError = class extends Error {
426
+ constructor(variableKey) {
427
+ const defaultMessage = "Unknown variable provided";
428
+ super(variableKey ? `${defaultMessage}: variableKey "${variableKey}"` : defaultMessage);
429
+ }
430
+ };
431
+ /**
432
+ * Error thrown when a variable is required but not provided.
433
+ */
434
+ var VariableRequiredError = class extends Error {
435
+ constructor(variableKey) {
436
+ const defaultMessage = "Variable required";
437
+ super(variableKey ? `${defaultMessage}: variableKey "${variableKey}"` : defaultMessage);
438
+ }
439
+ };
440
+ /**
441
+ * Error thrown when variable validation fails.
442
+ */
443
+ var VariableValidationFailedError = class extends Error {
444
+ constructor(variableNames) {
445
+ const defaultMessage = "Variable validation failed";
446
+ if (variableNames && variableNames.length > 0) super(`${defaultMessage}: variableNames [${variableNames.join(", ")}]`);
447
+ else super(defaultMessage);
448
+ }
449
+ };
450
+ /**
451
+ * Error thrown when an action is invalid for an invitation.
452
+ */
453
+ var InvalidActionError = class extends Error {
454
+ constructor(actionIdentifier) {
455
+ const defaultMessage = "Invalid action for invitation";
456
+ super(actionIdentifier ? `${defaultMessage}: actionIdentifier "${actionIdentifier}"` : defaultMessage);
457
+ }
458
+ };
459
+ /**
460
+ * Error thrown when cash assembly compilation fails.
461
+ */
462
+ var CashAssemblyCompilationFailedError = class extends Error {
463
+ constructor(message) {
464
+ const defaultMessage = "Cash assembly compilation failed";
465
+ super(message ? `${defaultMessage}: ${message}` : defaultMessage);
466
+ }
467
+ };
468
+ /**
469
+ * Error thrown when locking bytecode generation fails.
470
+ */
471
+ var LockingBytecodeGenerationFailedError = class extends Error {
472
+ constructor() {
473
+ super("Failed to generate locking bytecode");
474
+ }
475
+ };
476
+ /**
477
+ * Error thrown when locking data is not found.
478
+ */
479
+ var LockingDataNotFoundError = class extends Error {
480
+ constructor() {
481
+ super("Locking data not found");
482
+ }
483
+ };
484
+ /**
485
+ * Error thrown when transaction generation fails.
486
+ */
487
+ var TransactionGenerationFailedError = class extends Error {
488
+ constructor() {
489
+ super("Failed to generate transaction");
490
+ }
491
+ };
492
+ /**
493
+ * Error thrown when the created by identifier is already set.
494
+ */
495
+ var CreatedByIdentifierAlreadySetError = class extends Error {
496
+ constructor() {
497
+ super("Created by identifier already set");
498
+ }
499
+ };
500
+ /**
501
+ * Error thrown when the created by identifier signature is already set.
502
+ */
503
+ var CreatedByIdentifierSignatureAlreadySetError = class extends Error {
504
+ constructor() {
505
+ super("Created by identifier signature already set");
506
+ }
507
+ };
508
+ /**
509
+ * Error thrown when data is not found in the template.
510
+ */
511
+ var DataNotFoundError = class extends Error {
512
+ constructor() {
513
+ super("Data not found in template");
514
+ }
515
+ };
516
+ /**
517
+ * Error thrown when input is invalid.
518
+ */
519
+ var InvalidInputError = class extends Error {
520
+ constructor() {
521
+ super("Invalid input");
522
+ }
523
+ };
524
+ /**
525
+ * Error thrown when required data is missing.
526
+ */
527
+ var MissingRequiredDataError = class extends Error {
528
+ constructor() {
529
+ super("Missing required data");
530
+ }
531
+ };
532
+ /**
533
+ * Error thrown when a required field is missing.
534
+ */
535
+ var MissingRequiredFieldError = class extends Error {
536
+ constructor(fieldName) {
537
+ const defaultMessage = "Missing required field";
538
+ super(fieldName ? `${defaultMessage}: fieldName "${fieldName}"` : defaultMessage);
539
+ }
540
+ };
541
+ /**
542
+ * Error thrown when a required role for an entity is missing.
543
+ */
544
+ var MissingRequiredRoleForEntityError = class extends Error {
545
+ constructor(roleIdentifier, entityIdentifier) {
546
+ const defaultMessage = "Missing required role for entity";
547
+ if (roleIdentifier && entityIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}", entityIdentifier "${entityIdentifier}"`);
548
+ else if (roleIdentifier) super(`${defaultMessage}: roleIdentifier "${roleIdentifier}"`);
549
+ else if (entityIdentifier) super(`${defaultMessage}: entityIdentifier "${entityIdentifier}"`);
550
+ else super(defaultMessage);
551
+ }
552
+ };
553
+ /**
554
+ * Error thrown when a required signature by an entity is missing.
555
+ */
556
+ var MissingRequiredSignatureByEntityError = class extends Error {
557
+ constructor(entityIdentifier) {
558
+ const defaultMessage = "Missing required signature by entity";
559
+ super(entityIdentifier ? `${defaultMessage}: entityIdentifier "${entityIdentifier}"` : defaultMessage);
560
+ }
561
+ };
562
+ /**
563
+ * Error thrown when resource reservation fails.
564
+ */
565
+ var ReserveResourcesFailedError = class extends Error {
566
+ constructor() {
567
+ super("Failed to reserve resources");
568
+ }
569
+ };
570
+ /**
571
+ * Error thrown when signature verification fails.
572
+ */
573
+ var SignatureVerificationFailedError = class extends Error {
574
+ constructor() {
575
+ super("Signature verification failed");
576
+ }
577
+ };
578
+ /**
579
+ * Error thrown when a variable definition is invalid.
580
+ */
581
+ var InvalidVariableDefinitionError = class extends Error {
582
+ constructor(variableIdentifier) {
583
+ super(`Invalid variable definition: must be an object: variableIdentifier "${variableIdentifier}"`);
584
+ }
585
+ };
586
+ /**
587
+ * Error thrown when an output does not have a lockscript.
588
+ */
589
+ var OutputLockscriptNotFoundError = class extends Error {
590
+ constructor(outputIdentifier) {
591
+ super(`Output does not have a lockscript: outputIdentifier "${outputIdentifier}"`);
592
+ }
593
+ };
594
+ /**
595
+ * Error thrown when a locking script has an invalid type.
596
+ */
597
+ var InvalidLockingScriptTypeError = class extends Error {
598
+ constructor(outputIdentifier, expectedType, actualType) {
599
+ super(`Locking script has invalid lockingScript type: outputIdentifier "${outputIdentifier}", expected ${expectedType}, got ${actualType}`);
600
+ }
601
+ };
602
+ /**
603
+ * Error thrown when a locking type is invalid.
604
+ */
605
+ var InvalidLockingTypeError = class extends Error {
606
+ constructor(outputIdentifier, validTypes, actualType) {
607
+ super(`Invalid locking type: outputIdentifier "${outputIdentifier}", expected one of ${validTypes.join(", ")}, got ${actualType}`);
608
+ }
609
+ };
610
+ /**
611
+ * Error thrown when a derivative index has an invalid type.
612
+ */
613
+ var InvalidDerivativeIndexTypeError = class extends Error {
614
+ constructor(expectedType, actualType) {
615
+ super(`Invalid derivativeIndex type: expected ${expectedType}, got ${actualType}`);
616
+ }
617
+ };
618
+ /**
619
+ * Error thrown when a template output valueSatoshis has an invalid type for CashAssembly expression.
620
+ */
621
+ var InvalidTemplateOutputSatoshisTypeError = class extends Error {
622
+ constructor(actualType) {
623
+ super(`Template output valueSatoshis must be a string for CashAssembly expression, got ${actualType}`);
624
+ }
625
+ };
626
+ /**
627
+ * Error thrown when an electrum client is not found.
628
+ */
629
+ var ElectrumClientNotFoundError = class extends Error {
630
+ constructor() {
631
+ super("No electrum client found");
632
+ }
633
+ };
634
+
635
+ //#endregion
636
+ //#region source/utils/libauth-utils.ts
637
+ /**
638
+ * Generates bytecode for a specific CashAssembly evaluation using given variable values and a prepared compiler.
639
+ * Returns libauth result or error string.
640
+ *
641
+ * @param compiler - The libauth compiler.
642
+ * @param evaluation - The specific evaluation string to compile.
643
+ * @param variables - A record mapping variable names to their values.
644
+ * @returns Bytecode result object on success, otherwise an error string.
645
+ */
646
+ const generateCashAssemblyBytecode = (compiler, evaluation, variables) => {
647
+ const variableNames = extractVariablesFromEvaluations([evaluation]);
648
+ const missingVariables = variableNames.filter((name) => !Object.hasOwn(variables, name));
649
+ if (missingVariables.length > 0) throw new MissingRequiredVariableError(missingVariables);
650
+ const bytecode = {};
651
+ for (const variableName of variableNames) {
652
+ const value = variables[variableName];
653
+ if (!(value instanceof Uint8Array)) throw new InvalidVariableTypeError(variableName, "Uint8Array", typeof value);
654
+ bytecode[variableName] = value;
655
+ }
656
+ const compiledBytecode = compiler.generateBytecode({
657
+ data: { bytecode },
658
+ scriptId: evaluation
659
+ });
660
+ if (!compiledBytecode.success) throw new CashAssemblyCompilationFailedError("errors" in compiledBytecode ? JSON.stringify(compiledBytecode.errors) : JSON.stringify(compiledBytecode));
661
+ return compiledBytecode.bytecode;
662
+ };
663
+ /**
664
+ * Prepares a compiler for the provided CashAssembly evaluations, setting required variables as 'WalletData'.
665
+ *
666
+ * @param evaluations - Array of evaluation strings (e.g., ['$(<var1>)', '$(<var2> <var3>)'])
667
+ * @returns A Libauth compiler instance for use with these evaluations.
668
+ */
669
+ const compileCashAssemblyEvaluations = (evaluations) => {
670
+ const scripts = {};
671
+ for (const evaluation of evaluations) scripts[evaluation] = evaluation;
672
+ const variableNames = extractVariablesFromEvaluations(evaluations);
673
+ return createCompilerBch({
674
+ scripts,
675
+ variables: Object.fromEntries(variableNames.map((variableName) => [variableName, { type: "WalletData" }]))
676
+ });
677
+ };
678
+ /**
679
+ * Creates a map of variable identifiers to role identifiers for the libauth compiler configuration.
680
+ *
681
+ * @param template - The template used to gather the variable identifiers.
682
+ * @param role - The role identifier to assign to the variables.
683
+ * @returns {Record<string, string>} A map of variable identifiers to role identifiers.
684
+ */
685
+ const entityOwnershipForLibauthCompiler = (template, role) => {
686
+ const entityOwnershipMap = {};
687
+ const variableIdentifiers = template.variables ? Object.keys(template.variables) : [];
688
+ for (const variableIdentifier of variableIdentifiers) entityOwnershipMap[variableIdentifier] = role;
689
+ return entityOwnershipMap;
690
+ };
691
+ /**
692
+ * Creates a map of script identifiers to script definitions for the libauth compiler configuration.
693
+ *
694
+ * @param template - The template used to gather the scripts.
695
+ * @returns {CompilerConfiguration['scripts']} A map of script identifiers to script definitions.
696
+ */
697
+ const scriptsForLibauthCompiler = (template) => {
698
+ const scriptsMap = {};
699
+ const scriptEntries = template.scripts ? Object.entries(template.scripts) : [];
700
+ for (const [scriptId, scriptDefinition] of scriptEntries) scriptsMap[scriptId] = scriptDefinition;
701
+ return scriptsMap;
702
+ };
703
+ /**
704
+ * Converts template variables into libauth variables with types.
705
+ *
706
+ * @param template - The template to assign types to the variables.
707
+ * @returns CompilerConfiguration['variables']
708
+ */
709
+ const assignTypeToVariablesForLibauthCompiler = (template) => {
710
+ const variablesWithTypes = {};
711
+ const variableEntries = template.variables ? Object.entries(template.variables) : [];
712
+ for (const [variableIdentifier, variableDefinition] of variableEntries) {
713
+ if (!variableDefinition || typeof variableDefinition !== "object") throw new InvalidVariableDefinitionError(variableIdentifier);
714
+ let variableType;
715
+ if ("hint" in variableDefinition) if (variableDefinition.hint === "private_key") variableType = "Key";
716
+ else if (variableDefinition.hint === "script") variableType = "AddressData";
717
+ else variableType = "WalletData";
718
+ else variableType = "WalletData";
719
+ variablesWithTypes[variableIdentifier] = {
720
+ ...variableDefinition,
721
+ type: variableType
722
+ };
723
+ }
724
+ return variablesWithTypes;
725
+ };
726
+ /**
727
+ * Maps supported XO template locking types to the corresponding libauth compiler locking script type.
728
+ */
729
+ const XO_LOCKING_TYPE_TO_LIBAUTH_MAP = {
730
+ p2s: "standard",
731
+ p2pkh: "standard",
732
+ p2sh: "p2sh32"
733
+ };
734
+ /**
735
+ * Converts an XO template locking type to the corresponding libauth compiler locking script type.
736
+ *
737
+ * @param lockingType - The XO template locking type to convert.
738
+ * @returns The corresponding libauth compiler locking script type string.
739
+ */
740
+ const convertXOLockingTypeToLibauth = (lockingType) => {
741
+ return XO_LOCKING_TYPE_TO_LIBAUTH_MAP[lockingType];
742
+ };
743
+ /**
744
+ * Creates the libauth compatiblecompiler data for a unspent output.
745
+ *
746
+ * @param template - The template used to generate the compiler data for.
747
+ * @param unspentOutput - The unspent output to create the compiler data for.
748
+ * @returns The compiler data for the unspent output.
749
+ * @returns {Promise<{
750
+ * compiler: CompilerBch;
751
+ * script: string;
752
+ * valueSatoshis: bigint;
753
+ * }>} The compiler data for the unspent output.
754
+ */
755
+ const createLibauthCompilerDataFromUnspentOutput = async (template, unspentOutput) => {
756
+ const { outputIdentifier } = unspentOutput;
757
+ const output = template.getOutput(outputIdentifier);
758
+ const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);
759
+ if (!lockingScriptForOutput.lockingBytecode) throw new LockingScriptNotFoundError(lockingScriptForOutput.lockingBytecode);
760
+ template.validateLockingScript(lockingScriptForOutput, output.lockingScript);
761
+ const lockingScriptIdentifier = output.lockingScript;
762
+ let roleIdentifier = "owner";
763
+ try {
764
+ template.getRole(lockingScriptIdentifier, roleIdentifier);
765
+ } catch {
766
+ const [firstRoleId] = template.getFirstRole(lockingScriptIdentifier);
767
+ roleIdentifier = firstRoleId;
768
+ }
769
+ const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), roleIdentifier);
770
+ const scripts = scriptsForLibauthCompiler(template.getTemplate());
771
+ const variables = assignTypeToVariablesForLibauthCompiler(template.getTemplate());
772
+ if (!lockingScriptForOutput.unlockingBytecode) throw new UnlockingScriptNotFoundError(outputIdentifier);
773
+ if (typeof lockingScriptForOutput.lockingBytecode !== "string") throw new InvalidLockingScriptTypeError(outputIdentifier, "string", typeof lockingScriptForOutput.lockingBytecode);
774
+ const unlockingScripts = { [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode };
775
+ const validXOLockingTypes = Object.keys(XO_LOCKING_TYPE_TO_LIBAUTH_MAP);
776
+ const { lockingType } = lockingScriptForOutput;
777
+ if (lockingType === void 0) throw new InvalidLockingTypeError(outputIdentifier, validXOLockingTypes, lockingType);
778
+ if (lockingType !== "p2s" && lockingType !== "p2pkh" && lockingType !== "p2sh") throw new InvalidLockingTypeError(outputIdentifier, validXOLockingTypes, lockingType);
779
+ return {
780
+ compiler: createCompilerBch({
781
+ entityOwnership,
782
+ scripts,
783
+ variables,
784
+ unlockingScripts,
785
+ lockingScriptTypes: { lock: convertXOLockingTypeToLibauth(lockingType) }
786
+ }),
787
+ script: lockingScriptForOutput.unlockingBytecode,
788
+ valueSatoshis: BigInt(unspentOutput.valueSatoshis)
789
+ };
790
+ };
791
+
792
+ //#endregion
793
+ //#region source/utils/cashasm-utils.ts
794
+ /**
795
+ * Checks if the expression is a CashAssembly expression.
796
+ *
797
+ * @param expression - The expression to check.
798
+ * @returns True if the expression is a CashAssembly expression, false otherwise.
799
+ */
800
+ const isCashAsmExpression = (expression) => {
801
+ return typeof expression === "string" && /^\$\([^)]*\)$/.test(expression);
802
+ };
803
+ /**
804
+ * Extracts all CashAssembly evaluations (i.e., substrings like $(...)) from the input text.
805
+ *
806
+ * @param text - The input string to scan for CashAssembly evaluations.
807
+ * @returns An array of evaluation strings found in the input.
808
+ *
809
+ * @example
810
+ * extractCashAssemblyEvaluations("OP_DUP <$(<foo>)> OP_HASH160 $(<bar>)");
811
+ * // returns ['$(<foo>)', '$(<bar>)']
812
+ */
813
+ const extractCashAssemblyEvaluations = (text) => {
814
+ return text.match(/\$\([^)]+\)/g) ?? [];
815
+ };
816
+ /**
817
+ * Extracts variable names enclosed in angle brackets (e.g., <variableName>) from each evaluation string.
818
+ *
819
+ * @param evaluations - An array of evaluation strings from which to extract variable names.
820
+ * @returns An array of variable names (no angle brackets), as strings.
821
+ */
822
+ const extractVariablesFromEvaluations = (evaluations) => {
823
+ const variableRegex = /<([^>]+)>/g;
824
+ const variables = [];
825
+ for (const evaluation of evaluations) {
826
+ let match;
827
+ match = variableRegex.exec(evaluation);
828
+ while (match !== null) {
829
+ variables.push(match[1]);
830
+ match = variableRegex.exec(evaluation);
831
+ }
832
+ }
833
+ return variables;
834
+ };
835
+ /**
836
+ * Compiles all CashAssembly evaluations in a text string, using the provided variables.
837
+ * Each evaluation is replaced with its compiled bytecode (hex string).
838
+ *
839
+ * Handles complex expressions like $(<variable1> <variable2>) and simple ones like $(<variable>).
840
+ * Returns error string if required variables are missing or compilation fails.
841
+ *
842
+ * Supports variables of type: string (hex), bigint, number, boolean, and Uint8Array.
843
+ *
844
+ * @param text - The full string with possible CashAssembly evaluations.
845
+ * @param variables - Object mapping variable names to values for compilation.
846
+ * For invitation variables, use XOInvitationVariableValue types (bigint | boolean | number | string).
847
+ * For other use cases, Uint8Array is also supported.
848
+ * @returns Compiled text with all evaluations replaced with hex bytecode, or error string.
849
+ */
850
+ const compileCashAssemblyString = (text, variables) => {
851
+ let compiledText = text;
852
+ const evaluations = extractCashAssemblyEvaluations(text);
853
+ for (const evaluation of evaluations) {
854
+ const variableNames = extractVariablesFromEvaluations([evaluation]);
855
+ if (variableNames.filter((variableName) => !Object.prototype.hasOwnProperty.call(variables, variableName)).length > 0) throw new VariableValidationFailedError(variableNames);
856
+ const convertedVariables = {};
857
+ for (const variableName of variableNames) convertedVariables[variableName] = hexToBin(String(variables[variableName]));
858
+ const bytecodeHex = binToHex(generateCashAssemblyBytecode(compileCashAssemblyEvaluations([evaluation]), evaluation, convertedVariables));
859
+ compiledText = compiledText.replace(evaluation, bytecodeHex);
860
+ }
861
+ return compiledText;
862
+ };
863
+
864
+ //#endregion
865
+ //#region source/utils/store-utils.ts
866
+ /**
867
+ * Synchronizes the store of unspent outputs for a given script hash with the current state of the blockchain.
868
+ *
869
+ * This method performs the following:
870
+ * 1. Retrieves the stored script hash data from the state.
871
+ * 2. Fetches the current list of unspent outputs for the script hash from the state.
872
+ * 3. Queries the blockchain for all unspent transaction outputs associated with the script hash.
873
+ * 4. Adds any new unspent outputs found on the blockchain but missing from the state to the state.
874
+ * 5. Removes any unspent outputs present in the state but no longer in the blockchain.
875
+ *
876
+ * @param state - The State instance to use for data operations.
877
+ * @param scriptHash - The script hash for which to update the stored unspent outputs.
878
+ * @param fetchUnspentOutputsCallback - Callback function to fetch unspent outputs from the blockchain.
879
+ * @throws If the script hash is not found in the state.
880
+ */
881
+ const updateUnspentOutputsForScriptHashInStore = async (state, scriptHash, fetchUnspentOutputsCallback) => {
882
+ const scriptHashData = await state.getScriptHashData(scriptHash);
883
+ if (scriptHashData === void 0) throw new ScriptHashDataNotFoundError(scriptHash);
884
+ const unspentOutputsFromCache = await state.listUnspentOutputsData({ scriptHash });
885
+ const unspentOutputsFromBlockchain = await fetchUnspentOutputsCallback(scriptHash);
886
+ const cachedOutpointKeys = /* @__PURE__ */ new Set();
887
+ for (const cachedOutput of unspentOutputsFromCache) {
888
+ const key = `${cachedOutput.outpointTransactionHash}:${cachedOutput.outpointIndex}`;
889
+ cachedOutpointKeys.add(key);
890
+ }
891
+ const blockchainOutpointKeys = /* @__PURE__ */ new Set();
892
+ for (const unspentOutput of unspentOutputsFromBlockchain) {
893
+ const key = `${unspentOutput.tx_hash}:${unspentOutput.tx_pos}`;
894
+ blockchainOutpointKeys.add(key);
895
+ }
896
+ for (const unspentOutput of unspentOutputsFromBlockchain) {
897
+ const outpointKey = `${unspentOutput.tx_hash}:${unspentOutput.tx_pos}`;
898
+ if (!cachedOutpointKeys.has(outpointKey)) {
899
+ const unspentOutputData = {
900
+ status: unspentOutput.height === 0 ? UnspentOutputStatus.PENDING : UnspentOutputStatus.CONFIRMED,
901
+ reservedBy: void 0,
902
+ scriptHash,
903
+ selectable: true,
904
+ privacy: false,
905
+ templateIdentifier: scriptHashData.templateIdentifier,
906
+ outputIdentifier: scriptHashData.outputIdentifier,
907
+ outpointIndex: unspentOutput.tx_pos,
908
+ outpointTransactionHash: unspentOutput.tx_hash,
909
+ minedAtHeight: unspentOutput.height,
910
+ valueSatoshis: unspentOutput.value
911
+ };
912
+ await state.storeUnspentOutputData(unspentOutputData);
913
+ }
914
+ }
915
+ for (const cachedOutput of unspentOutputsFromCache) {
916
+ const cachedKey = `${cachedOutput.outpointTransactionHash}:${cachedOutput.outpointIndex}`;
917
+ if (!blockchainOutpointKeys.has(cachedKey)) await state.deleteUnspentOutputData(cachedOutput.outpointTransactionHash, cachedOutput.outpointIndex);
918
+ }
919
+ };
920
+
921
+ //#endregion
922
+ //#region source/monitor/blockchain.ts
923
+ /**
924
+ * BlockchainMonitor class that provides blockchain monitoring operations.
925
+ */
926
+ var BlockchainMonitor = class {
927
+ /**
928
+ * The state instance for data persistence.
929
+ */
930
+ state;
931
+ /**
932
+ * Flag indicating whether event listeners have been initialized.
933
+ */
934
+ eventListenersInitialized = false;
935
+ /**
936
+ * Creates a new instance of BlockchainMonitor.
937
+ *
938
+ * @param {State} state - The State instance for data persistence.
939
+ */
940
+ constructor(state) {
941
+ this.state = state;
942
+ }
943
+ /**
944
+ * Initializes event listeners for electrum application events.
945
+ * Registers listeners for all available events from the electrum application,
946
+ * including system, chain status, block, transaction, output, and address events.
947
+ * This should be called after the electrum application is initialized.
948
+ * Note: Event data is not stored, listeners are registered but remain empty.
949
+ *
950
+ * @returns {void}
951
+ */
952
+ initializeEventListeners() {
953
+ if (this.eventListenersInitialized) return;
954
+ electrumEvents.on("SystemFailure", (_error) => {
955
+ this.stop().catch(() => {});
956
+ });
957
+ electrumEvents.on("ChainStatus", (_status) => {});
958
+ electrumEvents.on("BlockReceived", (_data) => {});
959
+ electrumEvents.on("BlockVerified", (_data) => {});
960
+ electrumEvents.on("TransactionReceived", (_data) => {});
961
+ electrumEvents.on("TransactionVerified", (_data) => {});
962
+ electrumEvents.on("TransactionOrphaned", (_data) => {});
963
+ electrumEvents.on("TransactionFinalized", (_data) => {});
964
+ electrumEvents.on("TransactionContested", (_data) => {});
965
+ electrumEvents.on("TransactionRejected", (_data) => {});
966
+ electrumEvents.on("OutputReceived", (_data) => {});
967
+ electrumEvents.on("OutputContested", (_data) => {});
968
+ electrumEvents.on("OutputRejected", (_data) => {});
969
+ electrumEvents.on("OutputVerified", (_data) => {});
970
+ electrumEvents.on("OutputOrphaned", (_data) => {});
971
+ electrumEvents.on("OutputFinalized", (_data) => {});
972
+ electrumEvents.on("OutputSpent", (_data) => {});
973
+ electrumEvents.on("AddressUpdate", (_data) => {});
974
+ this.eventListenersInitialized = true;
975
+ }
976
+ /**
977
+ * Stops the blockchain monitor and releases resources.
978
+ * @returns {Promise<void>} Resolves when the blockchain monitor is stopped.
979
+ */
980
+ async stop() {
981
+ await stopElectrumNetwork();
982
+ this.eventListenersInitialized = false;
983
+ }
984
+ /**
985
+ * Handles the creation of a new unspent output by storing it in the state.
986
+ *
987
+ * @param {UnspentOutputData} data - The unspent output data to store.
988
+ * @returns {Promise<void>} Resolves when the unspent output data is stored.
989
+ */
990
+ async handleUnspentOutputCreated(data) {
991
+ await this.state.storeUnspentOutputData(data);
992
+ }
993
+ /**
994
+ * Handles script hash update notifications from the electrum protocol.
995
+ * When a script hash update is received, this method finds all associated
996
+ * locking bytecodes and updates their unspent outputs in the store.
997
+ *
998
+ * @param {ScriptHashSubscribeNotification} data - The script hash subscription notification data.
999
+ * @returns {Promise<void>} Resolves when all unspent outputs are updated.
1000
+ */
1001
+ async onScriptHashUpdate(data) {
1002
+ const [scriptHash] = data.params;
1003
+ const scriptHashDataList = await this.state.listScriptHashData({ scriptHash });
1004
+ const [firstElectrumClient] = electrumClients.values();
1005
+ for (const scriptHashData of scriptHashDataList) await updateUnspentOutputsForScriptHashInStore(this.state, scriptHashData.scriptHash, async () => {
1006
+ return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scriptHashData.scriptHash);
1007
+ });
1008
+ }
1009
+ };
1010
+
1011
+ //#endregion
1012
+ //#region source/defaults.ts
1013
+ const DEFAULT_INVITATION_EXPIRATION_IN_MILLISECONDS = 3600 * 1e3;
1014
+ const DEFAULT_STORAGE_TYPE = StorageType.INDEXEDDB;
1015
+ const DEFAULT_SEQUENCE_NUMBER = 0;
1016
+ const DEFAULT_LOCKTIME = 0;
1017
+ const DEFAULT_VERSION = 2;
1018
+ const PLACEHOLDER_UNLOCKING_BYTECODE = new Uint8Array(0);
1019
+ /**
1020
+ * The default electrum application identifier.
1021
+ */
1022
+ const DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER = "xo";
1023
+
1024
+ //#endregion
1025
+ //#region source/invitation/builder.ts
1026
+ /**
1027
+ * Builder for the XOInvitation
1028
+ */
1029
+ var InvitationBuilder = class InvitationBuilder {
1030
+ /**
1031
+ * The identifier of the current invitation.
1032
+ *
1033
+ * TODO: Add validations and type checks to the identifier e.g length.
1034
+ */
1035
+ invitationIdentifier;
1036
+ /**
1037
+ * The identifier of the template for the invitation.
1038
+ *
1039
+ * TODO: Add validations and type checks to the identifier e.g it should be a 32 byte hex string, etc.
1040
+ */
1041
+ templateIdentifier;
1042
+ /**
1043
+ * The identifier of the action for the invitation.
1044
+ */
1045
+ actionIdentifier;
1046
+ /**
1047
+ * The timestamp when the invitation is created.
1048
+ *
1049
+ */
1050
+ createdAtTimestamp;
1051
+ /**
1052
+ * The commits in the invitation.
1053
+ */
1054
+ commits;
1055
+ /**
1056
+ * Create a new InvitationBuilder.
1057
+ * @param invitation Context for invitation creation.
1058
+ */
1059
+ constructor(invitation) {
1060
+ const { templateIdentifier, actionIdentifier } = invitation;
1061
+ this.templateIdentifier = templateIdentifier;
1062
+ this.actionIdentifier = actionIdentifier;
1063
+ this.commits = [];
1064
+ this.invitationIdentifier = binToHex(generateRandomBytes(16));
1065
+ this.createdAtTimestamp = Date.now();
1066
+ }
1067
+ /**
1068
+ * Create a builder from an existing invitation.
1069
+ * @param invitation An existing XOInvitation.
1070
+ */
1071
+ static fromInvitation(invitation) {
1072
+ const builder = new InvitationBuilder({
1073
+ templateIdentifier: invitation.templateIdentifier,
1074
+ actionIdentifier: invitation.actionIdentifier
1075
+ });
1076
+ builder.invitationIdentifier = invitation.invitationIdentifier;
1077
+ builder.createdAtTimestamp = invitation.createdAtTimestamp;
1078
+ builder.commits = [...invitation.commits];
1079
+ return builder;
1080
+ }
1081
+ /**
1082
+ * Build the XOInvitation object to be shared.
1083
+ * @returns The built XOInvitation.
1084
+ */
1085
+ build() {
1086
+ return {
1087
+ invitationIdentifier: this.invitationIdentifier,
1088
+ templateIdentifier: this.templateIdentifier,
1089
+ actionIdentifier: this.actionIdentifier,
1090
+ createdAtTimestamp: this.createdAtTimestamp,
1091
+ commits: this.commits
1092
+ };
1093
+ }
1094
+ /**
1095
+ * Fully validates a given XOInvitation.
1096
+ *
1097
+ * @param template - The template to validate against.
1098
+ * @throws {InvitationExpiredError} If the invitation has expired.
1099
+ * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
1100
+ * @throws {InvalidRequirementsError} If the requirements are invalid.
1101
+ * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
1102
+ */
1103
+ validate(template) {
1104
+ if (generateTemplateIdentifier(template) !== this.templateIdentifier) throw new TemplateIdentifierMismatchError();
1105
+ const action = new Template(template).getActionOrThrow(this.actionIdentifier);
1106
+ const invitation = this.build();
1107
+ if (hasInvitationExpired(invitation)) throw new InvitationExpiredError();
1108
+ if (!validateInvitationEntities(invitation)) throw new InvalidEntityIdentifierError();
1109
+ if (!validateRoleRequirements(invitation, template, action)) throw new InvalidRequirementsError();
1110
+ if (!validateInvitationCommits(invitation)) throw new InvalidCommitSignaturesError();
1111
+ return this;
1112
+ }
1113
+ /**
1114
+ * Add a commit to the invitation.
1115
+ * @param commit The commit to add.
1116
+ * @returns The builder instance.
1117
+ */
1118
+ addCommit(commit) {
1119
+ if (!commit.signature) throw new CommitNotSignedError(commit.commitIdentifier);
1120
+ if (!commit.entityIdentifier) throw new CommitEntityIdentifierNotFoundError(commit.commitIdentifier);
1121
+ this.commits.push(commit);
1122
+ return this;
1123
+ }
1124
+ /**
1125
+ * Returns the commitIdentifier of the last commit in the invitation.
1126
+ * @returns The commitIdentifier as a string, or undefined if there are no commits.
1127
+ */
1128
+ getLastCommitIdentifier() {
1129
+ return this.commits[this.commits.length - 1]?.commitIdentifier;
1130
+ }
1131
+ /**
1132
+ * Returns the last InvitationCommit in the invitation.
1133
+ * @returns The last InvitationCommit object, or undefined if there are no commits.
1134
+ */
1135
+ getLastCommit() {
1136
+ return this.commits[this.commits.length - 1];
1137
+ }
1138
+ /**
1139
+ * Creates an unsigned commit without adding it to the invitation.
1140
+ * This allows for atomic commit creation with signature.
1141
+ *
1142
+ * @param params - Parameters for creating the commit
1143
+ * @param params.inputs - Optional array of inputs to add
1144
+ * @param params.outputs - Optional array of outputs to add
1145
+ * @param params.variables - Optional array of variables to add
1146
+ * @param params.transactionVersion - Optional transaction version
1147
+ * @param params.transactionLocktime - Optional transaction locktime
1148
+ * @param params.expiresAtTimestamp - Optional expiration timestamp (defaults to now + DEFAULT_INVITATION_EXPIRATION_IN_MILLISECONDS)
1149
+ * @returns The unsigned commit (without signature)
1150
+ */
1151
+ createUnsignedCommit(params) {
1152
+ const { inputs, outputs, variables, transactionVersion, transactionLocktime, expiresAtTimestamp } = params;
1153
+ if (inputs) this.validateMergesWithReferences(inputs);
1154
+ if (outputs) this.validateMergesWithReferences(outputs);
1155
+ return this.createCommit({
1156
+ previousCommitIdentifier: this.getLastCommitIdentifier(),
1157
+ inputs,
1158
+ outputs,
1159
+ variables,
1160
+ transactionVersion,
1161
+ transactionLocktime,
1162
+ expiresAtTimestamp: expiresAtTimestamp ?? Date.now() + DEFAULT_INVITATION_EXPIRATION_IN_MILLISECONDS
1163
+ });
1164
+ }
1165
+ /**
1166
+ * Creates a new commit from the provided data.
1167
+ * This is a private helper method that initializes the commit building logic.
1168
+ */
1169
+ createCommit(params) {
1170
+ const data = {
1171
+ variables: params.variables && params.variables.length > 0 ? params.variables : void 0,
1172
+ inputs: params.inputs && params.inputs.length > 0 ? params.inputs : void 0,
1173
+ outputs: params.outputs && params.outputs.length > 0 ? params.outputs : void 0
1174
+ };
1175
+ if (params.transactionVersion !== void 0) data.transactionVersion = params.transactionVersion;
1176
+ if (params.transactionLocktime !== void 0) data.transactionLocktime = params.transactionLocktime;
1177
+ return {
1178
+ commitIdentifier: binToHex(hash256(hexToBin(stringify(data) + params.previousCommitIdentifier + params.expiresAtTimestamp))),
1179
+ previousCommitIdentifier: params.previousCommitIdentifier,
1180
+ data,
1181
+ expiresAtTimestamp: params.expiresAtTimestamp
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Validates mergesWith references for inputs and outputs.
1186
+ * @private
1187
+ */
1188
+ validateMergesWithReferences(items) {
1189
+ for (const item of items) if (item.mergesWith) {
1190
+ if (!this.commits.find((commit) => commit.commitIdentifier === item.mergesWith?.commitIdentifier)) throw new ParentCommitNotFoundError(item.mergesWith.commitIdentifier, this.invitationIdentifier);
1191
+ }
1192
+ }
1193
+ };
1194
+
1195
+ //#endregion
1196
+ //#region source/invitation/commit.ts
1197
+ /**
1198
+ * Generates a random 16-byte commit identifier.
1199
+ *
1200
+ * @returns {string} The generated commit identifier as a hex string.
1201
+ */
1202
+ const generateCommitIdentifier = () => {
1203
+ return binToHex(generateRandomBytes(16));
1204
+ };
1205
+ /**
1206
+ * Finds the root commit identifier for a given entity in an invitation. The root commit is
1207
+ * the first commit the entity added to the invitation.
1208
+ *
1209
+ * @param {XOInvitation} invitation The invitation whose commits are searched.
1210
+ * @param {string} entityIdentifier The entity identifier to search for among the invitation commits.
1211
+ * @returns {string | undefined} The root commit identifier if the entity has a commit in the invitation, otherwise undefined.
1212
+ */
1213
+ const findRootCommitIdentifierInInvitation = (invitation, entityIdentifier) => {
1214
+ for (const commit of invitation.commits) if (commit.entityIdentifier === entityIdentifier) return commit.commitIdentifier;
1215
+ };
1216
+
1217
+ //#endregion
1218
+ //#region source/utils/template.ts
1219
+ /**
1220
+ * Template class for accessing template data.
1221
+ */
1222
+ var Template = class {
1223
+ /**
1224
+ * The template object.
1225
+ */
1226
+ template;
1227
+ /**
1228
+ * Creates a Template class from a template object.
1229
+ */
1230
+ constructor(template) {
1231
+ if (!template) throw new TemplateNotFoundError();
1232
+ this.template = template;
1233
+ }
1234
+ /**
1235
+ * Gets the underlying template object.
1236
+ */
1237
+ getTemplate() {
1238
+ return this.template;
1239
+ }
1240
+ /**
1241
+ * Gets the starting actions for the template.
1242
+ * @returns {Array<XOTemplateActionIntent>} The list of starting actions.
1243
+ */
1244
+ getStartingActions() {
1245
+ return this.template.start ?? [];
1246
+ }
1247
+ /**
1248
+ * Retrieves an output definition by identifier.
1249
+ * Step 1 in the flow: template → output
1250
+ * @throws {OutputNotFoundError} If the output is not found.
1251
+ */
1252
+ getOutput(outputIdentifier) {
1253
+ const output = this.template.outputs[outputIdentifier];
1254
+ if (!output) throw new OutputNotFoundError(outputIdentifier);
1255
+ return output;
1256
+ }
1257
+ /**
1258
+ * Retrieves the locking script identifier from an output.
1259
+ * Step 2 in the flow: output → locking script identifier
1260
+ * @throws {OutputNotFoundError} If the output is not found.
1261
+ * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.
1262
+ */
1263
+ getLockingScriptIdentifier(outputIdentifier) {
1264
+ const output = this.getOutput(outputIdentifier);
1265
+ if (!output.lockingScript) throw new LockingScriptNotFoundError(outputIdentifier);
1266
+ return output.lockingScript;
1267
+ }
1268
+ /**
1269
+ * Retrieves a locking script definition by identifier.
1270
+ * Step 3 in the flow: locking script identifier → locking script
1271
+ * @throws {LockingScriptNotFoundError} If the locking script is not found.
1272
+ */
1273
+ getLockingScript(lockingScriptIdentifier) {
1274
+ const lockingScript = this.template.lockingScripts[lockingScriptIdentifier];
1275
+ if (!lockingScript) throw new LockingScriptNotFoundError(lockingScriptIdentifier);
1276
+ return lockingScript;
1277
+ }
1278
+ /**
1279
+ * Retrieves the locking script for a given output.
1280
+ * Combines steps 1-3: output → locking script identifier → locking script
1281
+ * @throws {OutputNotFoundError} If the output is not found.
1282
+ * @throws {LockingScriptNotFoundError} If the output doesn't have a locking script identifier.
1283
+ * @throws {LockingScriptNotFoundError} If the locking script is not found.
1284
+ */
1285
+ getLockingScriptForOutput(outputIdentifier) {
1286
+ const lockingScriptIdentifier = this.getLockingScriptIdentifier(outputIdentifier);
1287
+ return this.getLockingScript(lockingScriptIdentifier);
1288
+ }
1289
+ /**
1290
+ * Validates that a locking script has required unlocking script and locking type.
1291
+ * Step 4 in the flow: validate locking script
1292
+ * @param lockingScript - The locking script to validate.
1293
+ * @param lockingScriptIdentifier - The identifier of the locking script (for error messages).
1294
+ * @throws {LockingScriptTypeNotFoundError} If lockingType is missing.
1295
+ */
1296
+ validateLockingScript(lockingScript, lockingScriptIdentifier) {
1297
+ if (!lockingScript.lockingType) throw new LockingScriptTypeNotFoundError(lockingScriptIdentifier);
1298
+ }
1299
+ /**
1300
+ * Retrieves a role within a locking script.
1301
+ * Step 5 in the flow: locking script → role
1302
+ * @param lockingScriptIdentifier - The locking script identifier.
1303
+ * @param roleIdentifier - The role identifier.
1304
+ * @throws {LockingScriptNotFoundError} If the locking script is not found.
1305
+ * @throws {RoleNotFoundError} If the role is not found.
1306
+ */
1307
+ getRole(lockingScriptIdentifier, roleIdentifier) {
1308
+ const role = this.getLockingScript(lockingScriptIdentifier).roles?.[roleIdentifier];
1309
+ if (!role) throw new RoleNotFoundError(roleIdentifier);
1310
+ return role;
1311
+ }
1312
+ /**
1313
+ * Retrieves the first available role in a locking script, or throws if none exist.
1314
+ * @param lockingScriptIdentifier - The locking script identifier.
1315
+ * @returns A tuple of [roleIdentifier, role].
1316
+ * @throws {LockingScriptNotFoundError} If the locking script is not found.
1317
+ * @throws {RoleNotFoundError} If no roles exist.
1318
+ */
1319
+ getFirstRole(lockingScriptIdentifier) {
1320
+ const roles = this.getLockingScript(lockingScriptIdentifier).roles ?? {};
1321
+ const roleKeys = Object.keys(roles);
1322
+ if (roleKeys.length === 0) throw new RoleNotFoundError();
1323
+ return [roleKeys[0], roles[roleKeys[0]]];
1324
+ }
1325
+ /**
1326
+ * Retrieves secrets for a locking script.
1327
+ * If roleIdentifier is provided, returns secrets from the role's state.
1328
+ * Otherwise, returns secrets from the locking script itself.
1329
+ * Step 6 in the flow: role → secrets (or locking script → secrets)
1330
+ * @param lockingScriptIdentifier - The locking script identifier.
1331
+ * @param roleIdentifier - The role identifier (optional, if not provided uses locking script secrets).
1332
+ * @returns Array of secret identifiers.
1333
+ * @throws {LockingScriptNotFoundError} If the locking script is not found.
1334
+ * @throws {RoleNotFoundError} If roleIdentifier is provided but the role is not found.
1335
+ */
1336
+ getSecrets(lockingScriptIdentifier, roleIdentifier) {
1337
+ if (roleIdentifier) return this.getRole(lockingScriptIdentifier, roleIdentifier).state?.secrets ?? [];
1338
+ return this.getLockingScript(lockingScriptIdentifier).state?.secrets ?? [];
1339
+ }
1340
+ /**
1341
+ * Retrieves an action definition by identifier.
1342
+ * @param actionIdentifier - The identifier of the action.
1343
+ * @throws {ActionNotFoundError} If the action is not found.
1344
+ */
1345
+ getActionOrThrow(actionIdentifier) {
1346
+ const action = this.template.actions[actionIdentifier];
1347
+ if (!action) throw new ActionNotFoundError(actionIdentifier);
1348
+ return action;
1349
+ }
1350
+ /**
1351
+ * Retrieves a transaction definition by identifier.
1352
+ * @param transactionIdentifier - The identifier of the transaction.
1353
+ * @throws {TransactionNotFoundError} If the transaction is not found.
1354
+ */
1355
+ getTransaction(transactionIdentifier) {
1356
+ const transaction = this.template.transactions?.[transactionIdentifier];
1357
+ if (!transaction) throw new TransactionNotFoundError(transactionIdentifier);
1358
+ return transaction;
1359
+ }
1360
+ /**
1361
+ * Retrieves the transaction for a given action.
1362
+ * Flow: action → transaction identifier → transaction
1363
+ * @param actionIdentifier - The identifier of the action.
1364
+ * @throws {ActionNotFoundError} If the action is not found.
1365
+ * @throws {TransactionNotFoundError} If the action doesn't have a transaction or it's not found.
1366
+ */
1367
+ getTransactionForAction(actionIdentifier) {
1368
+ const action = this.getActionOrThrow(actionIdentifier);
1369
+ if (!action.transaction) throw new TransactionNotFoundError(action.transaction);
1370
+ return this.getTransaction(action.transaction);
1371
+ }
1372
+ };
1373
+
1374
+ //#endregion
1375
+ //#region source/invitation/merger.ts
1376
+ /**
1377
+ * Note:
1378
+ * This file implements the merging of invitation commits using a chain model.
1379
+ *
1380
+ * Each commit has exactly one parent commit (or none for tip commits).
1381
+ *
1382
+ * The invitation always ensures that when a new commit is added and shared with the other parties
1383
+ * they can't change the information provided in the previous commits.
1384
+ *
1385
+ * Once the invitation is to be merged this is how it merges:
1386
+ *
1387
+ * - Gathers up all the variables, states, version, locktime, inputs and outputs from all the commits.
1388
+ * - It could be that there are duplicates of each identifier, to handle this the min/max from the template is
1389
+ * used to determine whether that should be allowed or not. (TODO: min/max logic not implemented yet)
1390
+ * - The mergesWith is used to merge the information with a previous commit. Any overwrite of that commit is strictly not allowed.
1391
+ * - The merger uses a visitor pattern to traverse the commits, each data point in the invitation is marked as visited and merged.
1392
+ * - After this process is done all the non marked data points are merged with the existing data.
1393
+ * - Finally for inputs and outputs are sorted based on the transactionIndex and full merged data is returned.
1394
+ */
1395
+ /**
1396
+ * Converts an array of XOInvitationVariable objects into an object,
1397
+ * where each key is the variable's identifier and the value is the variable's value.
1398
+ *
1399
+ * @param variables - Array of XOInvitationVariable objects to convert.
1400
+ * @returns An object mapping each variable identifier to its corresponding value.
1401
+ */
1402
+ const convertCommitVariablesIntoObject = (variables) => {
1403
+ const variablesObject = {};
1404
+ for (const variable of variables) variablesObject[variable.variableIdentifier] = variable.value;
1405
+ return variablesObject;
1406
+ };
1407
+ /**
1408
+ * Validates that all commit references exist.
1409
+ */
1410
+ const validateCommitReferences = (commits, commitsMap) => {
1411
+ for (const commit of commits) if (commit.previousCommitIdentifier && !commitsMap.has(commit.previousCommitIdentifier)) throw new ParentCommitNotFoundError(commit.previousCommitIdentifier, commit.commitIdentifier);
1412
+ };
1413
+ /**
1414
+ * Merges simple data types (variables, transactionVersion, transactionLocktime).
1415
+ */
1416
+ const mergeSimpleData = (commits) => {
1417
+ const variables = [];
1418
+ const versionCommitIdentifiers = [];
1419
+ const locktimeCommitIdentifiers = [];
1420
+ let transactionVersion;
1421
+ let transactionLocktime;
1422
+ for (const commit of commits) {
1423
+ if (commit.data.variables) variables.push(...commit.data.variables);
1424
+ if (commit.data.transactionVersion !== void 0) {
1425
+ versionCommitIdentifiers.push(commit.commitIdentifier);
1426
+ if (transactionVersion === void 0) transactionVersion = commit.data.transactionVersion;
1427
+ }
1428
+ if (commit.data.transactionLocktime !== void 0) {
1429
+ locktimeCommitIdentifiers.push(commit.commitIdentifier);
1430
+ if (transactionLocktime === void 0) transactionLocktime = commit.data.transactionLocktime;
1431
+ }
1432
+ }
1433
+ if (versionCommitIdentifiers.length > 1) throw new DuplicateTransactionVersionError(versionCommitIdentifiers);
1434
+ if (locktimeCommitIdentifiers.length > 1) throw new DuplicateTransactionLocktimeError(locktimeCommitIdentifiers);
1435
+ return {
1436
+ variables,
1437
+ transactionVersion,
1438
+ transactionLocktime
1439
+ };
1440
+ };
1441
+ /**
1442
+ * Validates that there are no duplicate transactionIndex values.
1443
+ */
1444
+ const validateTransactionIndices = (items, itemType) => {
1445
+ const indices = items.map((item) => item.transactionIndex).filter((idx) => idx !== void 0);
1446
+ const duplicates = indices.filter((idx, i) => indices.indexOf(idx) !== i);
1447
+ if (duplicates.length > 0) throw new DuplicateTransactionIndexError(itemType, duplicates);
1448
+ };
1449
+ /**
1450
+ * Generic function to merge items (inputs or outputs) with mergesWith references.
1451
+ */
1452
+ const mergeItemsWithMergesWith = (context) => {
1453
+ const { items, commitsMap, getItemsFromCommit, resolveItem, itemType } = context;
1454
+ const visitedCommits = /* @__PURE__ */ new Set();
1455
+ /**
1456
+ * Resolves mergesWith references for an item recursively with cycle detection.
1457
+ */
1458
+ const resolveItemMerges = (item, currentCommitIdentifier, visitedPath = /* @__PURE__ */ new Set()) => {
1459
+ const mergedItem = { ...item };
1460
+ if (item.mergesWith) {
1461
+ const mergeKey = `${item.mergesWith.commitIdentifier}:${item.mergesWith.index}`;
1462
+ if (visitedPath.has(mergeKey)) throw new CircularMergeReferenceError(itemType, mergeKey, currentCommitIdentifier);
1463
+ visitedPath.add(mergeKey);
1464
+ const mergesWithCommit = commitsMap.get(item.mergesWith.commitIdentifier);
1465
+ if (!mergesWithCommit) throw new MergesWithCommitNotFoundError(item.mergesWith.commitIdentifier, currentCommitIdentifier);
1466
+ const parentItems = getItemsFromCommit(mergesWithCommit);
1467
+ if (parentItems) {
1468
+ const parentItem = parentItems[item.mergesWith.index];
1469
+ if (!parentItem) throw new ItemNotFoundInCommitError(itemType, item.mergesWith.index, item.mergesWith.commitIdentifier);
1470
+ visitedCommits.add(item.mergesWith.commitIdentifier);
1471
+ const resolvedParent = resolveItemMerges(parentItem, item.mergesWith.commitIdentifier, visitedPath);
1472
+ Object.assign(mergedItem, resolvedParent);
1473
+ }
1474
+ }
1475
+ if (mergedItem.mergesWith) delete mergedItem.mergesWith;
1476
+ return mergedItem;
1477
+ };
1478
+ const resolvedItems = [];
1479
+ for (const { item, sourceCommitIdentifier } of items) if (item.mergesWith) {
1480
+ const resolvedItem = resolveItem(resolveItemMerges(item, sourceCommitIdentifier));
1481
+ resolvedItems.push(resolvedItem);
1482
+ }
1483
+ for (const { item, sourceCommitIdentifier } of items) if (!item.mergesWith && !visitedCommits.has(sourceCommitIdentifier)) {
1484
+ const resolvedItem = resolveItem(resolveItemMerges(item, sourceCommitIdentifier));
1485
+ resolvedItems.push(resolvedItem);
1486
+ }
1487
+ validateTransactionIndices(resolvedItems, itemType);
1488
+ resolvedItems.sort((a, b) => {
1489
+ return (a.transactionIndex ?? Number.MAX_SAFE_INTEGER) - (b.transactionIndex ?? Number.MAX_SAFE_INTEGER);
1490
+ });
1491
+ return resolvedItems;
1492
+ };
1493
+ /**
1494
+ * Applies input-specific properties and defaults.
1495
+ */
1496
+ const applyInputProperties = (input) => {
1497
+ const processedInput = { ...input };
1498
+ if (input.outpointIndex !== void 0) processedInput.outpointIndex = input.outpointIndex;
1499
+ if (input.outpointTransactionHash !== void 0) processedInput.outpointTransactionHash = typeof input.outpointTransactionHash === "string" ? hexToBin(input.outpointTransactionHash) : input.outpointTransactionHash;
1500
+ if (input.sequenceNumber !== void 0) processedInput.sequenceNumber = input.sequenceNumber;
1501
+ if (input.unlockingBytecode !== void 0 && input.unlockingBytecode !== PLACEHOLDER_UNLOCKING_BYTECODE) processedInput.unlockingBytecode = typeof input.unlockingBytecode === "string" ? hexToBin(input.unlockingBytecode) : input.unlockingBytecode;
1502
+ if (processedInput.sequenceNumber === void 0) processedInput.sequenceNumber = DEFAULT_SEQUENCE_NUMBER;
1503
+ if (processedInput.unlockingBytecode === void 0) processedInput.unlockingBytecode = PLACEHOLDER_UNLOCKING_BYTECODE;
1504
+ return processedInput;
1505
+ };
1506
+ /**
1507
+ * Merges inputs from all commits, resolving mergesWith references.
1508
+ * Also sorts all the inputs by transactionIndex.
1509
+ */
1510
+ const mergeInputs = (commits, commitsMap) => {
1511
+ const allInputs = [];
1512
+ for (const commit of commits) if (commit.data.inputs) for (const input of commit.data.inputs) allInputs.push({
1513
+ input,
1514
+ sourceCommitIdentifier: commit.commitIdentifier
1515
+ });
1516
+ return mergeItemsWithMergesWith({
1517
+ items: allInputs.map(({ input, sourceCommitIdentifier }) => ({
1518
+ item: input,
1519
+ sourceCommitIdentifier
1520
+ })),
1521
+ commitsMap,
1522
+ getItemsFromCommit: (commit) => commit.data.inputs,
1523
+ resolveItem: (item) => applyInputProperties(item),
1524
+ itemType: "input"
1525
+ });
1526
+ };
1527
+ /**
1528
+ * Resolves output from template if identifier is present.
1529
+ */
1530
+ const resolveOutputFromTemplate = (output, variables, templateInstance) => {
1531
+ const resolvedOutput = { ...output };
1532
+ if (!output.outputIdentifier) {
1533
+ if (output.valueSatoshis !== void 0) resolvedOutput.valueSatoshis = BigInt(output.valueSatoshis);
1534
+ if (output.lockingBytecode !== void 0) resolvedOutput.lockingBytecode = typeof output.lockingBytecode === "string" ? hexToBin(output.lockingBytecode) : output.lockingBytecode;
1535
+ return resolvedOutput;
1536
+ }
1537
+ const templateOutput = templateInstance.getOutput(output.outputIdentifier);
1538
+ if (resolvedOutput.valueSatoshis === void 0) {
1539
+ if (templateOutput.valueSatoshis && isCashAsmExpression(templateOutput.valueSatoshis)) {
1540
+ if (typeof templateOutput.valueSatoshis !== "string") throw new InvalidTemplateOutputSatoshisTypeError(typeof templateOutput.valueSatoshis);
1541
+ const variablesObject = convertCommitVariablesIntoObject(variables);
1542
+ resolvedOutput.valueSatoshis = BigInt(compileCashAssemblyString(templateOutput.valueSatoshis, variablesObject));
1543
+ }
1544
+ }
1545
+ if (resolvedOutput.lockingBytecode === void 0) {
1546
+ if (templateOutput.lockingScript && isCashAsmExpression(templateOutput.lockingScript)) {
1547
+ const variablesObject = convertCommitVariablesIntoObject(variables);
1548
+ resolvedOutput.lockingBytecode = hexToBin(compileCashAssemblyString(templateOutput.lockingScript, variablesObject));
1549
+ }
1550
+ }
1551
+ if (!resolvedOutput.lockingBytecode) throw new LockingBytecodeNotFoundForOutputError(output.outputIdentifier ?? "unknown", output.transactionIndex);
1552
+ if (typeof resolvedOutput.lockingBytecode === "string") resolvedOutput.lockingBytecode = hexToBin(resolvedOutput.lockingBytecode);
1553
+ if (output.valueSatoshis !== void 0) resolvedOutput.valueSatoshis = BigInt(output.valueSatoshis);
1554
+ if (output.lockingBytecode !== void 0) resolvedOutput.lockingBytecode = typeof output.lockingBytecode === "string" ? hexToBin(output.lockingBytecode) : output.lockingBytecode;
1555
+ delete resolvedOutput.outputIdentifier;
1556
+ return resolvedOutput;
1557
+ };
1558
+ /**
1559
+ * Applies output-specific properties and resolves from template.
1560
+ */
1561
+ const applyOutputProperties = (output, variables, templateInstance) => {
1562
+ return resolveOutputFromTemplate(output, variables, templateInstance);
1563
+ };
1564
+ /**
1565
+ * Merges outputs from all commits, resolving mergesWith references and template identifiers.
1566
+ * Final list is sorted by transactionIndex.
1567
+ */
1568
+ const mergeOutputs = (commits, commitsMap, template, variables) => {
1569
+ const templateInstance = new Template(template);
1570
+ const allOutputs = [];
1571
+ for (const commit of commits) if (commit.data.outputs) for (const output of commit.data.outputs) allOutputs.push({
1572
+ output,
1573
+ sourceCommitIdentifier: commit.commitIdentifier
1574
+ });
1575
+ return mergeItemsWithMergesWith({
1576
+ items: allOutputs.map(({ output, sourceCommitIdentifier }) => ({
1577
+ item: output,
1578
+ sourceCommitIdentifier
1579
+ })),
1580
+ commitsMap,
1581
+ getItemsFromCommit: (commit) => commit.data.outputs,
1582
+ resolveItem: (item) => applyOutputProperties(item, variables, templateInstance),
1583
+ itemType: "output"
1584
+ });
1585
+ };
1586
+ /**
1587
+ * Merges invitation commits and transforms it into MergedInvitation structure.
1588
+ *
1589
+ * @param invitation - The invitation containing commits to merge.
1590
+ * @param template - The template used for resolving output identifiers.
1591
+ * @returns MergedInvitation structure, or null if no commits exist.
1592
+ * @throws {Error} If merge conflicts or missing references are detected.
1593
+ */
1594
+ const mergeInvitationCommits = (invitation, template) => {
1595
+ const { commits } = invitation;
1596
+ if (!commits?.length) return null;
1597
+ const commitsMap = /* @__PURE__ */ new Map();
1598
+ for (const commit of commits) commitsMap.set(commit.commitIdentifier, commit);
1599
+ validateCommitReferences(commits, commitsMap);
1600
+ const { variables, transactionVersion, transactionLocktime } = mergeSimpleData(commits);
1601
+ return {
1602
+ inputs: mergeInputs(commits, commitsMap),
1603
+ outputs: mergeOutputs(commits, commitsMap, template, variables),
1604
+ variables,
1605
+ transactionVersion: transactionVersion ?? DEFAULT_VERSION,
1606
+ transactionLocktime: transactionLocktime ?? DEFAULT_LOCKTIME
1607
+ };
1608
+ };
1609
+
1610
+ //#endregion
1611
+ //#region source/invitation/queries.ts
1612
+ /**
1613
+ * Field names that represent requirement types in an invitation.
1614
+ * These are the top-level fields that can contain requirement identifiers.
1615
+ */
1616
+ const INVITATION_REQUIREMENT_FIELD_NAMES = [
1617
+ "variables",
1618
+ "inputs",
1619
+ "outputs"
1620
+ ];
1621
+ /**
1622
+ * Checks if a role requirement has any items of the specified types.
1623
+ * @param roleRequirement - The role requirement object to check for any populated requirement fields.
1624
+ * @returns `true` if the role has any requirements (variables, inputs, or outputs), `false` otherwise.
1625
+ */
1626
+ const hasRoleRequirements = (roleRequirement) => {
1627
+ return INVITATION_REQUIREMENT_FIELD_NAMES.some((requirementFieldName) => {
1628
+ const requirementIdentifiers = roleRequirement[requirementFieldName];
1629
+ return requirementIdentifiers && requirementIdentifiers.length > 0;
1630
+ });
1631
+ };
1632
+ /**
1633
+ * Filters role requirements to only include those with actual populated requirements.
1634
+ * Removes any roles that have no variables, inputs, or outputs defined.
1635
+ * @param roleRequirements - Record mapping role identifiers to their requirement objects.
1636
+ * @returns Filtered record containing only roles that have at least one requirement field populated.
1637
+ */
1638
+ const filterRolesWithRequirements = (roleRequirements) => {
1639
+ const filteredRoleRequirements = {};
1640
+ for (const [roleIdentifier, roleRequirement] of Object.entries(roleRequirements)) if (hasRoleRequirements(roleRequirement)) filteredRoleRequirements[roleIdentifier] = roleRequirement;
1641
+ return filteredRoleRequirements;
1642
+ };
1643
+ /**
1644
+ * Finds requirement identifiers that are required but not yet populated.
1645
+ * @param requiredIdentifiers - Array of requirement identifiers that are expected/required.
1646
+ * @param populatedIdentifiers - Array of requirement identifiers that have already been provided.
1647
+ * @returns Array of identifiers that are required but missing from the populated list.
1648
+ */
1649
+ const findMissingRequirementIdentifiers = (requiredIdentifiers = [], populatedIdentifiers = []) => {
1650
+ return requiredIdentifiers.filter((identifier) => !populatedIdentifiers.includes(identifier));
1651
+ };
1652
+ /**
1653
+ * Processes and identifies missing requirements by comparing template requirements with populated requirements.
1654
+ * Analyzes both top-level requirements and role-specific requirements to determine what is still needed.
1655
+ * @param requirementsFromTemplate - Requirements expected from the template definition.
1656
+ * @param populatedRequirements - Requirements that have already been populated in the invitation.
1657
+ * @returns Object containing:
1658
+ * - `missingRequirements`: Top-level missing requirements (variables, inputs, outputs).
1659
+ * - `missingRoleRequirements`: Record of role-specific missing requirements keyed by role identifier.
1660
+ */
1661
+ const processMissingRequirements = (requirementsFromTemplate, populatedRequirements) => {
1662
+ const missingRequirements = {};
1663
+ const missingRoleRequirements = {};
1664
+ INVITATION_REQUIREMENT_FIELD_NAMES.forEach((requirementFieldName) => {
1665
+ const missingIdentifiers = findMissingRequirementIdentifiers(requirementsFromTemplate[requirementFieldName], populatedRequirements[requirementFieldName]);
1666
+ if (missingIdentifiers.length > 0) missingRequirements[requirementFieldName] = missingIdentifiers;
1667
+ });
1668
+ for (const [roleIdentifier, roleRequirement] of Object.entries(requirementsFromTemplate.roles ?? {})) {
1669
+ const populatedRoleRequirement = populatedRequirements.roles?.[roleIdentifier];
1670
+ INVITATION_REQUIREMENT_FIELD_NAMES.forEach((requirementFieldName) => {
1671
+ const missingIdentifiers = findMissingRequirementIdentifiers(roleRequirement[requirementFieldName], populatedRoleRequirement?.[requirementFieldName]);
1672
+ if (missingIdentifiers.length > 0) {
1673
+ if (!missingRoleRequirements[roleIdentifier]) missingRoleRequirements[roleIdentifier] = {};
1674
+ missingRoleRequirements[roleIdentifier][requirementFieldName] = missingIdentifiers;
1675
+ }
1676
+ });
1677
+ }
1678
+ return {
1679
+ missingRequirements,
1680
+ missingRoleRequirements
1681
+ };
1682
+ };
1683
+ /**
1684
+ * Extracts and lists all requirements from the template and action for an invitation.
1685
+ * Analyzes the template action to determine what variables, inputs, outputs, and role-specific
1686
+ * requirements are needed to fulfill the action.
1687
+ *
1688
+ * @param template - The template.
1689
+ * @param action - The action that has requirements.
1690
+ * @returns {XOInvitationRequirements} An object containing all the requirements.
1691
+ */
1692
+ const listRequirementsFromTemplate = (template, action) => {
1693
+ const generalRequirements = {};
1694
+ const roleRequirements = {};
1695
+ if (action.roles) {
1696
+ for (const [roleIdentifier, roleDefinition] of Object.entries(action.roles)) if (roleDefinition.requirements) {
1697
+ if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};
1698
+ if (roleDefinition.requirements.variables) roleRequirements[roleIdentifier].variables = roleDefinition.requirements.variables;
1699
+ }
1700
+ }
1701
+ if (action.requirements?.participants) for (const roleSlot of action.requirements.participants) {
1702
+ const roleIdentifier = roleSlot.role;
1703
+ if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};
1704
+ const roleVariables = action.roles?.[roleIdentifier]?.requirements?.variables;
1705
+ if (roleVariables) roleRequirements[roleIdentifier].variables = roleVariables;
1706
+ }
1707
+ if (action.transaction) {
1708
+ const transactionDefinition = new Template(template).getTransaction(action.transaction);
1709
+ if (transactionDefinition.roles) for (const [roleIdentifier, transactionRoleRequirement] of Object.entries(transactionDefinition.roles)) {
1710
+ if (!roleRequirements[roleIdentifier]) roleRequirements[roleIdentifier] = {};
1711
+ if (transactionRoleRequirement.inputs) {
1712
+ const transactionInputRequirementIdentifiers = [];
1713
+ for (const transactionInputRequirement of transactionRoleRequirement.inputs) transactionInputRequirementIdentifiers.push(transactionInputRequirement.input);
1714
+ roleRequirements[roleIdentifier].inputs = transactionInputRequirementIdentifiers;
1715
+ }
1716
+ if (transactionRoleRequirement.outputs) {
1717
+ const transactionOutputRequirementIdentifiers = [];
1718
+ for (const transactionOutputRequirement of transactionRoleRequirement.outputs) transactionOutputRequirementIdentifiers.push(transactionOutputRequirement.output);
1719
+ roleRequirements[roleIdentifier].outputs = transactionOutputRequirementIdentifiers;
1720
+ }
1721
+ }
1722
+ if (transactionDefinition.inputs && transactionDefinition.inputs.length > 0) generalRequirements.inputs = transactionDefinition.inputs.map((transactionInput) => transactionInput.input);
1723
+ if (transactionDefinition.outputs && transactionDefinition.outputs.length > 0) generalRequirements.outputs = transactionDefinition.outputs.map((transactionOutput) => transactionOutput.output);
1724
+ }
1725
+ const roleRequirementsWithItems = filterRolesWithRequirements(roleRequirements);
1726
+ const finalRequirements = {};
1727
+ for (const requirementFieldName of INVITATION_REQUIREMENT_FIELD_NAMES) {
1728
+ const requirementIdentifiers = generalRequirements[requirementFieldName];
1729
+ if (requirementIdentifiers !== void 0 && requirementIdentifiers.length > 0) finalRequirements[requirementFieldName] = requirementIdentifiers;
1730
+ }
1731
+ if (Object.keys(roleRequirementsWithItems).length > 0) finalRequirements.roles = roleRequirementsWithItems;
1732
+ return finalRequirements;
1733
+ };
1734
+ /**
1735
+ * Counts the number of distinct entities that have filled a specific role in the invitation.
1736
+ * An entity is considered to have filled a role if any of its commits contain data
1737
+ * (variables, inputs, or outputs) associated with that role identifier.
1738
+ *
1739
+ * TODO: Determine how an Authorized Entity will get into the invitation process.
1740
+ *
1741
+ * @param invitation - The invitation to examine.
1742
+ * @param roleIdentifier - The role identifier to count filled slots for.
1743
+ * @returns The number of unique entities that have contributed data for the specified role.
1744
+ */
1745
+ const countFilledSlotsForRole = (invitation, roleIdentifier) => {
1746
+ const entityIdentifiers = /* @__PURE__ */ new Set();
1747
+ for (const commit of invitation.commits ?? []) {
1748
+ const { variables, inputs, outputs } = commit.data;
1749
+ let hasRoleData = false;
1750
+ for (const list of [
1751
+ variables ?? [],
1752
+ inputs ?? [],
1753
+ outputs ?? []
1754
+ ]) {
1755
+ for (const item of list) if (item.roleIdentifier === roleIdentifier) {
1756
+ hasRoleData = true;
1757
+ break;
1758
+ }
1759
+ if (hasRoleData) break;
1760
+ }
1761
+ if (hasRoleData) entityIdentifiers.add(commit.entityIdentifier);
1762
+ }
1763
+ return entityIdentifiers.size;
1764
+ };
1765
+ /**
1766
+ * Adds variable identifiers from invitation variables to the appropriate requirement collections.
1767
+ * Variables are added to either top-level requirements or role-specific requirements based on
1768
+ * whether they have a role identifier. This can be customized independently as variable handling evolves.
1769
+ *
1770
+ * @param variables - Array of invitation variables to extract identifiers from.
1771
+ * @param generalRequirements - Requirements object to add top-level variable identifiers to.
1772
+ * @param roleRequirements - Record of role requirements to add role-specific variable identifiers to.
1773
+ * @returns Updated requirements objects.
1774
+ */
1775
+ const addVariableIdentifiers = (variables, generalRequirements, roleRequirements) => {
1776
+ const updatedGeneralRequirements = { ...generalRequirements };
1777
+ const updatedRoleRequirements = { ...roleRequirements };
1778
+ for (const variable of variables) {
1779
+ if (!variable.variableIdentifier) continue;
1780
+ if (variable.roleIdentifier) {
1781
+ if (!updatedRoleRequirements[variable.roleIdentifier]) updatedRoleRequirements[variable.roleIdentifier] = {};
1782
+ const roleRequirement = updatedRoleRequirements[variable.roleIdentifier];
1783
+ if (!roleRequirement.variables) roleRequirement.variables = [];
1784
+ roleRequirement.variables.push(variable.variableIdentifier);
1785
+ } else {
1786
+ if (!updatedGeneralRequirements.variables) updatedGeneralRequirements.variables = [];
1787
+ updatedGeneralRequirements.variables.push(variable.variableIdentifier);
1788
+ }
1789
+ }
1790
+ return {
1791
+ generalRequirements: updatedGeneralRequirements,
1792
+ roleRequirements: updatedRoleRequirements
1793
+ };
1794
+ };
1795
+ /**
1796
+ * Adds input identifiers from invitation inputs to the appropriate requirement collections.
1797
+ * Inputs are added to either top-level requirements or role-specific requirements based on
1798
+ * whether they have a role identifier.
1799
+ *
1800
+ * @param inputs - Array of invitation inputs to extract identifiers from.
1801
+ * @param generalRequirements - Requirements object to add top-level input identifiers to.
1802
+ * @param roleRequirements - Record of role requirements to add role-specific input identifiers to.
1803
+ * @returns Updated requirements objects.
1804
+ */
1805
+ const addInputIdentifiers = (inputs, generalRequirements, roleRequirements) => {
1806
+ const updatedGeneralRequirements = { ...generalRequirements };
1807
+ const updatedRoleRequirements = { ...roleRequirements };
1808
+ for (const input of inputs) {
1809
+ if (!input.inputIdentifier) continue;
1810
+ if (input.roleIdentifier) {
1811
+ if (!updatedRoleRequirements[input.roleIdentifier]) updatedRoleRequirements[input.roleIdentifier] = {};
1812
+ const roleRequirement = updatedRoleRequirements[input.roleIdentifier];
1813
+ if (!roleRequirement.inputs) roleRequirement.inputs = [];
1814
+ roleRequirement.inputs.push(input.inputIdentifier);
1815
+ } else {
1816
+ if (!updatedGeneralRequirements.inputs) updatedGeneralRequirements.inputs = [];
1817
+ updatedGeneralRequirements.inputs.push(input.inputIdentifier);
1818
+ }
1819
+ }
1820
+ return {
1821
+ generalRequirements: updatedGeneralRequirements,
1822
+ roleRequirements: updatedRoleRequirements
1823
+ };
1824
+ };
1825
+ /**
1826
+ * Adds output identifiers from invitation outputs to the appropriate requirement collections.
1827
+ * Outputs are added to either top-level requirements or role-specific requirements based on
1828
+ * whether they have a role identifier. This can be customized independently as output handling evolves.
1829
+ *
1830
+ * @param outputs - Array of invitation outputs to extract identifiers from.
1831
+ * @param generalRequirements - Requirements object to add top-level output identifiers to.
1832
+ * @param roleRequirements - Record of role requirements to add role-specific output identifiers to.
1833
+ * @returns Updated requirements objects.
1834
+ */
1835
+ const addOutputIdentifiers = (outputs, generalRequirements, roleRequirements) => {
1836
+ const updatedGeneralRequirements = { ...generalRequirements };
1837
+ const updatedRoleRequirements = { ...roleRequirements };
1838
+ for (const output of outputs) {
1839
+ if (!output.outputIdentifier) continue;
1840
+ if (output.roleIdentifier) {
1841
+ if (!updatedRoleRequirements[output.roleIdentifier]) updatedRoleRequirements[output.roleIdentifier] = {};
1842
+ const roleRequirement = updatedRoleRequirements[output.roleIdentifier];
1843
+ if (!roleRequirement.outputs) roleRequirement.outputs = [];
1844
+ roleRequirement.outputs.push(output.outputIdentifier);
1845
+ } else {
1846
+ if (!updatedGeneralRequirements.outputs) updatedGeneralRequirements.outputs = [];
1847
+ updatedGeneralRequirements.outputs.push(output.outputIdentifier);
1848
+ }
1849
+ }
1850
+ return {
1851
+ generalRequirements: updatedGeneralRequirements,
1852
+ roleRequirements: updatedRoleRequirements
1853
+ };
1854
+ };
1855
+ /**
1856
+ * Lists all requirements that have been populated in the invitation by examining all commits.
1857
+ * Extracts variable, input, and output identifiers from all commits in the invitation and
1858
+ * organizes them into top-level and role-specific requirements.
1859
+ *
1860
+ * @param invitation - The invitation object to analyze for populated requirements.
1861
+ * @returns An object containing all populated requirements found in the invitation's commits,
1862
+ * including top-level requirements and role-specific requirements. Only includes roles
1863
+ * that have at least one requirement populated.
1864
+ */
1865
+ const listPopulatedRequirementsInInvitation = (invitation) => {
1866
+ let generalRequirements = {};
1867
+ let roleRequirements = {};
1868
+ for (const commit of invitation.commits ?? []) {
1869
+ const { variables, inputs, outputs } = commit.data;
1870
+ if (variables) {
1871
+ const result = addVariableIdentifiers(variables, generalRequirements, roleRequirements);
1872
+ generalRequirements = result.generalRequirements;
1873
+ roleRequirements = result.roleRequirements;
1874
+ }
1875
+ if (inputs) {
1876
+ const result = addInputIdentifiers(inputs, generalRequirements, roleRequirements);
1877
+ generalRequirements = result.generalRequirements;
1878
+ roleRequirements = result.roleRequirements;
1879
+ }
1880
+ if (outputs) {
1881
+ const result = addOutputIdentifiers(outputs, generalRequirements, roleRequirements);
1882
+ generalRequirements = result.generalRequirements;
1883
+ roleRequirements = result.roleRequirements;
1884
+ }
1885
+ }
1886
+ return {
1887
+ ...generalRequirements,
1888
+ ...Object.keys(roleRequirements).length > 0 && { roles: roleRequirements }
1889
+ };
1890
+ };
1891
+ /**
1892
+ * Lists all missing requirements for the invitation that have not yet been supplied.
1893
+ * Compares the requirements expected from the template with what has been populated in the invitation
1894
+ * to determine what is still needed.
1895
+ *
1896
+ * Logic: `missing_requirements = requirements_from_template - populated_requirements_in_invitation`
1897
+ *
1898
+ * @param invitation - The invitation object to check for missing requirements.
1899
+ * @param template - The template defining what requirements are expected.
1900
+ * @param action - The template action being analyzed to determine required requirements.
1901
+ * @returns An object containing all missing requirements, including top-level missing requirements
1902
+ * and role-specific missing requirements. Only includes roles that have at least one missing requirement.
1903
+ */
1904
+ const listMissingRequirements = (invitation, template, action) => {
1905
+ const { missingRequirements, missingRoleRequirements } = processMissingRequirements(listRequirementsFromTemplate(template, action), listPopulatedRequirementsInInvitation(invitation));
1906
+ const roleRequirementsWithMissingItems = filterRolesWithRequirements(missingRoleRequirements);
1907
+ const finalMissingRequirements = { ...missingRequirements };
1908
+ if (Object.keys(roleRequirementsWithMissingItems).length > 0) finalMissingRequirements.roles = roleRequirementsWithMissingItems;
1909
+ return finalMissingRequirements;
1910
+ };
1911
+ /**
1912
+ * Lists role identifiers for roles that still have capacity for additional participants.
1913
+ * A role is considered available if the number of distinct entities that have filled it
1914
+ * is less than the role's maximum slot count. If max is undefined, the role has unlimited capacity.
1915
+ *
1916
+ * @param invitation - The invitation object to check for available roles.
1917
+ * @param template - The template defining the invitation structure and requirements.
1918
+ * @param action - The template action being analyzed to determine which roles are expected.
1919
+ * @returns Array of role identifier strings representing roles that can still accept participants.
1920
+ * Returns an empty array if no roles are defined in the action.
1921
+ */
1922
+ const listAvailableRolesForInvitation = (invitation, action) => {
1923
+ const actionRoleSpecs = action.requirements?.participants ?? [];
1924
+ if (actionRoleSpecs.length === 0) return [];
1925
+ const availableRoleIdentifiers = [];
1926
+ for (const roleSpec of actionRoleSpecs) {
1927
+ const roleIdentifier = roleSpec.role;
1928
+ const filledSlots = countFilledSlotsForRole(invitation, roleIdentifier);
1929
+ const maxSlots = roleSpec.slots?.max;
1930
+ if (maxSlots === void 0 || filledSlots < maxSlots) availableRoleIdentifiers.push(roleIdentifier);
1931
+ }
1932
+ return availableRoleIdentifiers;
1933
+ };
1934
+
1935
+ //#endregion
1936
+ //#region source/invitation/validation.ts
1937
+ /**
1938
+ * Validates that the invitation has not expired for any of the commits.
1939
+ *
1940
+ * @param invitation - The XOInvitation object containing creation and expiration timestamps.
1941
+ * @returns True if the invitation is expired, false if it is valid.
1942
+ */
1943
+ const hasInvitationExpired = (invitation) => {
1944
+ const { commits } = invitation;
1945
+ const now = Date.now();
1946
+ return commits.some((commit) => commit.expiresAtTimestamp < now);
1947
+ };
1948
+ /**
1949
+ * Validates that all entity identifiers in the invitation are valid public keys.
1950
+ * Extracts unique entity identifiers from all commits.
1951
+ *
1952
+ * @param invitation - The invitation to validate.
1953
+ * @returns True if all entities are valid, false otherwise.
1954
+ */
1955
+ const validateInvitationEntities = (invitation) => {
1956
+ const entityIdentifiers = new Set(invitation.commits.map((commit) => commit.entityIdentifier));
1957
+ for (const entityIdentifier of entityIdentifiers) try {
1958
+ new PublicKey(entityIdentifier);
1959
+ } catch {
1960
+ return false;
1961
+ }
1962
+ return true;
1963
+ };
1964
+ /**
1965
+ * Validates that all provided requirements in the invitation were expected by the template.
1966
+ *
1967
+ * @param invitation - The invitation to validate.
1968
+ * @param template - The template to validate against.
1969
+ * @param action - The action to validate against.
1970
+ * @returns True if all requirements are expected, false otherwise.
1971
+ */
1972
+ const validateRoleRequirements = (invitation, template, action) => {
1973
+ const expectedRequirementsByTemplate = listRequirementsFromTemplate(template, action);
1974
+ const populatedRequirementsByInvitation = listPopulatedRequirementsInInvitation(invitation);
1975
+ const requirementTypes = [
1976
+ "variables",
1977
+ "inputs",
1978
+ "outputs"
1979
+ ];
1980
+ for (const type of requirementTypes) {
1981
+ const populated = populatedRequirementsByInvitation[type] ?? [];
1982
+ const expected = expectedRequirementsByTemplate[type] ?? [];
1983
+ for (const populatedIdentifier of populated) if (!expected.some((expectedIdentifier) => expectedIdentifier === populatedIdentifier)) return false;
1984
+ }
1985
+ if (populatedRequirementsByInvitation.roles) for (const [roleIdentifier, populatedRole] of Object.entries(populatedRequirementsByInvitation.roles)) {
1986
+ const expectedRole = expectedRequirementsByTemplate.roles?.[roleIdentifier];
1987
+ if (!expectedRole) return false;
1988
+ for (const type of requirementTypes) {
1989
+ const populated = populatedRole[type] ?? [];
1990
+ const expected = expectedRole[type] ?? [];
1991
+ for (const populatedIdentifier of populated) if (!expected.some((expectedIdentifier) => expectedIdentifier === populatedIdentifier)) return false;
1992
+ }
1993
+ }
1994
+ return true;
1995
+ };
1996
+ /**
1997
+ * Validates commit signatures.
1998
+ * Signature signs: stringify(data) + templateIdentifier + actionIdentifier + invitationIdentifier + commitIdentifier + previousCommitIdentifier
1999
+ *
2000
+ * @param invitation - The invitation containing commits to validate.
2001
+ * @returns True if all commit signatures are valid, false otherwise.
2002
+ */
2003
+ const validateInvitationCommits = (invitation) => {
2004
+ const { templateIdentifier, actionIdentifier, invitationIdentifier, commits } = invitation;
2005
+ for (const commit of commits) {
2006
+ const entityPublicKey = commit.entityIdentifier;
2007
+ const commitSigningPayload = buildInvitationCommitSigningPayload({
2008
+ data: commit.data,
2009
+ templateIdentifier,
2010
+ actionIdentifier,
2011
+ invitationIdentifier,
2012
+ commitIdentifier: commit.commitIdentifier,
2013
+ previousCommitIdentifier: commit.previousCommitIdentifier
2014
+ });
2015
+ if (!verifySchnorrSignature(commit.signature, entityPublicKey, commitSigningPayload)) return false;
2016
+ }
2017
+ return true;
2018
+ };
2019
+
2020
+ //#endregion
2021
+ //#region source/engine.ts
2022
+ /**
2023
+ * XO Engine class: Acts like an orchestrator for the XO system.
2024
+ */
2025
+ var Engine = class Engine {
2026
+ /**
2027
+ * The crypto instance.
2028
+ */
2029
+ crypto;
2030
+ /**
2031
+ * The state instance.
2032
+ */
2033
+ state;
2034
+ /**
2035
+ * The blockchain monitor instance.
2036
+ */
2037
+ blockchainMonitor;
2038
+ /**
2039
+ * The default template identifier.
2040
+ */
2041
+ defaultTemplateIdentifier;
2042
+ /**
2043
+ * The default role identifier.
2044
+ */
2045
+ defaultRoleIdentifier;
2046
+ /**
2047
+ * The default output identifier.
2048
+ */
2049
+ defaultOutputIdentifier;
2050
+ /**
2051
+ * Constructs a new instance of XO Engine.
2052
+ * @private
2053
+ * @param {string} seed - The wallet seed.
2054
+ * @param {State} store - Store instance.
2055
+ * @param {BlockchainMonitor} blockchainMonitor - Blockchain monitor instance.
2056
+ */
2057
+ constructor(seed, state, blockchainMonitor) {
2058
+ this.crypto = new Crypto(convertMnemonicToSeedBytes(seed));
2059
+ this.state = state;
2060
+ this.blockchainMonitor = blockchainMonitor;
2061
+ }
2062
+ /**
2063
+ * Initializes and creates a new XO Engine instance.
2064
+ * Configures the state, initializes the sync server and monitor for app and blockchain events
2065
+ *
2066
+ * @param {string} seed - Wallet seed used for signing and/or key derivation.
2067
+ * @param {XOEngineOptions} options - Database configuration options.
2068
+ * @returns {Promise<Engine>} An initialized Engine instance.
2069
+ */
2070
+ static async create(seed, options) {
2071
+ await initializeElectrumApplication(options.electrumApplicationIdentifier ?? DEFAULT_ELECTRUM_APPLICATION_IDENTIFIER, {
2072
+ electrumServers,
2073
+ ...options
2074
+ });
2075
+ const accountHash = binToHex(sha256.hash(utf8ToBin(seed)));
2076
+ const stateInstance = new State(await createStorageAdapter({
2077
+ storageType: options.storageType ?? DEFAULT_STORAGE_TYPE,
2078
+ databasePath: options.databasePath,
2079
+ databaseFilename: options.databaseFilename,
2080
+ accountHash
2081
+ }));
2082
+ const blockchainMonitor = new BlockchainMonitor(stateInstance);
2083
+ blockchainMonitor.initializeEventListeners();
2084
+ const engineInstance = new Engine(seed, stateInstance, blockchainMonitor);
2085
+ await engineInstance.initializeStateSync();
2086
+ return engineInstance;
2087
+ }
2088
+ /**
2089
+ * Stops the engine instance and cleans up resources.
2090
+ * @returns {Promise<void>} Resolves when the engine is stopped.
2091
+ */
2092
+ async stop() {
2093
+ await this.blockchainMonitor.stop();
2094
+ }
2095
+ /**
2096
+ * Retrieves the current chain status from the electrum application.
2097
+ * @returns {Promise<ChainStatus>} The current chain status.
2098
+ */
2099
+ async getChainStatus() {
2100
+ return getChainStatus();
2101
+ }
2102
+ /**
2103
+ * Retrieves a template by its identifier from the state.
2104
+ * @param {string} templateIdentifier - Template identifier.
2105
+ * @returns {Promise<XOTemplate | undefined>} The template object.
2106
+ */
2107
+ async getTemplate(templateIdentifier) {
2108
+ return await this.state.getTemplate(templateIdentifier);
2109
+ }
2110
+ /**
2111
+ * Imports a template into the Engine after sanitization and validation.
2112
+ * @param {string | XOTemplate} untrustedJsonOrObject - JSON or object containing the untrusted template to import.
2113
+ * @returns {Promise<void>} Resolves when the template is imported.
2114
+ * @throws {TemplateImportFailedError} If the template is invalid.
2115
+ */
2116
+ async importTemplate(untrustedJsonOrObject) {
2117
+ const template = parseTemplate$1(untrustedJsonOrObject);
2118
+ await this.state.storeTemplate(template);
2119
+ return {
2120
+ template,
2121
+ templateIdentifier: generateTemplateIdentifier$1(template)
2122
+ };
2123
+ }
2124
+ /**
2125
+ * Lists all the imported templates.
2126
+ * @returns {Promise<XOTemplate[]>} The list of imported templates.
2127
+ */
2128
+ async listImportedTemplates() {
2129
+ return await this.state.listTemplates() ?? [];
2130
+ }
2131
+ /**
2132
+ * Lists the starting actions available in a specified template.
2133
+ * @param {string} templateIdentifier - Template identifier.
2134
+ * @returns {Promise<Array<XOTemplateActionIntent>>} The list of starting actions.
2135
+ */
2136
+ async listStartingActions(templateIdentifier) {
2137
+ return new Template(await this.getTemplateOrThrow(templateIdentifier)).getStartingActions();
2138
+ }
2139
+ /**
2140
+ * Update the unspent outputs for all of a templates lockingBytecodes.
2141
+ *
2142
+ * TODO: Make this an private/internal method.
2143
+ *
2144
+ * @param {string} templateIdentifier - Template identifier.
2145
+ * @returns {Promise<void>} Resolves when the unspent outputs are updated.
2146
+ */
2147
+ async updateUnspentOutputsForTemplate(templateIdentifier) {
2148
+ const scriptHashDataList = await this.listScriptHashesForTemplate(templateIdentifier);
2149
+ for (const scriptHashData of scriptHashDataList) await this.updateUnspentOutputsForScriptHashInStore(scriptHashData.scriptHash);
2150
+ }
2151
+ /**
2152
+ * Subscribe to the script hashes for a template.
2153
+ *
2154
+ * TODO: Make this a private/internal method. We may change how/where this is defined in the future.
2155
+ * We'd like to ensure events are propagated to the sync server with an ACK and that the states match between remote and local.
2156
+ *
2157
+ * @param {string} templateIdentifier - Template identifier.
2158
+ * @returns {Promise<void>} Resolves when the script hashes are subscribed.
2159
+ */
2160
+ async subscribeToScriptHashForTemplate(templateIdentifier) {
2161
+ const [firstElectrumClient] = electrumClients.values();
2162
+ if (firstElectrumClient === void 0) return;
2163
+ const scriptHashDataList = await this.listScriptHashesForTemplate(templateIdentifier);
2164
+ for (const scriptHashData of scriptHashDataList) await subscribeToScriptHashUpdates(firstElectrumClient, scriptHashData.scriptHash);
2165
+ }
2166
+ /**
2167
+ * TENTATIVE METHOD: DEFAULT LOCKING STRATEGY UNKNOWN
2168
+ *
2169
+ * Sets the default locking parameters (template, output, and role identifiers) for the engine.
2170
+ * TODO: The default identifiers exist as the strategy on how to create the change and default
2171
+ * unlocking conditions are unclear. This is likely to change in the future.
2172
+ *
2173
+ * @param {string} templateIdentifier - The identifier of the template to use as default.
2174
+ * @param {string} outputIdentifier - The identifier of the output within the specified template.
2175
+ * @param {string} roleIdentifier - The identifier of the role to use as default for this output.
2176
+ * @returns {Promise<void>} Resolves when the default parameters have been successfully set.
2177
+ * @throws {Error} If the template or output cannot be found.
2178
+ */
2179
+ async setDefaultLockingParameters(templateIdentifier, outputIdentifier, roleIdentifier) {
2180
+ this.defaultTemplateIdentifier = templateIdentifier;
2181
+ this.defaultOutputIdentifier = outputIdentifier;
2182
+ this.defaultRoleIdentifier = roleIdentifier;
2183
+ }
2184
+ /**
2185
+ * TODO: Implement this.
2186
+ *
2187
+ * State sync should always be working, any hiccups in the sync process should be resolved
2188
+ * Unable to do so should halt all operations unless no remote servers are provided.
2189
+ *
2190
+ * Initializes the state sync process.
2191
+ * @returns {Promise<void>} Resolves when the state sync is initialized.
2192
+ */
2193
+ async initializeStateSync() {}
2194
+ /**
2195
+ * Creates an invitation that can be shared with other entities, user, application, etc.
2196
+ * Invitation is the fundamental communication unit in XO, all the interactions done using the
2197
+ * xo template are done using invitations.
2198
+ *
2199
+ * @param {InvitationCreationParameters} params - The parameters for invitation creation.
2200
+ * @param {string} params.templateIdentifier - Identifier for the template to use.
2201
+ * @param {string} params.actionIdentifier - Identifier for the action to initiate.
2202
+ * @returns {Promise<XOInvitation>} A promise that resolves to the constructed invitation.
2203
+ * @throws {TemplateNotFoundError} If the template is not found.
2204
+ * @throws {ActionNotFoundError} If the action is not found.
2205
+ *
2206
+ * TODO: Add all the throws that happen during the execution of the method.
2207
+ */
2208
+ async createInvitation(params) {
2209
+ new Template(await this.getTemplateOrThrow(params.templateIdentifier)).getActionOrThrow(params.actionIdentifier);
2210
+ const invitationBuilder = new InvitationBuilder(params);
2211
+ const invitationCommit = invitationBuilder.createUnsignedCommit({});
2212
+ const rootCommitIdentifier = invitationCommit.commitIdentifier;
2213
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2214
+ invitationCommit,
2215
+ invitationIdentifier: invitationBuilder.invitationIdentifier,
2216
+ rootCommitIdentifier,
2217
+ templateIdentifier: invitationBuilder.templateIdentifier,
2218
+ actionIdentifier: invitationBuilder.actionIdentifier
2219
+ });
2220
+ invitationBuilder.addCommit(signedCommit);
2221
+ const invitation = invitationBuilder.build();
2222
+ await this.state.storeInvitation(invitation.invitationIdentifier, {
2223
+ ...invitation,
2224
+ entityIdentifier: signedCommit.entityIdentifier
2225
+ });
2226
+ return invitation;
2227
+ }
2228
+ /**
2229
+ * Accepts an invitation, an entity accepts an invitation and becomes part of the invitation.
2230
+ *
2231
+ * @param {XOInvitation} invitation - The invitation to be accepted.
2232
+ * @param {AcceptInvitationParameters} params - Optional parameters for accepting the invitation.
2233
+ * @returns {Promise<XOInvitation>} The updated XOInvitation instance.
2234
+ * @throws {TemplateNotFoundError} If the template is not found.
2235
+ * @throws {ActionNotFoundError} If the action is not found.
2236
+ * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
2237
+ * @throws {InvalidRequirementsError} If the requirements are invalid.
2238
+ * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
2239
+ */
2240
+ async acceptInvitation(invitation, params) {
2241
+ new Template(await this.getTemplateOrThrow(invitation.templateIdentifier)).getActionOrThrow(invitation.actionIdentifier);
2242
+ const invitationFromStore = await this.state.getInvitation(invitation.invitationIdentifier);
2243
+ if (invitationFromStore !== void 0) return invitationFromStore;
2244
+ const invitationBuilder = InvitationBuilder.fromInvitation(invitation);
2245
+ const invitationCommit = invitationBuilder.createUnsignedCommit({ ...params });
2246
+ const rootCommitIdentifier = invitationCommit.commitIdentifier;
2247
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2248
+ invitationCommit,
2249
+ invitationIdentifier: invitationBuilder.invitationIdentifier,
2250
+ rootCommitIdentifier,
2251
+ templateIdentifier: invitationBuilder.templateIdentifier,
2252
+ actionIdentifier: invitationBuilder.actionIdentifier
2253
+ });
2254
+ invitationBuilder.addCommit(signedCommit);
2255
+ const acceptedInvitation = invitationBuilder.build();
2256
+ await this.state.storeInvitation(acceptedInvitation.invitationIdentifier, {
2257
+ ...acceptedInvitation,
2258
+ entityIdentifier: signedCommit.entityIdentifier
2259
+ });
2260
+ return acceptedInvitation;
2261
+ }
2262
+ /**
2263
+ * Appends the invitation with the new information.
2264
+ *
2265
+ * @param {XOInvitation} invitation - The invitation to append.
2266
+ * @param {AppendInvitationParameters} params - The parameters to append the invitation with.
2267
+ * @returns {Promise<XOInvitation>} The appended invitation.
2268
+ */
2269
+ async appendInvitation(invitation, params) {
2270
+ const invitationFromStore = await this.getInvitationOrThrow(invitation.invitationIdentifier);
2271
+ const rootCommitIdentifier = findRootCommitIdentifierInInvitation(invitationFromStore, invitationFromStore.entityIdentifier);
2272
+ if (rootCommitIdentifier === void 0) throw new RootCommitNotFoundError(invitationFromStore.entityIdentifier);
2273
+ const invitationBuilder = InvitationBuilder.fromInvitation(invitation);
2274
+ if (params.outputs) for (const output of params.outputs) {
2275
+ if (output.mergesWith !== void 0 || output.roleIdentifier !== void 0 || output.lockingBytecode !== void 0) continue;
2276
+ output.lockingBytecode = hexToBin(await this.generateLockingBytecodeForDefaultParameters());
2277
+ }
2278
+ const signedCommit = this.crypto.signInvitationCommitWithSchnorr({
2279
+ invitationCommit: invitationBuilder.createUnsignedCommit({ ...params }),
2280
+ invitationIdentifier: invitationBuilder.invitationIdentifier,
2281
+ rootCommitIdentifier,
2282
+ templateIdentifier: invitationBuilder.templateIdentifier,
2283
+ actionIdentifier: invitationBuilder.actionIdentifier
2284
+ });
2285
+ invitationBuilder.addCommit(signedCommit);
2286
+ const inputsForReservation = await this.findOwnResources(params.inputs ?? []);
2287
+ if (inputsForReservation.length > 0) await this.reserveResources(inputsForReservation, invitationBuilder.invitationIdentifier);
2288
+ const updatedInvitation = invitationBuilder.build();
2289
+ await this.state.storeInvitation(updatedInvitation.invitationIdentifier, {
2290
+ ...updatedInvitation,
2291
+ entityIdentifier: invitationFromStore.entityIdentifier
2292
+ });
2293
+ return updatedInvitation;
2294
+ }
2295
+ /**
2296
+ * Signs the provided invitation once all the resources are reserved and the invitation is complete.
2297
+ * This method is used to sign own inputs and provide unlocking data for them, this appends the
2298
+ * invitation and adds new commit with unlocking data.
2299
+ *
2300
+ * @param {XOInvitation} invitation - The invitation to sign.
2301
+ * @returns {Promise<XOInvitation>} Resolves when signing is complete.
2302
+ *
2303
+ * TODO: Add all the throws that happen during the execution of the method.
2304
+ */
2305
+ async signInvitation(invitation) {
2306
+ const invitationFromStore = await this.getInvitationOrThrow(invitation.invitationIdentifier);
2307
+ const template = await this.getTemplateOrThrow(invitationFromStore.templateIdentifier);
2308
+ const mergedCommit = mergeInvitationCommits(invitationFromStore, template);
2309
+ if (!mergedCommit) throw new MergedCommitNotFoundError();
2310
+ const transactionResult = generateTransaction({
2311
+ version: mergedCommit.transactionVersion,
2312
+ locktime: mergedCommit.transactionLocktime,
2313
+ inputs: mergedCommit.inputs,
2314
+ outputs: mergedCommit.outputs
2315
+ });
2316
+ if (!transactionResult.success) throw new TransactionGenerationFailedError();
2317
+ const unspentOutputs = await this.state.listUnspentOutputsData({ reservedBy: invitationFromStore.invitationIdentifier });
2318
+ for (const [index, input] of transactionResult.transaction.inputs.entries()) {
2319
+ let unspentOutput;
2320
+ for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex && sourceOutput.reservedBy) {
2321
+ unspentOutput = sourceOutput;
2322
+ break;
2323
+ }
2324
+ if (!unspentOutput) continue;
2325
+ const scriptHashData = await this.state.getScriptHashData(unspentOutput.scriptHash);
2326
+ if (scriptHashData === void 0) throw new ScriptHashDataNotFoundError(unspentOutput.scriptHash);
2327
+ let data;
2328
+ if (scriptHashData.derivationSource) {
2329
+ if (scriptHashData.derivationSource.lockingType === "standard") {
2330
+ const templateDataForInput = await this.state.getTemplate(scriptHashData.templateIdentifier);
2331
+ if (!templateDataForInput) throw new TemplateNotFoundError(scriptHashData.templateIdentifier);
2332
+ const templateInstanceForInput = new Template(templateDataForInput);
2333
+ const lockingScriptIdentifier = templateInstanceForInput.getLockingScriptIdentifier(scriptHashData.outputIdentifier);
2334
+ const secretIdentifiers = templateInstanceForInput.getSecrets(lockingScriptIdentifier, scriptHashData.roleIdentifier);
2335
+ const { derivativeIndex } = scriptHashData.derivationSource;
2336
+ if (typeof derivativeIndex !== "string") throw new InvalidDerivativeIndexTypeError("string", typeof derivativeIndex);
2337
+ data = this.crypto.derivePrivateKeyRecordForCompiler({
2338
+ compilerKeyIdentifiers: secretIdentifiers,
2339
+ templateIdentifier: scriptHashData.templateIdentifier,
2340
+ templateKeyDerivationIndex: Number(derivativeIndex)
2341
+ });
2342
+ }
2343
+ }
2344
+ if (!data) throw new LockingDataNotFoundError();
2345
+ const compilerData = await createLibauthCompilerDataFromUnspentOutput(new Template(template), unspentOutput);
2346
+ transactionResult.transaction.inputs[index] = {
2347
+ ...input,
2348
+ unlockingBytecode: {
2349
+ ...compilerData,
2350
+ data
2351
+ }
2352
+ };
2353
+ }
2354
+ const signedTransaction = generateTransaction({
2355
+ version: transactionResult.transaction.version,
2356
+ locktime: transactionResult.transaction.locktime,
2357
+ inputs: transactionResult.transaction.inputs,
2358
+ outputs: transactionResult.transaction.outputs
2359
+ });
2360
+ if (!signedTransaction.success) throw new TransactionGenerationFailedError();
2361
+ let extendedInvitation = InvitationBuilder.fromInvitation(invitation).build();
2362
+ for (const input of signedTransaction.transaction.inputs.values()) {
2363
+ let unspentOutput;
2364
+ for (const sourceOutput of unspentOutputs) if (sourceOutput.outpointTransactionHash === binToHex(input.outpointTransactionHash) && sourceOutput.outpointIndex === input.outpointIndex) {
2365
+ unspentOutput = sourceOutput;
2366
+ break;
2367
+ }
2368
+ if (!unspentOutput) throw new UnspentOutputNotFoundError();
2369
+ let commitToExtend;
2370
+ let indexToExtend;
2371
+ for (const commit of extendedInvitation.commits) for (const [index, commitInput] of (commit.data.inputs ?? []).entries()) if (commitInput.outpointTransactionHash && binToHex(commitInput.outpointTransactionHash) === binToHex(input.outpointTransactionHash) && Number(commitInput.outpointIndex) === Number(input.outpointIndex)) {
2372
+ commitToExtend = commit;
2373
+ indexToExtend = index;
2374
+ }
2375
+ if (commitToExtend === void 0 || indexToExtend === void 0) throw new CommitNotFoundInInvitationError();
2376
+ extendedInvitation = await this.appendInvitation(extendedInvitation, { inputs: [{
2377
+ mergesWith: {
2378
+ commitIdentifier: commitToExtend.commitIdentifier,
2379
+ index: indexToExtend
2380
+ },
2381
+ unlockingBytecode: input.unlockingBytecode
2382
+ }] });
2383
+ }
2384
+ return extendedInvitation;
2385
+ }
2386
+ /**
2387
+ * Executes an action for a given invitation.
2388
+ * @param {XOInvitation} invitation - The invitation whose action to execute.
2389
+ * @param {ExecuteActionParameters} params - Parameters for executing the action.
2390
+ * @returns {Promise<void>} Resolves when the action is executed.
2391
+ *
2392
+ * TODO: Add all the throws that happen during the execution of the method.
2393
+ */
2394
+ async executeAction(invitation, params) {
2395
+ const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);
2396
+ const builder = InvitationBuilder.fromInvitation(invitation).validate(templateFromStore).build();
2397
+ const action = new Template(templateFromStore).getActionOrThrow(builder.actionIdentifier);
2398
+ const mergedCommit = mergeInvitationCommits(builder, templateFromStore);
2399
+ if (!mergedCommit) throw new MergedCommitNotFoundError();
2400
+ if (!action.transaction) throw new TransactionNotFoundError();
2401
+ const resultTransaction = generateTransaction({
2402
+ version: mergedCommit.transactionVersion,
2403
+ locktime: mergedCommit.transactionLocktime,
2404
+ inputs: mergedCommit.inputs,
2405
+ outputs: mergedCommit.outputs
2406
+ });
2407
+ if (!resultTransaction.success) throw new TransactionGenerationFailedError();
2408
+ const transactionHex = binToHex(encodeTransaction(resultTransaction.transaction));
2409
+ const txHash = hashTransaction(hexToBin(transactionHex));
2410
+ if (params.broadcastTransaction) return await broadcastTransaction(transactionHex);
2411
+ return txHash;
2412
+ }
2413
+ /**
2414
+ * Fully validates a given XOInvitation according to template and signature checks.
2415
+ *
2416
+ * @param {XOInvitation} invitation - The invitation to validate.
2417
+ * @returns {Promise<void>} Resolves if invitation is valid.
2418
+ * @throws {TemplateNotFoundError} If the template is not found.
2419
+ * @throws {ActionNotFoundError} If the action is not found.
2420
+ * @throws {InvitationExpiredError} If the invitation has expired.
2421
+ * @throws {InvalidEntityIdentifierError} If the entity identifiers are invalid.
2422
+ * @throws {InvalidRequirementsError} If the requirements are invalid.
2423
+ * @throws {InvalidCommitSignaturesError} If the commit signatures are invalid.
2424
+ */
2425
+ async isInvitationValid(invitation) {
2426
+ const template = new Template(await this.state.getTemplate(invitation.templateIdentifier));
2427
+ try {
2428
+ InvitationBuilder.fromInvitation(invitation).validate(template.getTemplate());
2429
+ return true;
2430
+ } catch {
2431
+ return false;
2432
+ }
2433
+ }
2434
+ /**
2435
+ * Lists available roles for the given invitation.
2436
+ *
2437
+ * @param {XOInvitation} invitation - The invitation to examine.
2438
+ * @returns {Promise<string[]>} The list of roles that still require data.
2439
+ * @throws {TemplateNotFoundError} If the template is not found.
2440
+ * @throws {ActionNotFoundError} If the action is not found.
2441
+ */
2442
+ async listAvailableRoles(invitation) {
2443
+ return listAvailableRolesForInvitation(invitation, new Template(await this.getTemplateOrThrow(invitation.templateIdentifier)).getActionOrThrow(invitation.actionIdentifier));
2444
+ }
2445
+ /**
2446
+ * Lists requirements for the provided invitation.
2447
+ *
2448
+ * @param {XOInvitation} invitation - The invitation to analyze requirements for.
2449
+ * @returns {Promise<XOInvitationRequirements>} The requirements information.
2450
+ *
2451
+ */
2452
+ async listRequirements(invitation) {
2453
+ const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);
2454
+ return listRequirementsFromTemplate(templateFromStore, new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier));
2455
+ }
2456
+ /**
2457
+ * Lists missing requirements for the provided invitation.
2458
+ *
2459
+ * @param {XOInvitation} invitation - The invitation to analyze.
2460
+ * @returns {Promise<XOInvitationRequirements>} The missing requirements.
2461
+ */
2462
+ async listMissingRequirements(invitation) {
2463
+ const templateFromStore = await this.getTemplateOrThrow(invitation.templateIdentifier);
2464
+ return listMissingRequirements(invitation, templateFromStore, new Template(templateFromStore).getActionOrThrow(invitation.actionIdentifier));
2465
+ }
2466
+ /**
2467
+ * Lists all the unspent outputs.
2468
+ *
2469
+ * @returns {Promise<UnspentOutputData[]>} The list of unspent outputs.
2470
+ */
2471
+ async listUnspentOutputsData() {
2472
+ return this.state.listUnspentOutputsData();
2473
+ }
2474
+ /**
2475
+ * Finds suitable resources for an invitation.
2476
+ *
2477
+ * TODO: May become private. This may change in the future and become a more advanced coin selection method used directly by the engine.
2478
+ * The current behavior is that it finds "spendable" outputs, but we may adjust this to actually find "suitable" outputs.
2479
+ *
2480
+ * @param {XOInvitation} invitation - The invitation to find resources for.
2481
+ * @param {GetSpendableResourcesParameters} options - Parameters for finding suitable resources.
2482
+ * @returns {Promise<{ unspentOutputs: UnspentOutputData[] }>} The list of suitable resources.
2483
+ */
2484
+ async getSpendableResources(invitation, options) {
2485
+ const { templateIdentifier } = invitation;
2486
+ if (await this.state.getTemplate(templateIdentifier) === void 0) throw new TemplateNotFoundError(templateIdentifier);
2487
+ const sourceTemplateIdentifier = options?.templateIdentifier ?? this.defaultTemplateIdentifier;
2488
+ const sourceOutputIdentifier = options?.outputIdentifier ?? this.defaultOutputIdentifier;
2489
+ const rawSourceTemplate = await this.state.getTemplate(sourceTemplateIdentifier);
2490
+ if (rawSourceTemplate === void 0) throw new TemplateNotFoundError(sourceTemplateIdentifier);
2491
+ new Template(rawSourceTemplate).getOutput(sourceOutputIdentifier);
2492
+ const scriptHashDataList = await this.state.listScriptHashData({ templateIdentifier: sourceTemplateIdentifier });
2493
+ const unspentOutputs = [];
2494
+ for (const scriptHashData of scriptHashDataList) {
2495
+ const outputsByScriptHash = await this.state.listUnspentOutputsData({ scriptHash: scriptHashData.scriptHash });
2496
+ const unspentOutputsByScriptHash = [];
2497
+ for (const output of outputsByScriptHash) if (output.reservedBy === void 0) unspentOutputsByScriptHash.push(output);
2498
+ unspentOutputs.push(...unspentOutputsByScriptHash);
2499
+ }
2500
+ return { unspentOutputs };
2501
+ }
2502
+ /**
2503
+ * Retrieves a list of script hash data stored for a given template identifier.
2504
+ *
2505
+ * @param {string} templateIdentifier - The identifier of the template.
2506
+ * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.
2507
+ */
2508
+ async listScriptHashesForTemplate(templateIdentifier) {
2509
+ return this.state.listScriptHashData({ templateIdentifier });
2510
+ }
2511
+ /**
2512
+ * Gets all the script hashes from all the templates.
2513
+ *
2514
+ * @returns {Promise<ScriptHashData[]>} An array of script hash data objects.
2515
+ */
2516
+ async listScriptHashes() {
2517
+ const scriptHashDataPromises = (await this.state.listTemplates()).map((template) => generateTemplateIdentifier$1(template)).map((templateIdentifier) => this.listScriptHashesForTemplate(templateIdentifier));
2518
+ return (await Promise.all(scriptHashDataPromises)).flat();
2519
+ }
2520
+ /**
2521
+ * Generates the locking bytecode for a specified template output and role.
2522
+ *
2523
+ * Role is important because in the template definition it can direct to a different secret or a locking script
2524
+ * for that to be discovered and used, it must know what role is provided. Also, it's important for libauth compiler
2525
+ * to know what role is being used to generate the locking bytecode.
2526
+ *
2527
+ * Currently, only "standard" type (e.g. P2PKH) locking scripts are supported.
2528
+ * In the future, this method will be extended to support more output script types based on template definitions.
2529
+ *
2530
+ * Future definition of primitives is going to define how other non-p2pkh locking scripts are validated,
2531
+ * for example, p2pkh is possible because the engine know what a private key and public key is more such primitives
2532
+ * will be defined and they will be helpful in generating and validating locking scripts of different types.
2533
+ *
2534
+ * Process overview:
2535
+ * - Fetch the template and output definition by their identifiers.
2536
+ * - Find the relevant locking script and roles.
2537
+ * - Select the specified role or fallback to the first available role.
2538
+ * - Build the entity ownership mapping, scripts, and variable definitions for Libauth.
2539
+ * - Set up unlocking scripts and locking script type for the compiler configuration.
2540
+ * - For "standard" lock scripts, generate entropy if required. (TODO: Improve entropy generation.)
2541
+ * - Compile the locking bytecode with the Libauth compiler.
2542
+ * - Subscribe to blockchain updates for the script hash and store the resulting bytecode.
2543
+ *
2544
+ * TODO: Support additional types of outputs/scripts tied to template specification.
2545
+ * TODO: If important to make this process faster, consider emitting an event and pushing process to the event loop.
2546
+ * TODO: Encrypt the new information, update the encrypted state servers.
2547
+ *
2548
+ * @param {string} templateIdentifier - Identifier of the template.
2549
+ * @param {string} outputIdentifier - Identifier of the output (from the template).
2550
+ * @param {string} roleIdentifier - Role identifier (corresponding to a role in the output's script).
2551
+ * @returns {Promise<string>} The generated locking bytecode as a hexadecimal string.
2552
+ * @throws {Error} If any required template, output, or configuration is not found, or if compilation fails.
2553
+ */
2554
+ async generateLockingBytecode(templateIdentifier, outputIdentifier, roleIdentifier) {
2555
+ const template = new Template(await this.state.getTemplate(templateIdentifier));
2556
+ const output = template.getOutput(outputIdentifier);
2557
+ const lockingScriptForOutput = template.getLockingScriptForOutput(outputIdentifier);
2558
+ if (!output.lockingScript) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2559
+ template.validateLockingScript(lockingScriptForOutput, output.lockingScript);
2560
+ const selectedRoleId = roleIdentifier ?? template.getFirstRole(output.lockingScript)[0];
2561
+ if (roleIdentifier) template.getRole(output.lockingScript, roleIdentifier);
2562
+ const finalRoleIdentifier = selectedRoleId;
2563
+ const entityOwnership = entityOwnershipForLibauthCompiler(template.getTemplate(), finalRoleIdentifier);
2564
+ const scripts = scriptsForLibauthCompiler(template.getTemplate());
2565
+ const variables = assignTypeToVariablesForLibauthCompiler(template.getTemplate());
2566
+ if (lockingScriptForOutput.unlockingBytecode === void 0 || lockingScriptForOutput.lockingBytecode === void 0) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2567
+ const unlockingScripts = { [lockingScriptForOutput.unlockingBytecode]: lockingScriptForOutput.lockingBytecode };
2568
+ const { lockingType } = lockingScriptForOutput;
2569
+ if (!lockingType) throw new LockingScriptTypeNotFoundError(outputIdentifier);
2570
+ const compiler = createCompilerBch({
2571
+ entityOwnership,
2572
+ scripts,
2573
+ variables,
2574
+ unlockingScripts,
2575
+ lockingScriptTypes: { lock: convertXOLockingTypeToLibauth(lockingType) }
2576
+ });
2577
+ let lockingBytecodeMetadata = { lockingType: lockingScriptForOutput.lockingType };
2578
+ let lockingData;
2579
+ switch (lockingScriptForOutput.lockingType) {
2580
+ case "p2pkh": {
2581
+ const { lockingData: standardLockingData, derivativeIndex: standardDerivativeIndex } = await this.generateLockingDataForStandardP2PKH(templateIdentifier, outputIdentifier, finalRoleIdentifier, lockingScriptForOutput);
2582
+ lockingData = standardLockingData;
2583
+ lockingBytecodeMetadata = {
2584
+ ...lockingBytecodeMetadata,
2585
+ derivativeIndex: standardDerivativeIndex
2586
+ };
2587
+ break;
2588
+ }
2589
+ default: throw new LockingScriptTypeNotFoundError(output.lockingScript ?? outputIdentifier);
2590
+ }
2591
+ if (!lockingData) throw new LockingDataNotFoundError();
2592
+ const scriptId = lockingScriptForOutput.lockingBytecode;
2593
+ const resultLockingBytecode = compiler.generateBytecode({
2594
+ data: lockingData,
2595
+ scriptId
2596
+ });
2597
+ if (!resultLockingBytecode.success) throw new LockingBytecodeGenerationFailedError();
2598
+ const lockingBytecode = binToHex(resultLockingBytecode.bytecode);
2599
+ const scriptHash = scriptToScriptHash(hexToBin(lockingBytecode));
2600
+ const existingScriptHashData = await this.state.getScriptHashData(scriptHash);
2601
+ if (existingScriptHashData) return existingScriptHashData.lockingBytecode;
2602
+ const [firstElectrumClient] = electrumClients.values();
2603
+ if (!firstElectrumClient) throw new ElectrumClientNotFoundError();
2604
+ await subscribeToScriptHashUpdates(firstElectrumClient, scriptHash);
2605
+ await this.state.storeScriptHashData({
2606
+ lockingBytecode,
2607
+ derivationSource: lockingBytecodeMetadata,
2608
+ scriptHash,
2609
+ templateIdentifier,
2610
+ outputIdentifier,
2611
+ roleIdentifier: finalRoleIdentifier
2612
+ });
2613
+ await this.updateUnspentOutputsForScriptHashInStore(lockingBytecode);
2614
+ return lockingBytecode;
2615
+ }
2616
+ /**
2617
+ * Generates a locking bytecode using the engine's default template, output, and role identifiers.
2618
+ *
2619
+ * @returns A promise that resolves to the generated locking bytecode as a string.
2620
+ */
2621
+ async generateLockingBytecodeForDefaultParameters() {
2622
+ return this.generateLockingBytecode(this.defaultTemplateIdentifier, this.defaultOutputIdentifier, this.defaultRoleIdentifier);
2623
+ }
2624
+ /**
2625
+ * Generate locking data and derivative index for P2PKH.
2626
+ */
2627
+ async generateLockingDataForStandardP2PKH(templateIdentifier, outputIdentifier, roleIdentifier, lockingScriptForOutput) {
2628
+ const lastDerivativeIndex = await this.state.getLastDerivativeIndexForP2PKH(templateIdentifier, outputIdentifier);
2629
+ const derivativeIndex = lastDerivativeIndex === null ? "0" : (parseInt(lastDerivativeIndex, 10) + 1).toString();
2630
+ const privateKeyIdentifiers = (lockingScriptForOutput.roles?.[roleIdentifier])?.state?.secrets ?? [];
2631
+ return {
2632
+ lockingData: this.crypto.derivePrivateKeyRecordForCompiler({
2633
+ compilerKeyIdentifiers: privateKeyIdentifiers,
2634
+ templateIdentifier,
2635
+ templateKeyDerivationIndex: Number(derivativeIndex)
2636
+ }),
2637
+ derivativeIndex
2638
+ };
2639
+ }
2640
+ /**
2641
+ * Fetches a stored invitation by identifier
2642
+ *
2643
+ * @param {string} invitationIdentifier - The identifier to look up.
2644
+ * @returns {Promise<StoredInvitation | undefined>} The stored invitation, or undefined.
2645
+ */
2646
+ async getInvitationOrThrow(invitationIdentifier) {
2647
+ const invitation = await this.state.getInvitation(invitationIdentifier);
2648
+ if (invitation === void 0) throw new InvitationNotFoundInStoreError(invitationIdentifier);
2649
+ return invitation;
2650
+ }
2651
+ /**
2652
+ * Fetches a stored template by identifier
2653
+ *
2654
+ * @param {string} templateIdentifier - The identifier to look up.
2655
+ * @returns {Promise<XOTemplate>} The stored template.
2656
+ */
2657
+ async getTemplateOrThrow(templateIdentifier) {
2658
+ const template = await this.state.getTemplate(templateIdentifier);
2659
+ if (template === void 0) throw new TemplateNotFoundError(templateIdentifier);
2660
+ return template;
2661
+ }
2662
+ /**
2663
+ * Synchronizes the store of unspent outputs for a given script hash with the current state of the blockchain.
2664
+ *
2665
+ * This method performs the following:
2666
+ * 1. Retrieves the stored script hash data from the store.
2667
+ * 2. Fetches the current list of unspent outputs for the script hash from the store.
2668
+ * 3. Computes the corresponding scripthash from the script hash.
2669
+ * 4. Queries the blockchain for all unspent transaction outputs associated with the scripthash.
2670
+ * 5. Adds any new unspent outputs found on the blockchain but missing from the store to the store.
2671
+ * 6. Removes any unspent outputs present in the store but no longer in the blockchain.
2672
+ *
2673
+ * @param scriptHash - The script hash for which to update the stored unspent outputs.
2674
+ * @throws If the script hash is not found in the store.
2675
+ */
2676
+ async updateUnspentOutputsForScriptHashInStore(scriptHash) {
2677
+ const [firstElectrumClient] = electrumClients.values();
2678
+ if (!firstElectrumClient) throw new ElectrumClientNotFoundError();
2679
+ await updateUnspentOutputsForScriptHashInStore(this.state, scriptHash, async (scripthash) => {
2680
+ return fetchScriptHashUnspentTransactionOutputs(firstElectrumClient, scripthash);
2681
+ });
2682
+ }
2683
+ /**
2684
+ * TODO: Internal function, move elsewhere.
2685
+ *
2686
+ * Finds own inputs and prepares a list for the lookup in the store.
2687
+ *
2688
+ * @param {XOInvitationInput[]} inputs - The inputs to find resources for.
2689
+ * @returns {Promise<XOInvitationInput[]>} The list of own inputs for reservation.
2690
+ */
2691
+ async findOwnResources(inputs) {
2692
+ const inputsForReservation = [];
2693
+ if (inputs) for (const input of inputs) {
2694
+ if (input.mergesWith) continue;
2695
+ inputsForReservation.push({
2696
+ outpointTransactionHash: input.outpointTransactionHash,
2697
+ outpointIndex: input.outpointIndex
2698
+ });
2699
+ }
2700
+ return inputsForReservation;
2701
+ }
2702
+ /**
2703
+ * Reserves utxos and store information in the storage.
2704
+ *
2705
+ * @param {XOInvitationInput[]} inputs - The inputs to reserve.
2706
+ * @param {string} invitationIdentifier - The identifier of the invitation for which the resources are being reserved.
2707
+ * @returns {Promise<void>} Resolves when the reservation is complete.
2708
+ */
2709
+ async reserveResources(inputs, invitationIdentifier) {
2710
+ const outpoints = [];
2711
+ for (const input of inputs) {
2712
+ if (!input.outpointTransactionHash || input.outpointIndex === void 0) throw new InvalidInputError();
2713
+ outpoints.push({
2714
+ outpointTransactionHash: binToHex(input.outpointTransactionHash),
2715
+ outpointIndex: input.outpointIndex
2716
+ });
2717
+ }
2718
+ await this.state.executeBulkUnspentOutputReservation(outpoints, true, invitationIdentifier);
2719
+ }
2720
+ };
2721
+
2722
+ //#endregion
2723
+ export { ActionNotFoundError, BlockchainMonitor, CashAssemblyCompilationFailedError, CircularMergeReferenceError, CommitEntityIdentifierNotFoundError, CommitNotFoundInInvitationError, CommitNotSignedError, CreatedByIdentifierAlreadySetError, CreatedByIdentifierSignatureAlreadySetError, DataNotFoundError, DuplicateTransactionIndexError, DuplicateTransactionLocktimeError, DuplicateTransactionVersionError, ElectrumClientNotFoundError, Engine, InvalidActionError, InvalidCommitSignaturesError, InvalidDataTypeError, InvalidDerivativeIndexTypeError, InvalidEntityIdentifierError, InvalidInputError, InvalidInvitationError, InvalidLockingScriptTypeError, InvalidLockingTypeError, InvalidRequirementsError, InvalidRoleError, InvalidTemplateOutputSatoshisTypeError, InvalidVariableDefinitionError, InvalidVariableTypeError, InvitationAlreadyAcceptedError, InvitationBuilder, InvitationCreatedInFutureError, InvitationExpiredError, InvitationNotAcceptedError, InvitationNotFoundInStoreError, ItemNotFoundInCommitError, LockingBytecodeGenerationFailedError, LockingBytecodeNotFoundForOutputError, LockingDataNotFoundError, LockingScriptNotFoundError, LockingScriptTypeNotFoundError, LockscriptNotFoundError, MergedCommitNotFoundError, MergesWithCommitNotFoundError, MissingRequiredDataError, MissingRequiredFieldError, MissingRequiredRoleForEntityError, MissingRequiredSignatureByEntityError, MissingRequiredVariableError, MultipleRolesForStartingActionError, NoRoleSpecifiedAndMultipleRolesAvailableToBeAcceptedError, OutputLockscriptNotFoundError, OutputNotFoundError, ParentCommitNotFoundError, ReserveResourcesFailedError, RoleAlreadyAcceptedByAnotherEntityError, RoleCannotStartActionError, RoleNotAvailableToBeAcceptedError, RoleNotDefinedForActionError, RoleNotFoundError, RootCommitNotFoundError, ScriptHashDataNotFoundError, ScriptNotFoundError, SignatureVerificationFailedError, StartingActionNotFoundError, Template, TemplateIdentifierMismatchError, TemplateNotFoundError, TransactionGenerationFailedError, TransactionNotFoundError, UnknownVariableError, UnlockingScriptNotFoundError, UnspentOutputNotFoundError, VariableRequiredError, VariableValidationFailedError, assignTypeToVariablesForLibauthCompiler, compileCashAssemblyEvaluations, compileCashAssemblyString, convertCommitVariablesIntoObject, convertXOLockingTypeToLibauth, createLibauthCompilerDataFromUnspentOutput, entityOwnershipForLibauthCompiler, extractCashAssemblyEvaluations, extractVariablesFromEvaluations, findRootCommitIdentifierInInvitation, generateCashAssemblyBytecode, generateCommitIdentifier, generateTemplateIdentifier, hasInvitationExpired, isCashAsmExpression, listAvailableRolesForInvitation, listMissingRequirements, listPopulatedRequirementsInInvitation, listRequirementsFromTemplate, mergeInvitationCommits, parseTemplate, scriptsForLibauthCompiler, updateUnspentOutputsForScriptHashInStore, validateInvitationCommits, validateInvitationEntities, validateRoleRequirements };
2724
+ //# sourceMappingURL=index.mjs.map