@bsv/wallet-toolbox 1.1.5 → 1.1.6

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.
Files changed (62) hide show
  1. package/docs/README.md +1 -1
  2. package/docs/client.md +698 -442
  3. package/docs/monitor.md +54 -37
  4. package/docs/services.md +53 -34
  5. package/docs/setup.md +295 -38
  6. package/docs/storage.md +115 -103
  7. package/docs/wallet.md +697 -442
  8. package/out/src/Setup.d.ts +3 -3
  9. package/out/src/Setup.js +5 -5
  10. package/out/src/SetupClient.d.ts +105 -12
  11. package/out/src/SetupClient.d.ts.map +1 -1
  12. package/out/src/SetupClient.js +3 -4
  13. package/out/src/SetupClient.js.map +1 -1
  14. package/out/src/Wallet.d.ts +4 -0
  15. package/out/src/Wallet.d.ts.map +1 -1
  16. package/out/src/Wallet.js +7 -0
  17. package/out/src/Wallet.js.map +1 -1
  18. package/out/src/sdk/WalletError.d.ts +0 -1
  19. package/out/src/sdk/WalletError.d.ts.map +1 -1
  20. package/out/src/sdk/WalletError.js +0 -1
  21. package/out/src/sdk/WalletError.js.map +1 -1
  22. package/out/src/sdk/validationHelpers.d.ts +1 -0
  23. package/out/src/sdk/validationHelpers.d.ts.map +1 -1
  24. package/out/src/sdk/validationHelpers.js +2 -1
  25. package/out/src/sdk/validationHelpers.js.map +1 -1
  26. package/out/src/storage/StorageProvider.d.ts +1 -4
  27. package/out/src/storage/StorageProvider.d.ts.map +1 -1
  28. package/out/src/storage/StorageProvider.js +1 -4
  29. package/out/src/storage/StorageProvider.js.map +1 -1
  30. package/out/src/storage/methods/createAction.d.ts.map +1 -1
  31. package/out/src/storage/methods/createAction.js +42 -11
  32. package/out/src/storage/methods/createAction.js.map +1 -1
  33. package/out/src/storage/methods/generateChange.js +1 -1
  34. package/out/src/storage/methods/generateChange.js.map +1 -1
  35. package/out/src/storage/schema/tables/ProvenTxReq.d.ts +4 -4
  36. package/out/test/examples/README.man.test.js +1 -1
  37. package/out/test/utils/TestUtilsWalletStorage.d.ts +2 -1
  38. package/out/test/utils/TestUtilsWalletStorage.d.ts.map +1 -1
  39. package/out/test/utils/TestUtilsWalletStorage.js +112 -27
  40. package/out/test/utils/TestUtilsWalletStorage.js.map +1 -1
  41. package/out/test/wallet/action/createAction.test.js +31 -5
  42. package/out/test/wallet/action/createAction.test.js.map +1 -1
  43. package/out/test/wallet/action/createAction2.test.d.ts +37 -0
  44. package/out/test/wallet/action/createAction2.test.d.ts.map +1 -0
  45. package/out/test/wallet/action/createAction2.test.js +1145 -0
  46. package/out/test/wallet/action/createAction2.test.js.map +1 -0
  47. package/out/tsconfig.all.tsbuildinfo +1 -1
  48. package/package.json +2 -2
  49. package/src/Setup.ts +5 -5
  50. package/src/SetupClient.ts +107 -15
  51. package/src/Wallet.ts +9 -0
  52. package/src/sdk/WalletError.ts +0 -1
  53. package/src/sdk/validationHelpers.ts +3 -1
  54. package/src/storage/StorageProvider.ts +1 -4
  55. package/src/storage/methods/createAction.ts +48 -12
  56. package/src/storage/methods/generateChange.ts +1 -1
  57. package/src/storage/schema/tables/ProvenTxReq.ts +4 -4
  58. package/test/examples/README.man.test.ts +1 -1
  59. package/test/utils/TestUtilsWalletStorage.ts +131 -35
  60. package/test/wallet/action/createAction.test.ts +36 -5
  61. package/test/wallet/action/createAction2.test.ts +1400 -0
  62. package/ts2md.json +6 -6
@@ -0,0 +1,1145 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isEmptyObject = void 0;
7
+ exports.toLogString = toLogString;
8
+ exports.createActionResultToTxLogString = createActionResultToTxLogString;
9
+ exports.txToLogString = txToLogString;
10
+ exports.numberArrayToHexString = numberArrayToHexString;
11
+ const chalk_1 = __importDefault(require("chalk"));
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const sdk_1 = require("@bsv/sdk");
15
+ const TestUtilsWalletStorage_1 = require("../../utils/TestUtilsWalletStorage");
16
+ const noLog = true;
17
+ const logFilePath = path_1.default.resolve(__dirname, 'createAction2.test.ts');
18
+ function sanitizeTestName(testName) {
19
+ const cleanTestName = testName.replace(/[^a-zA-Z0-9_]/g, '_');
20
+ return cleanTestName.startsWith('LOG_')
21
+ ? cleanTestName
22
+ : `LOG_${cleanTestName}`;
23
+ }
24
+ describe('createAction2 nosend transactions', () => {
25
+ jest.setTimeout(99999999);
26
+ let ctxs = [];
27
+ const env = TestUtilsWalletStorage_1._tu.getEnv('test');
28
+ const testName = () => { var _a; return (_a = expect.getState().currentTestName) !== null && _a !== void 0 ? _a : 'test'; };
29
+ beforeEach(async () => {
30
+ ctxs = [];
31
+ if (env.runMySQL) {
32
+ ctxs.push(await TestUtilsWalletStorage_1._tu.createLegacyWalletMySQLCopy(testName()));
33
+ }
34
+ ctxs.push(await TestUtilsWalletStorage_1._tu.createLegacyWalletSQLiteCopy(testName()));
35
+ });
36
+ afterEach(async () => {
37
+ for (const { wallet } of ctxs)
38
+ await wallet.destroy();
39
+ });
40
+ test('1_transaction with single output checked using toLogString', async () => {
41
+ for (const { wallet } of ctxs) {
42
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
43
+ const fundingLabel = 'funding transaction for createAction';
44
+ const fundingArgs = {
45
+ outputs: [
46
+ {
47
+ basket: 'funding basket',
48
+ tags: ['funding transaction output', 'test tag'],
49
+ satoshis: 3,
50
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
51
+ outputDescription: 'Funding Output'
52
+ }
53
+ ],
54
+ labels: [
55
+ fundingLabel,
56
+ 'this is an extra long test label that should be truncated at 80 chars when it is displayed'
57
+ ],
58
+ description: 'Funding transaction',
59
+ options: { noSend: true, randomizeOutputs: false }
60
+ };
61
+ const fundingResult = await wallet.createAction(fundingArgs);
62
+ expect(fundingResult.tx).toBeDefined();
63
+ const actionsResult = await wallet.listActions({
64
+ labels: [fundingLabel],
65
+ includeInputs: true,
66
+ includeOutputs: true,
67
+ includeInputSourceLockingScripts: true,
68
+ includeInputUnlockingScripts: true,
69
+ includeOutputLockingScripts: true,
70
+ includeLabels: true
71
+ });
72
+ const rl1 = toLogString(fundingResult.tx, actionsResult);
73
+ expect(rl1.log).toBe(`transactions:3
74
+ txid:30bdac0f5c6491f130820517802ff57e20e5a50c08b5c65e6976627fb82ae930 version:1 lockTime:0 sats:-4 status:nosend
75
+ outgoing:true desc:'Funding transaction' labels:['funding transaction for createaction','this is an extra long test
76
+ label that should be truncated at 80 chars when it is...']
77
+ inputs: 1
78
+ 0: sourceTXID:a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 sats:913
79
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
80
+ unlock:(214)483045022100cfef1f6d781af99a1de14efd6f24f2a14234a26097012f27121eb36f4e330c1d0220... seq:4294967295
81
+ outputs: 2
82
+ 0: sats:3 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true basket:'funding basket'
83
+ desc:'Funding Output' tags:['funding transaction output','test tag']
84
+ 1: sats:909 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`);
85
+ }
86
+ });
87
+ test('2_transaction with multiple outputs checked using toLogString', async () => {
88
+ for (const { wallet } of ctxs) {
89
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
90
+ const fundingLabel = 'funding transaction for createAction';
91
+ const fundingArgs = {
92
+ outputs: [
93
+ {
94
+ basket: 'funding basket',
95
+ tags: ['funding transaction for createAction', 'test tag'],
96
+ satoshis: 5,
97
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
98
+ outputDescription: 'Funding output'
99
+ },
100
+ {
101
+ basket: 'extra basket',
102
+ tags: ['extra transaction output', 'extra test tag'],
103
+ satoshis: 6,
104
+ lockingScript: '76a914fedcba9876543210fedcba9876543210fedcba88ac',
105
+ outputDescription: 'Extra Output'
106
+ }
107
+ ],
108
+ labels: [fundingLabel, 'this is the extra label'],
109
+ description: 'Funding transaction with multiple outputs',
110
+ options: { noSend: true, randomizeOutputs: false }
111
+ };
112
+ const fundingResult = await wallet.createAction(fundingArgs);
113
+ const actionsResult = await wallet.listActions({
114
+ labels: [fundingLabel],
115
+ includeInputs: true,
116
+ includeOutputs: true,
117
+ includeInputSourceLockingScripts: true,
118
+ includeInputUnlockingScripts: true,
119
+ includeOutputLockingScripts: true,
120
+ includeLabels: true
121
+ });
122
+ const rl1 = toLogString(fundingResult.tx, actionsResult);
123
+ expect(rl1.log).toBe(`transactions:3
124
+ txid:b3848f2cabf5887ec679ca60347a29f6ecad425fda738700265c2f9d22c18ab5 version:1 lockTime:0 sats:-12 status:nosend
125
+ outgoing:true desc:'Funding transaction with multiple outputs' labels:['funding transaction for createaction','this
126
+ is the extra label']
127
+ inputs: 1
128
+ 0: sourceTXID:a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 sats:913
129
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
130
+ unlock:(212)473044022079020cc8ea5ee6b3610806286e41567147d4b4b07d16bc1341311e00ce7647b0022034... seq:4294967295
131
+ outputs: 3
132
+ 0: sats:5 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true basket:'funding basket'
133
+ desc:'Funding output' tags:['funding transaction for createaction','test tag']
134
+ 1: sats:6 lock:(48)76a914fedcba9876543210fedcba9876543210fedcba88ac index:1 spendable:true basket:'extra basket'
135
+ desc:'Extra Output' tags:['extra transaction output','extra test tag']
136
+ 2: sats:901 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:2 spendable:true basket:'default'`);
137
+ }
138
+ });
139
+ test('3_transaction with explicit change check also uses toLogString on the spend', async () => {
140
+ var _a, _b, _c;
141
+ for (const { wallet } of ctxs) {
142
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
143
+ const fundingArgs = {
144
+ outputs: [
145
+ {
146
+ satoshis: 4,
147
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
148
+ outputDescription: 'Funding output'
149
+ }
150
+ ],
151
+ description: 'Funding transaction',
152
+ options: { noSend: true, randomizeOutputs: false }
153
+ };
154
+ const fundingResult = await wallet.createAction(fundingArgs);
155
+ expect(fundingResult.tx).toBeDefined();
156
+ expect(fundingResult.noSendChange).toBeDefined();
157
+ expect(fundingResult.noSendChange.length).toBe(1);
158
+ log(`noSendChange returned:${JSON.stringify(fundingResult.noSendChange, null, 2)}`);
159
+ const outputSatoshis = 2;
160
+ const estimatedFee = 1;
161
+ const fundingBeef = sdk_1.Beef.fromBinary(fundingResult.tx);
162
+ expect(fundingBeef).toBeDefined();
163
+ const spendingArgs = {
164
+ inputs: [
165
+ {
166
+ outpoint: `${fundingResult.txid}.0`,
167
+ unlockingScript: '47304402207f2e9a',
168
+ inputDescription: 'desc3'
169
+ }
170
+ ],
171
+ inputBEEF: fundingBeef.toBinary(),
172
+ outputs: [
173
+ {
174
+ satoshis: outputSatoshis,
175
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
176
+ outputDescription: 'First spending Output for check on change '
177
+ }
178
+ ],
179
+ labels: ['spending transaction test'],
180
+ description: 'Explicit check on returned change',
181
+ options: {
182
+ noSend: true,
183
+ randomizeOutputs: false,
184
+ noSendChange: []
185
+ }
186
+ };
187
+ const spendingResult = await wallet.createAction(spendingArgs);
188
+ expect(spendingResult.tx).toBeDefined();
189
+ log(`Spending transaction created:${JSON.stringify(spendingResult, null, 2)}`);
190
+ const spendingActionsResult = await wallet.listActions({
191
+ labels: ['spending transaction test'],
192
+ includeInputs: true,
193
+ includeOutputs: true,
194
+ includeInputSourceLockingScripts: true,
195
+ includeInputUnlockingScripts: true,
196
+ includeOutputLockingScripts: true,
197
+ includeLabels: true
198
+ });
199
+ const totalInputSatoshis = (_b = (_a = spendingActionsResult.actions[0]) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b.reduce((sum, input) => sum + input.sourceSatoshis, 0);
200
+ const expectedChange = totalInputSatoshis - outputSatoshis - estimatedFee;
201
+ const outputs = ((_c = spendingActionsResult.actions[0]) === null || _c === void 0 ? void 0 : _c.outputs) || [];
202
+ const changeOutput = outputs.find(output => output.basket === 'default');
203
+ expect(changeOutput.satoshis).toBe(expectedChange);
204
+ const actualFee = totalInputSatoshis - outputSatoshis - expectedChange;
205
+ expect(actualFee).toBe(estimatedFee);
206
+ const rl1 = toLogString(spendingResult.tx, spendingActionsResult);
207
+ expect(rl1.log).toBe(`transactions:5
208
+ txid:afa6713aab0957cf5bb00dee532ad7b895e919a99564ec2016b51cb3d472d87f version:1 lockTime:0 sats:1 status:nosend
209
+ outgoing:true desc:'Explicit check on returned change' labels:['spending transaction test']
210
+ inputs: 2
211
+ 0: sourceTXID:527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 sats:995
212
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
213
+ unlock:(214)483045022100973a84555fa864e08313bda5c88e1991094db7b8d82586c899276155dabcbc9a0220... seq:4294967295
214
+ 1: sourceTXID:70afdc54187a1cdb8e35f7d00e5e111cbf5c43c4dc3f1da2cc44479133c75f9e.0 sats:4 desc:'Funding output'
215
+ lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac unlock:(16)47304402207f2e9a seq:4294967295
216
+ outputs: 2
217
+ 0: sats:2 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true desc:'First spending
218
+ Output for check on change '
219
+ 1: sats:996 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`);
220
+ }
221
+ });
222
+ test('4_transaction with custom options knownTxids and returnTXIDOnly false uses toLogString', async () => {
223
+ for (const { wallet } of ctxs) {
224
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
225
+ const fundingOutputSatoshis = 4;
226
+ const fundingArgs = {
227
+ outputs: [
228
+ {
229
+ satoshis: fundingOutputSatoshis,
230
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
231
+ outputDescription: 'Funding output'
232
+ }
233
+ ],
234
+ description: 'Funding transaction',
235
+ options: { noSend: true, randomizeOutputs: false }
236
+ };
237
+ const fundingResult = await wallet.createAction(fundingArgs);
238
+ expect(fundingResult.tx).toBeDefined();
239
+ const spendingArgs = {
240
+ description: 'Check knownTxids and returnTXIDOnly',
241
+ outputs: [
242
+ {
243
+ satoshis: 4,
244
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
245
+ outputDescription: 'returnTXIDOnly false test'
246
+ }
247
+ ],
248
+ labels: ['custom options test'],
249
+ options: {
250
+ knownTxids: ['tx123', 'tx456'],
251
+ returnTXIDOnly: false,
252
+ noSend: true,
253
+ randomizeOutputs: false
254
+ }
255
+ };
256
+ const spendingResult = await wallet.createAction(spendingArgs);
257
+ expect(spendingArgs.options.knownTxids).toEqual(expect.arrayContaining(['tx123', 'tx456']));
258
+ const spendingActionsResult = await wallet.listActions({
259
+ labels: ['custom options test'],
260
+ includeInputs: true,
261
+ includeOutputs: true,
262
+ includeInputSourceLockingScripts: true,
263
+ includeInputUnlockingScripts: true,
264
+ includeOutputLockingScripts: true,
265
+ includeLabels: true
266
+ });
267
+ const rl1 = toLogString(spendingResult.tx, spendingActionsResult);
268
+ expect(rl1.log).toBe(`transactions:2
269
+ txid:38ded69627603b30bd1f55eb3f88098dbf74f2ef0ff5e3cfe6a34f97ce2db9c2 version:1 lockTime:0 sats:-5 status:nosend
270
+ outgoing:true desc:'Check knownTxids and returnTXIDOnly' labels:['custom options test']
271
+ inputs: 1
272
+ 0: sourceTXID:527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 sats:995
273
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
274
+ unlock:(212)4730440220113a6f72035a6ddcd6930db7e3f3d5c70486f9aaefb095e6fa3557afa916ec37022054... seq:4294967295
275
+ outputs: 2
276
+ 0: sats:4 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true desc:'returnTXIDOnly
277
+ false test'
278
+ 1: sats:990 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`);
279
+ }
280
+ });
281
+ test('5_transaction with custom options knownTxids and returnTXIDOnly true', async () => {
282
+ for (const { wallet } of ctxs) {
283
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
284
+ const fundingOutputSatoshis = 4;
285
+ const fundingArgs = {
286
+ outputs: [
287
+ {
288
+ satoshis: fundingOutputSatoshis,
289
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
290
+ outputDescription: 'Funding output'
291
+ }
292
+ ],
293
+ description: 'Funding transaction',
294
+ options: { noSend: true }
295
+ };
296
+ const fundingResult = await wallet.createAction(fundingArgs);
297
+ expect(fundingResult.tx).toBeDefined();
298
+ const spendingArgs = {
299
+ description: 'Check knownTxids and returnTXIDOnly',
300
+ outputs: [
301
+ {
302
+ satoshis: 4,
303
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
304
+ outputDescription: 'returnTXIDOnly true test'
305
+ }
306
+ ],
307
+ labels: ['custom options test'],
308
+ options: {
309
+ knownTxids: ['tx123', 'tx456'],
310
+ returnTXIDOnly: true,
311
+ noSend: true
312
+ }
313
+ };
314
+ const spendingResult = await wallet.createAction(spendingArgs);
315
+ expect(spendingResult.tx).not.toBeDefined();
316
+ expect(spendingArgs.options.knownTxids).toEqual(expect.arrayContaining(['tx123', 'tx456']));
317
+ }
318
+ });
319
+ test('6_transaction with custom options knownTxids check returned BeefParty txids', async () => {
320
+ var _a;
321
+ for (const { wallet } of ctxs) {
322
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
323
+ const fundingOutputSatoshis = 4;
324
+ const fundingArgs = {
325
+ outputs: [
326
+ {
327
+ satoshis: fundingOutputSatoshis,
328
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
329
+ outputDescription: 'Funding Output'
330
+ }
331
+ ],
332
+ description: 'Funding transaction',
333
+ options: { noSend: true }
334
+ };
335
+ const fundingResult = await wallet.createAction(fundingArgs);
336
+ expect(fundingResult.tx).toBeDefined();
337
+ const spendingArgs = {
338
+ description: 'Check knownTxids txids',
339
+ outputs: [
340
+ {
341
+ satoshis: 4,
342
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
343
+ outputDescription: 'Output for check txids'
344
+ }
345
+ ],
346
+ labels: ['custom options test'],
347
+ options: {
348
+ knownTxids: ['tx123', 'tx456'],
349
+ returnTXIDOnly: true,
350
+ noSend: true
351
+ }
352
+ };
353
+ const spendingResult = await wallet.createAction(spendingArgs);
354
+ expect(spendingResult).toBeDefined();
355
+ expect(spendingArgs.options.knownTxids).toEqual(expect.arrayContaining(['tx123', 'tx456']));
356
+ const fundingBeef = sdk_1.Beef.fromBinary(fundingResult.tx);
357
+ expect(fundingBeef).toBeDefined();
358
+ const BeefPartyTxids = fundingBeef.txs.map(tx => tx.txid);
359
+ const expectedTxids = ['tx123', 'tx456', ...BeefPartyTxids];
360
+ expect((_a = spendingArgs.options.knownTxids) === null || _a === void 0 ? void 0 : _a.sort()).toEqual(expectedTxids.sort());
361
+ }
362
+ });
363
+ test('7_transaction with custom options knownTxids check returned BeefParty txids with additional spend', async () => {
364
+ var _a, _b;
365
+ for (const { wallet } of ctxs) {
366
+ wallet.randomVals = [0.1, 0.2, 0.3, 0.7, 0.8, 0.9];
367
+ const fundingOutputSatoshis = 4;
368
+ const fundingArgs = {
369
+ outputs: [
370
+ {
371
+ satoshis: fundingOutputSatoshis,
372
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
373
+ outputDescription: 'Funding Output'
374
+ }
375
+ ],
376
+ description: 'Funding transaction',
377
+ options: { noSend: true }
378
+ };
379
+ const fundingResult = await wallet.createAction(fundingArgs);
380
+ expect(fundingResult.tx).toBeDefined();
381
+ const spendingArgs = {
382
+ description: 'Check knownTxids txids extra',
383
+ outputs: [
384
+ {
385
+ satoshis: 4,
386
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
387
+ outputDescription: 'Output for check txids extra'
388
+ }
389
+ ],
390
+ options: {
391
+ knownTxids: ['tx123', 'tx456'],
392
+ returnTXIDOnly: false,
393
+ noSend: true
394
+ }
395
+ };
396
+ const spendingResult = await wallet.createAction(spendingArgs);
397
+ expect(spendingResult).toBeDefined();
398
+ expect(spendingArgs.options.knownTxids).toEqual(expect.arrayContaining(['tx123', 'tx456']));
399
+ const fundingBeef = sdk_1.Beef.fromBinary(fundingResult.tx);
400
+ expect(fundingBeef).toBeDefined();
401
+ const partyBeefTxids = fundingBeef.txs.map(tx => tx.txid);
402
+ const expectedTxids = ['tx123', 'tx456', ...partyBeefTxids];
403
+ expect((_a = spendingArgs.options.knownTxids) === null || _a === void 0 ? void 0 : _a.sort()).toEqual(expectedTxids.sort());
404
+ const additionalSpendArgs = {
405
+ description: 'Extra spend transaction',
406
+ outputs: [
407
+ {
408
+ satoshis: 4,
409
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
410
+ outputDescription: 'Extra spend output'
411
+ }
412
+ ],
413
+ labels: ['extra spend test'],
414
+ options: {
415
+ knownTxids: spendingArgs.options.knownTxids,
416
+ returnTXIDOnly: true,
417
+ noSend: true
418
+ }
419
+ };
420
+ const additionalSpendResult = await wallet.createAction(additionalSpendArgs);
421
+ expect(additionalSpendResult).toBeDefined();
422
+ const finalBeef = sdk_1.Beef.fromBinary(spendingResult.tx);
423
+ expect(finalBeef).toBeDefined();
424
+ const finalPartyBeefTxids = finalBeef.txs.map(tx => tx.txid);
425
+ const finalExpectedTxids = [...expectedTxids, ...finalPartyBeefTxids];
426
+ expect((_b = additionalSpendArgs.options.knownTxids) === null || _b === void 0 ? void 0 : _b.sort()).toEqual(finalExpectedTxids.sort());
427
+ }
428
+ });
429
+ /* WIP
430
+
431
+ test('8_no-send transaction with zero satoshis output', async () => {
432
+ for (const { wallet, activeStorage: storage } of ctxs) {
433
+ const args: CreateActionArgs = {
434
+ outputs: [
435
+ {
436
+ satoshis: 0,
437
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
438
+ outputDescription: 'Invalid output'
439
+ }
440
+ ],
441
+ description: 'Valid transaction',
442
+ options: {
443
+ returnTXIDOnly: false,
444
+ randomizeOutputs: false,
445
+ noSend: true
446
+ }
447
+ }
448
+ const result: CreateActionResult = await wallet.createAction(args)
449
+ expect(result.tx).toBeDefined()
450
+ expect(result.signableTransaction).toBeUndefined()
451
+ }
452
+ })
453
+
454
+ test('9_no-send transaction without auth (should fail)', async () => {
455
+ for (const { wallet, activeStorage: storage } of ctxs) {
456
+ const args: CreateActionArgs = {
457
+ outputs: [
458
+ {
459
+ satoshis: 5,
460
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
461
+ outputDescription: 'Valid output'
462
+ }
463
+ ],
464
+ description: 'Valid transaction',
465
+ options: {
466
+ returnTXIDOnly: false,
467
+ randomizeOutputs: false,
468
+ noSend: true
469
+ }
470
+ }
471
+ await expect(wallet.createAction(args, undefined)).rejects.toThrow()
472
+ }
473
+ })
474
+
475
+ test('10_no-send transaction with malformed args (invalid destination)', async () => {
476
+ for (const { wallet, activeStorage: storage } of ctxs) {
477
+ const args: CreateActionArgs = {
478
+ outputs: [
479
+ {
480
+ satoshis: 6,
481
+ lockingScript: 'invalid_script',
482
+ outputDescription: 'Valid output'
483
+ }
484
+ ],
485
+ description: 'Valid transaction',
486
+ options: {
487
+ noSend: true
488
+ }
489
+ }
490
+ await expect(wallet.createAction(args)).rejects.toThrow()
491
+ }
492
+ })
493
+
494
+ test('11_transaction with OP_RETURN', async () => {
495
+ for (const { wallet, activeStorage: storage } of ctxs) {
496
+ const args: CreateActionArgs = {
497
+ outputs: [
498
+ {
499
+ satoshis: 0,
500
+ lockingScript: '6a0c48656c6c6f20576f726c64',
501
+ outputDescription: 'OP_RETURN data'
502
+ }
503
+ ],
504
+ description: 'Transaction embedding OP_RETURN data',
505
+ options: { noSend: true }
506
+ }
507
+ const result: CreateActionResult = await wallet.createAction(args)
508
+ expect(result.tx).toBeDefined()
509
+ expect(result.signableTransaction).toBeUndefined()
510
+ }
511
+ })
512
+
513
+ test('12_high fee transaction', async () => {
514
+ for (const { wallet, activeStorage: storage } of ctxs) {
515
+ const args: CreateActionArgs = {
516
+ inputs: [
517
+ {
518
+ outpoint: 'tx4.0',
519
+ unlockingScript: '47304402207f2e9a',
520
+ inputDescription: 'desc4'
521
+ }
522
+ ],
523
+ outputs: [
524
+ {
525
+ satoshis: 950,
526
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
527
+ outputDescription: 'Output D'
528
+ }
529
+ ],
530
+ description:
531
+ 'Transaction that results in high fees (insufficient change)',
532
+ options: { noSend: true }
533
+ }
534
+ await expect(wallet.createAction(args)).rejects.toThrow(
535
+ /WERR_INSUFFICIENT_FUNDS/
536
+ )
537
+ }
538
+ })
539
+
540
+ test('13_zero fee transaction', async () => {
541
+ for (const { wallet, activeStorage: storage } of ctxs) {
542
+ const args: CreateActionArgs = {
543
+ inputs: [
544
+ {
545
+ outpoint: 'tx5.0',
546
+ unlockingScript: '47304402207f2e9a',
547
+ inputDescription: 'desc5'
548
+ }
549
+ ],
550
+ outputs: [
551
+ {
552
+ satoshis: 500,
553
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
554
+ outputDescription: 'Output E'
555
+ }
556
+ ],
557
+ description: 'Zero-fee transaction attempt',
558
+ options: { noSend: true }
559
+ }
560
+ await expect(wallet.createAction(args)).rejects.toThrow(
561
+ /WERR_INSUFFICIENT_FUNDS/
562
+ )
563
+ }
564
+ })
565
+
566
+ test('14_dust transaction', async () => {
567
+ for (const { wallet, activeStorage: storage } of ctxs) {
568
+ const args: CreateActionArgs = {
569
+ outputs: [
570
+ {
571
+ satoshis: 1,
572
+ lockingScript: '76a914abcdef0123456789abcdef0123456789abcdef88ac',
573
+ outputDescription: 'Dust output'
574
+ }
575
+ ],
576
+ description: 'Transaction with dust output',
577
+ options: { noSend: true }
578
+ }
579
+ await expect(wallet.createAction(args)).rejects.toThrow(
580
+ /WERR_INVALID_PARAMETER/
581
+ )
582
+ }
583
+ })
584
+ */
585
+ });
586
+ // Helper functions
587
+ function getExpectedLog(testName, logFilePath) {
588
+ if (!fs_1.default.existsSync(logFilePath)) {
589
+ return null;
590
+ }
591
+ const fileContent = fs_1.default.readFileSync(logFilePath, 'utf8');
592
+ const sanitizedTestName = sanitizeTestName(testName);
593
+ // Use regex to extract the correct log constant
594
+ const logRegex = new RegExp(`const\\s+${sanitizedTestName}\\s*=\\s*\\{\\s*log:\\s*['\`]([\\s\\S]*?)['\`]\\s*,\\s*logColor:\\s*['\`]([\\s\\S]*?)['\`]\\s*\\}`, 'm');
595
+ const match = fileContent.match(logRegex);
596
+ if (match) {
597
+ return { log: match[1], logColor: match[2] };
598
+ }
599
+ return null;
600
+ }
601
+ const normalizeVariableParts = (log) => {
602
+ return log
603
+ .replace(/txid:[a-f0-9]{64}/g, 'txid:PLACEHOLDER') // Replace txids
604
+ .replace(/unlock:\(\d+\)(?:483045022100[a-f0-9]{64}0220|[a-f0-9]+)/g, 'unlock:PLACEHOLDER')
605
+ .replace(/lock:\(\d+\)76a914[a-f0-9]{40}/g, 'lock:PLACEHOLDER') // Replace locking script
606
+ .replace(/index:\d+ spendable:/g, 'index:PLACEHOLDER spendable:') // Normalize index
607
+ .trim();
608
+ };
609
+ /**
610
+ * Appends logs as a constant to a test file.
611
+ * @param {string} testName - The name of the test.
612
+ * @param {{ log: string; logColor: string }} rl - The log data.
613
+ */
614
+ function appendLogsAsConst(testName, rl) {
615
+ const normalizedTestName = testName
616
+ .replace(/[^a-zA-Z0-9_ ]/g, '')
617
+ .trim()
618
+ .replace(/\s+/g, '_');
619
+ const sanitizedTestName = sanitizeTestName(normalizedTestName);
620
+ const logFilePath = path_1.default.resolve(__dirname, 'createAction2.man.test.ts');
621
+ const logConst = `
622
+ // Auto-generated test log - ${new Date().toISOString()}
623
+ const ${sanitizedTestName} = {
624
+ log: \`${rl.log}\`,
625
+ logColor: \`${rl.logColor}\`
626
+ };
627
+ `.trim();
628
+ fs_1.default.appendFileSync(logFilePath, `\n${logConst}\n`, 'utf8');
629
+ }
630
+ /**
631
+ * Truncates a string to a maximum length of 80 characters.
632
+ * @param {string} s - The string to truncate.
633
+ * @returns {string} - The truncated string.
634
+ */ const truncate = (s) => (s.length > 80 ? s.slice(0, 80) + '...' : s);
635
+ /**
636
+ * Formats an optional field if it has a defined value.
637
+ * @param {string} fieldName - The name of the field.
638
+ * @param {any} value - The value of the field.
639
+ * @returns {string} - The formatted field string.
640
+ */
641
+ const formatOptionalField = (fieldName, value) => value !== undefined && value !== null && value !== ''
642
+ ? ` ${fieldName}:${value}`
643
+ : '';
644
+ /**
645
+ * Formats an optional field with quotes if it has a defined value.
646
+ * @param {string} fieldName - The name of the field.
647
+ * @param {any} value - The value of the field.
648
+ * @returns {string} - The formatted field string with quotes.
649
+ */
650
+ const formatOptionalFieldWithQuotes = (fieldName, value) => value !== undefined && value !== null && value !== ''
651
+ ? ` ${fieldName}:'${value}'`
652
+ : '';
653
+ /**
654
+ * Formats an optional field with color if it has a defined value.
655
+ * @param {string} fieldName - The name of the field.
656
+ * @param {any} value - The value of the field.
657
+ * @param {(val: string) => string} colorFunc - The function to apply color formatting.
658
+ * @returns {string} - The formatted field string with color.
659
+ */
660
+ const formatOptionalFieldWithColor = (fieldName, value, colorFunc) => value !== undefined && value !== null && value !== ''
661
+ ? ` ${chalk_1.default.gray(fieldName + ':')}${colorFunc(typeof value === 'string' ? value : String(value))}`
662
+ : '';
663
+ /**
664
+ * Formats metadata if present.
665
+ * @param {any} metadata - The metadata object.
666
+ * @returns {string} - The formatted metadata string.
667
+ */
668
+ const formatMetadata = (metadata) => metadata && !(0, exports.isEmptyObject)(metadata)
669
+ ? `metadata:${JSON.stringify(metadata)}`
670
+ : '';
671
+ /**
672
+ * Formats the Merkle path if present.
673
+ * @param {MerklePath | string} [merklePath] - The Merkle path.
674
+ * @returns {string} - The formatted Merkle path string.
675
+ */
676
+ const formatMerklePath = (merklePath) => merklePath ? `merklePath:${String(merklePath)}` : '';
677
+ const MAX_LOG_LINE_LENGTH = 120; // Define in the test
678
+ /**
679
+ * Wraps a log line to a specified max length.
680
+ * @param {string} text - The text to wrap.
681
+ * @param {number} indent - The indentation level.
682
+ * @param {number} [maxLength=120] - The maximum length of a line.
683
+ * @returns {string} - The wrapped log line.
684
+ */
685
+ const wrapLogLine = (text, indent, maxLength = 120) => {
686
+ const words = text.trim().split(' ');
687
+ let wrappedText = ' '.repeat(indent);
688
+ let currentLineLength = indent * 2;
689
+ for (const word of words) {
690
+ if (currentLineLength + word.length + 1 > maxLength) {
691
+ wrappedText += '\n' + ' '.repeat(indent) + ' ' + word + ' ';
692
+ currentLineLength = indent * 2 + word.length + 1;
693
+ }
694
+ else {
695
+ wrappedText += word + ' ';
696
+ currentLineLength += word.length + 1;
697
+ }
698
+ }
699
+ return wrappedText.trimEnd();
700
+ };
701
+ /**
702
+ * Formats an indented line.
703
+ * @param {number} indent - The indentation level.
704
+ * @param {string} content - The content of the line.
705
+ * @returns {string} - The formatted indented line.
706
+ */
707
+ const formatIndentedLineWithWrap = (indent, content, maxLength = 120) => wrapLogLine(content.trim(), indent, maxLength);
708
+ /**
709
+ * Formats a list of wallet action inputs for logging.
710
+ * @param {WalletActionInput[]} [inputs] - The list of wallet action inputs.
711
+ * @returns {{ log: string; logColor: string }[]} - An array of formatted log strings and their colorized versions.
712
+ */
713
+ const formatInputs = (inputs) => inputs && inputs.length > 0
714
+ ? inputs
715
+ .sort((a, b) => a.sourceOutpoint.localeCompare(b.sourceOutpoint))
716
+ .map((input, i) => {
717
+ let line = `${i}: sourceTXID:${input.sourceOutpoint} sats:${input.sourceSatoshis}`;
718
+ let color = `${chalk_1.default.gray(`${i}:`)} ${chalk_1.default.blue(input.sourceOutpoint)} ${chalk_1.default.green(`${input.sourceSatoshis} sats`)}`;
719
+ line += formatOptionalFieldWithQuotes('desc', input.inputDescription);
720
+ color += formatOptionalFieldWithColor('desc', input.inputDescription, chalk_1.default.white);
721
+ if (input.sourceLockingScript) {
722
+ line += ` lock:(${input.sourceLockingScript.length})${truncate(input.sourceLockingScript)}`;
723
+ color += ` ${chalk_1.default.gray('lock:')}(${input.sourceLockingScript.length})${chalk_1.default.cyan(truncate(input.sourceLockingScript))}`;
724
+ }
725
+ if (input.unlockingScript) {
726
+ line += ` unlock:(${input.unlockingScript.length})${truncate(input.unlockingScript)}`;
727
+ color += ` ${chalk_1.default.gray('unlock:')}(${input.unlockingScript.length})${chalk_1.default.cyan(truncate(input.unlockingScript))}`;
728
+ }
729
+ line += ` seq:${input.sequenceNumber}`;
730
+ color += ` ${chalk_1.default.gray('seq:')}${input.sequenceNumber}`;
731
+ return {
732
+ log: formatIndentedLineWithWrap(2, line),
733
+ logColor: formatIndentedLineWithWrap(2, color)
734
+ };
735
+ })
736
+ : [
737
+ {
738
+ log: formatIndentedLineWithWrap(2, 'No inputs'),
739
+ logColor: formatIndentedLineWithWrap(2, chalk_1.default.gray('No inputs'))
740
+ }
741
+ ];
742
+ /**
743
+ * Formats a list of wallet action outputs for logging.
744
+ * @param {WalletActionOutput[]} [outputs] - The list of wallet action outputs.
745
+ * @returns {{ log: string; logColor: string }[]} - An array of formatted log strings and their colorized versions.
746
+ */
747
+ const formatOutputs = (outputs) => outputs && outputs.length > 0
748
+ ? outputs
749
+ .sort((a, b) => a.satoshis - b.satoshis)
750
+ .map((output, i) => {
751
+ var _a, _b, _c, _d, _e;
752
+ let line = `${i}: sats:${output.satoshis} lock:(${((_a = output.lockingScript) === null || _a === void 0 ? void 0 : _a.length) || ''})${(_b = truncate(output.lockingScript)) !== null && _b !== void 0 ? _b : 'N/A'}`;
753
+ let color = `${chalk_1.default.gray(`${i}:`)} ${chalk_1.default.green(`${output.satoshis} sats`)} ${chalk_1.default.gray('lock:')}(${((_c = output.lockingScript) === null || _c === void 0 ? void 0 : _c.length) || ''})${chalk_1.default.cyan((_d = truncate(output.lockingScript)) !== null && _d !== void 0 ? _d : 'N/A')}`;
754
+ line += formatOptionalField('index', output.outputIndex);
755
+ color += formatOptionalFieldWithColor('index', output.outputIndex, chalk_1.default.white);
756
+ line += formatOptionalField('spendable', output.spendable);
757
+ color += formatOptionalFieldWithColor('spendable', output.spendable, chalk_1.default.white);
758
+ line += formatOptionalFieldWithQuotes('custinst', output.customInstructions);
759
+ color += formatOptionalFieldWithColor('custinst', output.customInstructions, chalk_1.default.white);
760
+ line += formatOptionalFieldWithQuotes('basket', output.basket);
761
+ color += formatOptionalFieldWithColor('basket', output.basket, chalk_1.default.white);
762
+ line += formatOptionalFieldWithQuotes('desc', output.outputDescription);
763
+ color += formatOptionalFieldWithColor('desc', output.outputDescription, chalk_1.default.white);
764
+ if ((_e = output.tags) === null || _e === void 0 ? void 0 : _e.length) {
765
+ const tagsString = `[${output.tags.map(tag => `'${truncate(tag)}'`).join(',')}]`;
766
+ line += ` tags:${tagsString}`;
767
+ color += ` ${chalk_1.default.gray('tags:')}${chalk_1.default.white(tagsString)}`;
768
+ }
769
+ return {
770
+ log: formatIndentedLineWithWrap(2, line),
771
+ logColor: formatIndentedLineWithWrap(2, color)
772
+ };
773
+ })
774
+ : [
775
+ {
776
+ log: formatIndentedLineWithWrap(2, 'No outputs'),
777
+ logColor: formatIndentedLineWithWrap(2, chalk_1.default.gray('No outputs'))
778
+ }
779
+ ];
780
+ /**
781
+ * Formats a list of labels into a string representation.
782
+ * @param {string[]} [labels] - The list of labels.
783
+ * @returns {string} - A formatted string of labels enclosed in brackets.
784
+ */
785
+ const formatLabels = (labels) => labels && labels.length > 0
786
+ ? `[${labels.map(label => `'${truncate(label)}'`).join(',')}]`
787
+ : '';
788
+ /**
789
+ * Generates a formatted log string from an AtomicBEEF object.
790
+ * @param {AtomicBEEF} atomicBeef - The AtomicBEEF object containing transaction data.
791
+ * @param {ListActionsResult} [actionsResult] - The result of listing actions, used for additional transaction metadata.
792
+ * @param {boolean} [showKey=true] - Whether to display key transaction details.
793
+ * @returns {Promise<{ log: string; logColor: string }>} - An object containing the formatted log string and a colorized version.
794
+ */
795
+ function toLogString(atomicBeef, actionsResult, showKey = true) {
796
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
797
+ const BEEF_V1 = 4022206465;
798
+ try {
799
+ const beef = sdk_1.Beef.fromBinary(atomicBeef);
800
+ beef.version = BEEF_V1;
801
+ let log = `transactions:${beef.txs.length}`;
802
+ let logColor = chalk_1.default.gray(`transactions:${beef.txs.length}`);
803
+ if (showKey) {
804
+ logColor += ` ${chalk_1.default.gray(`key:`)} (${chalk_1.default.blue('txid/outpoint')} ${chalk_1.default.cyan('script')} ${chalk_1.default.green('sats')})`;
805
+ }
806
+ const mainTxid = beef.txs.slice(-1)[0].txid;
807
+ const mainTx = beef.findAtomicTransaction(mainTxid);
808
+ const action = actionsResult === null || actionsResult === void 0 ? void 0 : actionsResult.actions.find(a => a.txid === mainTxid);
809
+ const labelString = formatLabels(action === null || action === void 0 ? void 0 : action.labels);
810
+ const metadataString = formatMetadata(mainTx.metadata);
811
+ const merklePathString = formatMerklePath(mainTx.merklePath);
812
+ log += `\n${formatIndentedLineWithWrap(1, `txid:${mainTxid} version:${mainTx.version} lockTime:${mainTx.lockTime}${formatOptionalField('sats', action === null || action === void 0 ? void 0 : action.satoshis)}${formatOptionalField('status', action === null || action === void 0 ? void 0 : action.status)}${formatOptionalField('outgoing', action === null || action === void 0 ? void 0 : action.isOutgoing)}${formatOptionalFieldWithQuotes('desc', action === null || action === void 0 ? void 0 : action.description)}${metadataString}${merklePathString} labels:${labelString}`)}`;
813
+ logColor += `\n${formatIndentedLineWithWrap(1, [
814
+ chalk_1.default.blue(mainTxid),
815
+ ` ${chalk_1.default.gray('version:')}${mainTx.version}`,
816
+ ` ${chalk_1.default.gray('lockTime:')}${mainTx.lockTime}`,
817
+ ` ${chalk_1.default.green(`${action === null || action === void 0 ? void 0 : action.satoshis} sats`)}`,
818
+ formatOptionalFieldWithColor('status', action === null || action === void 0 ? void 0 : action.status, chalk_1.default.white),
819
+ formatOptionalFieldWithColor('outgoing', action === null || action === void 0 ? void 0 : action.isOutgoing, chalk_1.default.white),
820
+ formatOptionalFieldWithColor('desc', action === null || action === void 0 ? void 0 : action.description, chalk_1.default.white),
821
+ metadataString ? chalk_1.default.gray(metadataString) : '',
822
+ merklePathString ? chalk_1.default.gray(merklePathString) : '',
823
+ ` ${chalk_1.default.gray('labels:')}${chalk_1.default.white(labelString)}`
824
+ ]
825
+ .filter(Boolean)
826
+ .join(''))}`;
827
+ log += `\n${formatIndentedLine(1, `inputs: ${(_b = (_a = action === null || action === void 0 ? void 0 : action.inputs) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`)}`;
828
+ logColor += `\n${formatIndentedLine(1, chalk_1.default.gray(`inputs: ${(_d = (_c = action === null || action === void 0 ? void 0 : action.inputs) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0}`))}`;
829
+ const sortedInputs = ((_e = action === null || action === void 0 ? void 0 : action.inputs) !== null && _e !== void 0 ? _e : []).sort((a, b) => a.sourceOutpoint.localeCompare(b.sourceOutpoint));
830
+ const formattedInputs = formatInputs(sortedInputs);
831
+ formattedInputs.forEach(({ log: inputLog, logColor: inputLogColor }) => {
832
+ log += `\n${formatIndentedLine(2, inputLog)}`;
833
+ logColor += `\n${formatIndentedLine(2, inputLogColor)}`;
834
+ });
835
+ log += `\n${formatIndentedLineWithWrap(1, `outputs: ${(_g = (_f = action === null || action === void 0 ? void 0 : action.outputs) === null || _f === void 0 ? void 0 : _f.length) !== null && _g !== void 0 ? _g : 0}`)}`;
836
+ logColor += `\n${formatIndentedLineWithWrap(1, chalk_1.default.gray(`outputs: ${(_j = (_h = action === null || action === void 0 ? void 0 : action.outputs) === null || _h === void 0 ? void 0 : _h.length) !== null && _j !== void 0 ? _j : 0}`))}`;
837
+ const sortedOutputs = (_k = action === null || action === void 0 ? void 0 : action.outputs) === null || _k === void 0 ? void 0 : _k.slice().sort((a, b) => a.satoshis - b.satoshis);
838
+ const formattedOutputs = formatOutputs(sortedOutputs);
839
+ formattedOutputs.forEach(({ log: outputLog, logColor: outputLogColor }) => {
840
+ log += `\n${formatIndentedLine(2, outputLog)}`;
841
+ logColor += `\n${formatIndentedLine(2, outputLogColor)}`;
842
+ });
843
+ return { log, logColor };
844
+ }
845
+ catch (error) {
846
+ return {
847
+ log: `Error parsing transaction: ${error.message}`,
848
+ logColor: chalk_1.default.red(`Error parsing transaction: ${error.message}`)
849
+ };
850
+ }
851
+ }
852
+ function createActionResultToTxLogString(createActionResult, actionsResult, showKey = false) {
853
+ const BEEF_V1 = 4022206465;
854
+ const beef = sdk_1.Beef.fromBinary(createActionResult === null || createActionResult === void 0 ? void 0 : createActionResult.tx);
855
+ beef.version = BEEF_V1;
856
+ const mainTxid = beef.txs.slice(-1)[0].txid;
857
+ return txToLogString(beef.findAtomicTransaction(mainTxid), 0, showKey, actionsResult);
858
+ }
859
+ const MAX_RECURSION_DEPTH = 3;
860
+ /**
861
+ * Truncates a TXID, replacing the middle 48 characters with '...'.
862
+ * @param {string} txid - The original transaction ID.
863
+ * @returns {string} - The truncated TXID.
864
+ */
865
+ const truncateTxid = (txid) => {
866
+ if (txid.length <= 64) {
867
+ return txid.slice(0, 8) + '...' + txid.slice(-8);
868
+ }
869
+ return txid;
870
+ };
871
+ /**
872
+ * Formats a list of transaction outputs for logging.
873
+ * @param {TransactionOutput[]} [outputs] - The list of transaction outputs.
874
+ * @param {number} indent - The current indentation level.
875
+ * @returns {{ log: string; logColor: string }[]} - A formatted log string array.
876
+ */
877
+ const formatTxOutputs = (outputs, indent) => outputs && outputs.length > 0
878
+ ? outputs
879
+ .sort((a, b) => a.satoshis - b.satoshis)
880
+ .map((output, i) => {
881
+ let line = formatIndentedLine(indent + 4, `${i}: lock:(${output.lockingScript.toHex().length || ''})${truncate(output.lockingScript.toHex())}`);
882
+ let color = formatIndentedLine(indent + 4, `${chalk_1.default.gray(`${i}:`)} ${chalk_1.default.gray('lock:')}(${output.lockingScript.toHex().length || ''})${chalk_1.default.cyan(truncate(output.lockingScript.toHex()))}`);
883
+ if (output.satoshis) {
884
+ line += ` sats:${output.satoshis}`;
885
+ color += ` ${chalk_1.default.green(`${output.satoshis} sats`)}`;
886
+ }
887
+ return { log: line, logColor: color };
888
+ })
889
+ : [
890
+ {
891
+ log: formatIndentedLine(indent + 4, 'No outputs'),
892
+ logColor: formatIndentedLine(indent + 4, chalk_1.default.gray('No outputs'))
893
+ }
894
+ ];
895
+ /**
896
+ * Formats transaction inputs with proper indentation.
897
+ * @param {TransactionInput[]} inputs - The list of transaction inputs.
898
+ * @param {number} indent - The current indentation level.
899
+ * @returns {{ log: string; logColor: string }[]} - A formatted log string array.
900
+ */
901
+ const formatTxInputs = (inputs, indent) => inputs && inputs.length > 0
902
+ ? inputs
903
+ .sort((a, b) => a.sourceTXID.localeCompare(b.sourceTXID))
904
+ .map((input, i) => {
905
+ let line = formatIndentedLine(indent + 4, `${i}: sourceTXID:${truncateTxid(input.sourceTXID)}.${input.sourceOutputIndex}`);
906
+ let color = formatIndentedLine(indent + 4, `${chalk_1.default.gray(`${i}:`)} ${chalk_1.default.blue(truncateTxid(input.sourceTXID))}.${chalk_1.default.blue(input.sourceOutputIndex)}`);
907
+ if (input.unlockingScript) {
908
+ line += `\n${formatIndentedLine(indent + 6, `unlock:(${input.unlockingScript.toHex().length})${truncate(input.unlockingScript.toHex())}`)}`;
909
+ color += `\n${formatIndentedLine(indent + 6, `${chalk_1.default.gray('unlock:')}(${input.unlockingScript.toHex().length})${chalk_1.default.cyan(truncate(input.unlockingScript.toHex()))}`)}`;
910
+ }
911
+ if (input.sequence) {
912
+ line += `\n${formatIndentedLine(indent + 6, `seq:${input.sequence}`)}`;
913
+ color += `\n${formatIndentedLine(indent + 6, `${chalk_1.default.gray('seq:')}${input.sequence}`)}`;
914
+ }
915
+ if (input.sourceTransaction) {
916
+ const { log: sourceTxLog, logColor: sourceTxLogColor } = txToLogString(input.sourceTransaction, indent + 6);
917
+ const sourceTxLogTrimed = sourceTxLog.replace(/\s+Transaction/, 'Transaction');
918
+ const sourceTxLogColorTrimed = sourceTxLogColor.replace(/\s+Transaction/, 'Transaction');
919
+ line += `\n${formatIndentedLine(indent + 6, `sourceTx:`)}${sourceTxLogTrimed}`;
920
+ color += `\n${formatIndentedLine(indent + 6, `${chalk_1.default.gray('sourceTx:')}`)}${sourceTxLogColorTrimed}`;
921
+ }
922
+ else {
923
+ line += `\n${formatIndentedLine(indent + 6, `sourceTx:Transaction [Max Depth Reached]`)}`;
924
+ color += `\n${formatIndentedLine(indent + 6, chalk_1.default.gray(`sourceTx:Transaction [Max Depth Reached]`))}`;
925
+ }
926
+ return { log: line, logColor: color };
927
+ })
928
+ : [
929
+ {
930
+ log: formatIndentedLine(indent + 4, 'No inputs'),
931
+ logColor: formatIndentedLine(indent + 4, chalk_1.default.gray('No inputs'))
932
+ }
933
+ ];
934
+ /**
935
+ * Generates a formatted log string from a Transaction object.
936
+ * Ensures proper indentation and prevents recursion errors.
937
+ * @param {Transaction} tx - The Transaction object containing transaction data.
938
+ * @param {number} indent - The current indentation level.
939
+ * @param {boolean} [showKey=true] - Whether to display key transaction details.
940
+ * @param {ListActionsResult} [actionsResult] - The result of listing actions.
941
+ * @returns {{ log: string; logColor: string }} - A formatted log string and colorized version.
942
+ */
943
+ function txToLogString(tx, indent = 0, showKey = false, actionsResult) {
944
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
945
+ try {
946
+ if (indent / 2 >= MAX_RECURSION_DEPTH) {
947
+ return {
948
+ log: formatIndentedLine(indent + 4, 'Transaction [Max Depth Reached]'),
949
+ logColor: chalk_1.default.gray(formatIndentedLine(indent + 4, 'Transaction [Max Depth Reached]'))
950
+ };
951
+ }
952
+ const beef = sdk_1.Beef.fromBinary(tx.toBEEF());
953
+ const mainTxid = beef.txs.slice(-1)[0].txid;
954
+ const metadataString = formatMetadata(tx.metadata);
955
+ const merklePathString = formatMerklePath(tx.merklePath);
956
+ let log = formatIndentedLine(indent, `Transaction:${truncateTxid(mainTxid)}`);
957
+ let logColor = formatIndentedLine(indent, `${chalk_1.default.gray('Transaction:')}${chalk_1.default.blue(truncateTxid(mainTxid))}`);
958
+ if (showKey) {
959
+ logColor += ` ${chalk_1.default.gray(`key:`)} (${chalk_1.default.blue('txid/outpoint')} ${chalk_1.default.cyan('script')} ${chalk_1.default.green('sats')})`;
960
+ }
961
+ log += `\n${formatIndentedLine(indent + 2, `version:${tx.version} lockTime:${tx.lockTime}${metadataString}${merklePathString}`)}`;
962
+ logColor += `\n${formatIndentedLine(indent + 2, `${chalk_1.default.gray('version:')}${chalk_1.default.white(tx.version)} ${chalk_1.default.gray('lockTime:')}${chalk_1.default.white(tx.lockTime)}` +
963
+ (metadataString ? chalk_1.default.gray(metadataString) : '') +
964
+ (merklePathString ? chalk_1.default.gray(merklePathString) : ''))}`;
965
+ log += `\n${formatIndentedLine(indent + 2, `inputs: ${(_b = (_a = tx === null || tx === void 0 ? void 0 : tx.inputs) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`)}`;
966
+ logColor += `\n${formatIndentedLine(indent + 2, chalk_1.default.gray(`inputs: ${(_d = (_c = tx === null || tx === void 0 ? void 0 : tx.inputs) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0}`))}`;
967
+ const sortedInputs = ((_e = tx === null || tx === void 0 ? void 0 : tx.inputs) !== null && _e !== void 0 ? _e : []).sort((a, b) => a.sourceTXID.localeCompare(b.sourceTXID));
968
+ const formattedInputs = formatTxInputs(sortedInputs, indent);
969
+ formattedInputs.forEach(({ log: inputLog, logColor: inputLogColor }) => {
970
+ log += `\n${inputLog}`;
971
+ logColor += `\n${inputLogColor}`;
972
+ });
973
+ log += `\n${formatIndentedLine(indent + 2, `outputs: ${(_g = (_f = tx === null || tx === void 0 ? void 0 : tx.outputs) === null || _f === void 0 ? void 0 : _f.length) !== null && _g !== void 0 ? _g : 0}`)}`;
974
+ logColor += `\n${formatIndentedLine(indent + 2, chalk_1.default.gray(`outputs: ${(_j = (_h = tx === null || tx === void 0 ? void 0 : tx.outputs) === null || _h === void 0 ? void 0 : _h.length) !== null && _j !== void 0 ? _j : 0}`))}`;
975
+ const sortedOutputs = (_k = tx === null || tx === void 0 ? void 0 : tx.outputs) === null || _k === void 0 ? void 0 : _k.slice().sort((a, b) => a.satoshis - b.satoshis);
976
+ const formattedTxOutputs = formatTxOutputs(sortedOutputs, indent);
977
+ formattedTxOutputs.forEach(({ log: outputLog, logColor: outputLogColor }) => {
978
+ log += `\n${outputLog}`;
979
+ logColor += `\n${outputLogColor}`;
980
+ });
981
+ return { log, logColor };
982
+ }
983
+ catch (error) {
984
+ return {
985
+ log: `Error parsing transaction: ${error.message}`,
986
+ logColor: chalk_1.default.red(`Error parsing transaction: ${error.message}`)
987
+ };
988
+ }
989
+ }
990
+ /**
991
+ * Checks if an object is empty.
992
+ * @param {unknown} obj - The object to check.
993
+ * @returns {boolean} - Returns true if the object is empty, otherwise false.
994
+ */
995
+ const isEmptyObject = (obj) => {
996
+ return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;
997
+ };
998
+ exports.isEmptyObject = isEmptyObject;
999
+ const formatIndentedLine = (indent, content) => ' '.repeat(indent * 2) + content.trim(); // Trim ensures no accidental double spacing
1000
+ function log(s) {
1001
+ if (!noLog)
1002
+ console.log(s);
1003
+ //if (!noLog) process.stdout.write(s)
1004
+ }
1005
+ function logWarn(s) {
1006
+ process.stdout.write(chalk_1.default.yellowBright(s));
1007
+ }
1008
+ function numberArrayToHexString(numbers) {
1009
+ return numbers.map(num => num.toString(16).padStart(2, '0')).join('');
1010
+ }
1011
+ /***Use these to generate the log string ***/
1012
+ //const testName = expect.getState().currentTestName ?? 'Unknown_Test'
1013
+ //appendLogsAsConst(testName, rl1)
1014
+ // Auto-generated test log - 2025-02-05T13:04:29.906Z
1015
+ const LOG_createAction_nosend_transactions_1_transaction_with_single_output_checked_using_toLogString = {
1016
+ log: `transactions:3
1017
+ txid:30bdac0f5c6491f130820517802ff57e20e5a50c08b5c65e6976627fb82ae930 version:1 lockTime:0 sats:-4 status:nosend
1018
+ outgoing:true desc:'Funding transaction' labels:['funding transaction for createaction','this is an extra long test
1019
+ label that should be truncated at 80 chars when it is...']
1020
+ inputs: 1
1021
+ 0: sourceTXID:a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 sats:913
1022
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
1023
+ unlock:(214)483045022100cfef1f6d781af99a1de14efd6f24f2a14234a26097012f27121eb36f4e330c1d0220... seq:4294967295
1024
+ outputs: 2
1025
+ 0: sats:3 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true basket:'funding basket'
1026
+ desc:'Funding Output' tags:['funding transaction output','test tag']
1027
+ 1: sats:909 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`,
1028
+ logColor: `transactions:3 key: (txid/outpoint script sats)
1029
+ 30bdac0f5c6491f130820517802ff57e20e5a50c08b5c65e6976627fb82ae930 version:1 lockTime:0
1030
+ -4 sats status:nosend outgoing:true desc:Funding
1031
+ transaction labels:['funding transaction for createaction','this is an extra long test label that
1032
+ should be truncated at 80 chars when it is...']
1033
+ inputs: 1
1034
+ 0: a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 913 sats
1035
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
1036
+ unlock:(214)483045022100cfef1f6d781af99a1de14efd6f24f2a14234a26097012f27121eb36f4e330c1d0220...
1037
+ seq:4294967295
1038
+ outputs: 2
1039
+ 0: 3 sats lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac
1040
+ index:0 spendable:true basket:funding basket
1041
+ desc:Funding Output tags:['funding transaction output','test tag']
1042
+ 1: 909 sats lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac
1043
+ index:1 spendable:true basket:default`
1044
+ };
1045
+ // Auto-generated test log - 2025-02-05T13:46:12.091Z
1046
+ const LOG_createAction_nosend_transactions_2_transaction_with_multiple_outputs_checked_using_toLogString = {
1047
+ log: `transactions:3
1048
+ txid:b3848f2cabf5887ec679ca60347a29f6ecad425fda738700265c2f9d22c18ab5 version:1 lockTime:0 sats:-12 status:nosend
1049
+ outgoing:true desc:'Funding transaction with multiple outputs' labels:['funding transaction for createaction','this
1050
+ is the extra label']
1051
+ inputs: 1
1052
+ 0: sourceTXID:a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 sats:913
1053
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
1054
+ unlock:(212)473044022079020cc8ea5ee6b3610806286e41567147d4b4b07d16bc1341311e00ce7647b0022034... seq:4294967295
1055
+ outputs: 3
1056
+ 0: sats:5 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true basket:'funding basket'
1057
+ desc:'Funding output' tags:['funding transaction for createaction','test tag']
1058
+ 1: sats:6 lock:(48)76a914fedcba9876543210fedcba9876543210fedcba88ac index:1 spendable:true basket:'extra basket'
1059
+ desc:'Extra Output' tags:['extra transaction output','extra test tag']
1060
+ 2: sats:901 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:2 spendable:true basket:'default'`,
1061
+ logColor: `transactions:3 key: (txid/outpoint script sats)
1062
+ b3848f2cabf5887ec679ca60347a29f6ecad425fda738700265c2f9d22c18ab5 version:1 lockTime:0
1063
+ -12 sats status:nosend outgoing:true desc:Funding
1064
+ transaction with multiple outputs labels:['funding transaction for createaction','this is the
1065
+ extra label']
1066
+ inputs: 1
1067
+ 0: a3a8fe7f541c1383ff7b975af49b27284ae720af5f2705d8409baaf519190d26.2 913 sats
1068
+ lock:(50)76a914f7238871139f4926cbd592a03a737981e558245d88ac
1069
+ unlock:(212)473044022079020cc8ea5ee6b3610806286e41567147d4b4b07d16bc1341311e00ce7647b0022034...
1070
+ seq:4294967295
1071
+ outputs: 3
1072
+ 0: 5 sats lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac
1073
+ index:0 spendable:true basket:funding basket
1074
+ desc:Funding output tags:['funding transaction for createaction','test
1075
+ tag']
1076
+ 1: 6 sats lock:(48)76a914fedcba9876543210fedcba9876543210fedcba88ac
1077
+ index:1 spendable:true basket:extra basket
1078
+ desc:Extra Output tags:['extra transaction output','extra test tag']
1079
+ 2: 901 sats lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac
1080
+ index:2 spendable:true basket:default`
1081
+ };
1082
+ // Auto-generated test log - 2025-02-05T14:50:57.843Z
1083
+ const LOG_createAction_nosend_transactions_3_transaction_with_explicit_change_check_also_uses_toLogString_on_the_spend = {
1084
+ log: `transactions:5
1085
+ txid:afa6713aab0957cf5bb00dee532ad7b895e919a99564ec2016b51cb3d472d87f version:1 lockTime:0 sats:1 status:nosend
1086
+ outgoing:true desc:'Explicit check on returned change' labels:['spending transaction test']
1087
+ inputs: 2
1088
+ 0: sourceTXID:527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 sats:995
1089
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
1090
+ unlock:(214)483045022100973a84555fa864e08313bda5c88e1991094db7b8d82586c899276155dabcbc9a0220... seq:4294967295
1091
+ 1: sourceTXID:70afdc54187a1cdb8e35f7d00e5e111cbf5c43c4dc3f1da2cc44479133c75f9e.0 sats:4 desc:'Funding output'
1092
+ lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac unlock:(16)47304402207f2e9a seq:4294967295
1093
+ outputs: 2
1094
+ 0: sats:2 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true desc:'First spending
1095
+ Output for check on change '
1096
+ 1: sats:996 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`,
1097
+ logColor: `transactions:5 key: (txid/outpoint script sats)
1098
+ afa6713aab0957cf5bb00dee532ad7b895e919a99564ec2016b51cb3d472d87f version:1 lockTime:0
1099
+ 1 sats status:nosend outgoing:true desc:Explicit
1100
+ check on returned change labels:['spending transaction test']
1101
+ inputs: 2
1102
+ 0: 527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 995 sats
1103
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
1104
+ unlock:(214)483045022100973a84555fa864e08313bda5c88e1991094db7b8d82586c899276155dabcbc9a0220...
1105
+ seq:4294967295
1106
+ 1: 70afdc54187a1cdb8e35f7d00e5e111cbf5c43c4dc3f1da2cc44479133c75f9e.0 4 sats
1107
+ desc:Funding output
1108
+ lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac
1109
+ unlock:(16)47304402207f2e9a seq:4294967295
1110
+ outputs: 2
1111
+ 0: 2 sats lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac
1112
+ index:0 spendable:true desc:First spending Output for check
1113
+ on change 
1114
+ 1: 996 sats lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac
1115
+ index:1 spendable:true basket:default`
1116
+ };
1117
+ // Auto-generated test log - 2025-02-05T15:22:24.388Z
1118
+ const LOG_createAction_nosend_transactions_4_transaction_with_custom_options_knownTxids_and_returnTXIDOnly_false_uses_toLogString = {
1119
+ log: `transactions:2
1120
+ txid:38ded69627603b30bd1f55eb3f88098dbf74f2ef0ff5e3cfe6a34f97ce2db9c2 version:1 lockTime:0 sats:-5 status:nosend
1121
+ outgoing:true desc:'Check knownTxids and returnTXIDOnly' labels:['custom options test']
1122
+ inputs: 1
1123
+ 0: sourceTXID:527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 sats:995
1124
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
1125
+ unlock:(212)4730440220113a6f72035a6ddcd6930db7e3f3d5c70486f9aaefb095e6fa3557afa916ec37022054... seq:4294967295
1126
+ outputs: 2
1127
+ 0: sats:4 lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac index:0 spendable:true desc:'returnTXIDOnly
1128
+ false test'
1129
+ 1: sats:990 lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac index:1 spendable:true basket:'default'`,
1130
+ logColor: `transactions:2 key: (txid/outpoint script sats)
1131
+ 38ded69627603b30bd1f55eb3f88098dbf74f2ef0ff5e3cfe6a34f97ce2db9c2 version:1 lockTime:0
1132
+ -5 sats status:nosend outgoing:true desc:Check
1133
+ knownTxids and returnTXIDOnly labels:['custom options test']
1134
+ inputs: 1
1135
+ 0: 527ffe88f70d5b7de2b8b5ba9966b9c755e7da4de749d4fcd27140a03145a11d.0 995 sats
1136
+ lock:(50)76a914ab2b66432503a3681fc5af1502207ca458c8752d88ac
1137
+ unlock:(212)4730440220113a6f72035a6ddcd6930db7e3f3d5c70486f9aaefb095e6fa3557afa916ec37022054...
1138
+ seq:4294967295
1139
+ outputs: 2
1140
+ 0: 4 sats lock:(48)76a914abcdef0123456789abcdef0123456789abcdef88ac
1141
+ index:0 spendable:true desc:returnTXIDOnly false test
1142
+ 1: 990 sats lock:(50)76a9145947e66cdd43c70fb1780116b79e6f7d96e30e0888ac
1143
+ index:1 spendable:true basket:default`
1144
+ };
1145
+ //# sourceMappingURL=createAction2.test.js.map