smartledger-bsv 3.3.3 โ†’ 3.3.5

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/CHANGELOG.md +50 -28
  2. package/README.md +55 -36
  3. package/bsv-covenant.min.js +6 -6
  4. package/bsv-gdaf.min.js +6 -6
  5. package/bsv-ltp.min.js +6 -6
  6. package/bsv-mnemonic.min.js +4 -4
  7. package/bsv-smartcontract.min.js +5 -5
  8. package/bsv.bundle.js +5 -5
  9. package/bsv.min.js +5 -5
  10. package/demos/README.md +188 -0
  11. package/demos/architecture_demo.js +247 -0
  12. package/demos/browser-test.html +1208 -0
  13. package/demos/bsv_wallet_demo.js +242 -0
  14. package/demos/complete_ltp_demo.js +511 -0
  15. package/demos/debug_tools_demo.js +87 -0
  16. package/demos/demo_features.js +123 -0
  17. package/demos/easy_interface_demo.js +109 -0
  18. package/demos/ecies_demo.js +182 -0
  19. package/demos/gdaf_core_test.js +131 -0
  20. package/demos/gdaf_demo.js +237 -0
  21. package/demos/ltp_demo.js +361 -0
  22. package/demos/ltp_primitives_demo.js +403 -0
  23. package/demos/message_demo.js +209 -0
  24. package/demos/preimage_separation_demo.js +383 -0
  25. package/demos/script_helper_demo.js +289 -0
  26. package/demos/security_demo.js +287 -0
  27. package/demos/shamir_demo.js +121 -0
  28. package/demos/simple_demo.js +204 -0
  29. package/demos/simple_p2pkh_demo.js +169 -0
  30. package/demos/simple_utxo_preimage_demo.js +196 -0
  31. package/demos/smart_contract_demo.html +1347 -0
  32. package/demos/smart_contract_demo.js +910 -0
  33. package/demos/utxo_generator_demo.js +244 -0
  34. package/demos/validation_pipeline_demo.js +155 -0
  35. package/demos/web3keys.html +740 -0
  36. package/docs/BUNDLE_UPDATE_SUMMARY.md +40 -0
  37. package/docs/DOCUMENTATION_REVIEW_REPORT.md +11 -11
  38. package/docs/FIX_CREATEHMAC_ISSUE.md +91 -0
  39. package/docs/MODULE_REFERENCE_COMPLETE.md +28 -28
  40. package/docs/SMARTLEDGER_BSV_USAGE_ANSWERS.md +477 -0
  41. package/docs/SMARTLEDGER_BSV_USAGE_EXAMPLES.js +372 -0
  42. package/docs/SMARTLEDGER_BSV_USAGE_GUIDE.md +555 -0
  43. package/docs/SMART_CONTRACT_DEVELOPMENT_GUIDE.md +1459 -0
  44. package/docs/advanced/UTXO_MANAGER_GUIDE.md +2 -2
  45. package/docs/getting-started/INSTALLATION.md +25 -25
  46. package/docs/getting-started/QUICK_START.md +7 -7
  47. package/docs/migration/FROM_BSV_1_5_6.md +5 -5
  48. package/examples/complete_workflow_demo.js +783 -0
  49. package/examples/definitive_working_demo.js +261 -0
  50. package/examples/final_working_contracts.js +338 -0
  51. package/examples/smart_contract_templates.js +718 -0
  52. package/examples/working_smart_contracts.js +348 -0
  53. package/index.js +7 -0
  54. package/lib/browser-utxo-manager-es5.js +316 -0
  55. package/lib/browser-utxo-manager.js +533 -0
  56. package/lib/mnemonic/pbkdf2.browser.js +69 -0
  57. package/lib/mnemonic/pbkdf2.js +2 -68
  58. package/lib/mnemonic/pbkdf2.node.js +68 -0
  59. package/package.json +19 -8
  60. package/tests/browser-compatibility/README.md +35 -0
  61. package/tests/browser-compatibility/test-cdn-vs-local.html +186 -0
  62. package/tests/browser-compatibility/test-pbkdf2.html +51 -0
@@ -0,0 +1,372 @@
1
+ /**
2
+ * SmartLedger-BSV Usage Examples
3
+ * ==============================
4
+ *
5
+ * Practical examples demonstrating solutions to common usage questions
6
+ * Based on smartledger-bsv v3.3.4 analysis
7
+ */
8
+
9
+ const bsv = require('../index');
10
+
11
+ /**
12
+ * Example 1: Complete Field Name Reference
13
+ * Shows all working vs non-working field names
14
+ */
15
+ function demonstrateFieldNames() {
16
+ console.log('๐Ÿงช Example 1: Field Name Compatibility\n');
17
+
18
+ // Create example preimage
19
+ const example = bsv.SmartContract.Preimage.createExample();
20
+ const preimageHex = example.preimage.toString('hex');
21
+
22
+ console.log('โœ… WORKING field names for testFieldExtraction():');
23
+ const workingFields = [
24
+ 'nVersion', // NOT 'version'
25
+ 'hashPrevouts', // โœ… Same name
26
+ 'hashSequence', // โœ… Same name
27
+ 'outpoint_txid', // NOT 'outpoint' (split into two)
28
+ 'outpoint_vout',
29
+ 'scriptCode', // โœ… Same name
30
+ 'scriptLen', // CompactSize varint
31
+ 'value', // NOT 'amount'
32
+ 'nSequence', // NOT 'sequence'
33
+ 'hashOutputs', // โœ… Same name
34
+ 'nLocktime', // NOT 'locktime'
35
+ 'sighashType' // NOT 'sighash'
36
+ ];
37
+
38
+ workingFields.forEach(fieldName => {
39
+ try {
40
+ const result = bsv.SmartContract.testFieldExtraction(preimageHex, fieldName);
41
+ console.log(` โœ… ${fieldName.padEnd(15)}: ${result.fieldExtraction.value.substring(0, 16)}...`);
42
+ } catch (error) {
43
+ console.log(` โŒ ${fieldName.padEnd(15)}: ${error.message}`);
44
+ }
45
+ });
46
+
47
+ console.log('\nโŒ NON-WORKING field names (use mapping instead):');
48
+ const nonWorkingFields = ['version', 'outpoint', 'amount', 'sequence', 'locktime', 'sighash'];
49
+
50
+ nonWorkingFields.forEach(fieldName => {
51
+ try {
52
+ bsv.SmartContract.testFieldExtraction(preimageHex, fieldName);
53
+ console.log(` โš ๏ธ ${fieldName} - unexpected success`);
54
+ } catch (error) {
55
+ console.log(` โŒ ${fieldName.padEnd(15)}: ${error.message}`);
56
+ }
57
+ });
58
+
59
+ console.log('\n๐Ÿ“ Field Name Mapping Reference:');
60
+ const mapping = {
61
+ 'version': 'nVersion',
62
+ 'outpoint': 'outpoint_txid + outpoint_vout',
63
+ 'amount': 'value',
64
+ 'sequence': 'nSequence',
65
+ 'locktime': 'nLocktime',
66
+ 'sighash': 'sighashType'
67
+ };
68
+
69
+ Object.entries(mapping).forEach(([old, correct]) => {
70
+ console.log(` ${old.padEnd(12)} โ†’ ${correct}`);
71
+ });
72
+
73
+ return { preimageHex, workingFields, nonWorkingFields, mapping };
74
+ }
75
+
76
+ /**
77
+ * Example 2: Working Custom Transaction Preimage
78
+ * Demonstrates how to avoid CompactSize errors
79
+ */
80
+ function demonstrateCustomTransaction() {
81
+ console.log('\n๐Ÿ—๏ธ Example 2: Working Custom Transaction\n');
82
+
83
+ try {
84
+ // Step 1: Create complete UTXO with proper script
85
+ const privateKey = new bsv.PrivateKey();
86
+ const address = privateKey.toAddress();
87
+ const script = bsv.Script.buildPublicKeyHashOut(address);
88
+
89
+ console.log('๐Ÿ“‹ Creating UTXO with complete structure...');
90
+ const utxo = {
91
+ txId: '1234567890abcdef'.repeat(4), // Valid 32-byte txId
92
+ outputIndex: 0,
93
+ address: address.toString(),
94
+ script: script.toString(), // โœ… CRITICAL: Valid script hex
95
+ satoshis: 100000
96
+ };
97
+
98
+ console.log(` โœ… UTXO created: ${utxo.satoshis} sats`);
99
+ console.log(` โœ… Address: ${address.toString()}`);
100
+ console.log(` โœ… Script: ${script.toString().substring(0, 20)}...`);
101
+
102
+ // Step 2: Create transaction with proper structure
103
+ console.log('\n๐Ÿ”จ Building transaction...');
104
+ const tx = new bsv.Transaction()
105
+ .from(utxo)
106
+ .to('1BitcoinEaterAddressDontSendf59kuE', 50000)
107
+ .change(address)
108
+ .sign(privateKey);
109
+
110
+ console.log(` โœ… Transaction created: ${tx.id}`);
111
+ console.log(` โœ… Inputs: ${tx.inputs.length}, Outputs: ${tx.outputs.length}`);
112
+
113
+ // Step 3: Generate preimage with FORKID (critical!)
114
+ console.log('\n๐Ÿงพ Generating preimage with FORKID...');
115
+ const sighashType = bsv.crypto.Signature.SIGHASH_ALL | bsv.crypto.Signature.SIGHASH_FORKID;
116
+ const preimageBuffer = bsv.Transaction.sighash.sighashPreimage(
117
+ tx, sighashType, 0, script, new bsv.crypto.BN(utxo.satoshis)
118
+ );
119
+
120
+ const preimageHex = preimageBuffer.toString('hex');
121
+ console.log(` โœ… Preimage generated: ${preimageBuffer.length} bytes`);
122
+ console.log(` โœ… Hex: ${preimageHex.substring(0, 60)}...`);
123
+
124
+ // Step 4: Test field extraction
125
+ console.log('\n๐Ÿ” Testing field extraction on custom preimage...');
126
+ const testFields = ['nVersion', 'value', 'sighashType'];
127
+
128
+ testFields.forEach(fieldName => {
129
+ try {
130
+ const result = bsv.SmartContract.testFieldExtraction(preimageHex, fieldName);
131
+ console.log(` โœ… ${fieldName}: ${result.fieldExtraction.interpretation?.description || 'extracted successfully'}`);
132
+ } catch (error) {
133
+ console.log(` โŒ ${fieldName}: ${error.message}`);
134
+ }
135
+ });
136
+
137
+ return { success: true, preimageHex, tx, utxo };
138
+
139
+ } catch (error) {
140
+ console.log(`โŒ Custom transaction failed: ${error.message}`);
141
+ return { success: false, error: error.message };
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Example 3: extractPreimage() vs testFieldExtraction()
147
+ * Shows when to use each method
148
+ */
149
+ function compareExtractionMethods() {
150
+ console.log('\n๐Ÿ”ฌ Example 3: Comparing Extraction Methods\n');
151
+
152
+ const example = bsv.SmartContract.Preimage.createExample();
153
+ const preimageHex = example.preimage.toString('hex');
154
+
155
+ console.log('๐Ÿ“Š Method 1: extractPreimage() - General purpose');
156
+ try {
157
+ const extracted = bsv.SmartContract.extractPreimage(preimageHex);
158
+ console.log(' Available fields:', Object.keys(extracted).join(', '));
159
+ console.log(` โœ… version: ${extracted.version.toString('hex')} (BIP-143 name)`);
160
+ console.log(` โœ… amount: ${extracted.amount.toString('hex')} (BIP-143 name)`);
161
+ console.log(' โ†’ Use for: data analysis, debugging, general field access');
162
+ } catch (error) {
163
+ console.log(` โŒ extractPreimage failed: ${error.message}`);
164
+ }
165
+
166
+ console.log('\n๐Ÿ› ๏ธ Method 2: testFieldExtraction() - ASM generation');
167
+ try {
168
+ const result1 = bsv.SmartContract.testFieldExtraction(preimageHex, 'nVersion');
169
+ const result2 = bsv.SmartContract.testFieldExtraction(preimageHex, 'value');
170
+
171
+ console.log(` โœ… nVersion: ${result1.fieldExtraction.value} (SmartLedger name)`);
172
+ console.log(` โœ… value: ${result2.fieldExtraction.value} (SmartLedger name)`);
173
+ console.log(' โ†’ Use for: covenant development, ASM generation, smart contracts');
174
+
175
+ console.log('\n๐Ÿ“œ Generated ASM for value extraction:');
176
+ console.log(result2.fieldExtraction.asmGenerated);
177
+
178
+ } catch (error) {
179
+ console.log(` โŒ testFieldExtraction failed: ${error.message}`);
180
+ }
181
+
182
+ console.log('\n๐ŸŽฏ Recommendation:');
183
+ console.log(' โ€ข Use extractPreimage() for data analysis and debugging');
184
+ console.log(' โ€ข Use testFieldExtraction() for covenant development and ASM generation');
185
+ console.log(' โ€ข Both are correct - just use appropriate field names!');
186
+
187
+ return { extracted: true };
188
+ }
189
+
190
+ /**
191
+ * Example 4: Robust Error Handling
192
+ * Production-ready error handling pattern
193
+ */
194
+ function demonstrateErrorHandling() {
195
+ console.log('\n๐Ÿ›ก๏ธ Example 4: Robust Error Handling\n');
196
+
197
+ const example = bsv.SmartContract.Preimage.createExample();
198
+ const preimageHex = example.preimage.toString('hex');
199
+
200
+ function robustExtraction(preimageHex, fieldName) {
201
+ console.log(`๐Ÿ” Attempting to extract: ${fieldName}`);
202
+
203
+ // Step 1: Try direct extraction
204
+ try {
205
+ const result = bsv.SmartContract.testFieldExtraction(preimageHex, fieldName);
206
+ if (result.success) {
207
+ console.log(` โœ… Direct extraction successful: ${result.fieldExtraction.value.substring(0, 16)}...`);
208
+ return { success: true, method: 'direct', value: result.fieldExtraction.value };
209
+ }
210
+ } catch (error) {
211
+ console.log(` โš ๏ธ Direct extraction failed: ${error.message}`);
212
+ }
213
+
214
+ // Step 2: Try field name mapping
215
+ const mapping = {
216
+ 'version': 'nVersion',
217
+ 'amount': 'value',
218
+ 'sequence': 'nSequence',
219
+ 'locktime': 'nLocktime',
220
+ 'sighash': 'sighashType'
221
+ };
222
+
223
+ const mappedField = mapping[fieldName];
224
+ if (mappedField) {
225
+ console.log(` ๐Ÿ”„ Trying field mapping: ${fieldName} โ†’ ${mappedField}`);
226
+ try {
227
+ const result = bsv.SmartContract.testFieldExtraction(preimageHex, mappedField);
228
+ if (result.success) {
229
+ console.log(` โœ… Mapped extraction successful: ${result.fieldExtraction.value.substring(0, 16)}...`);
230
+ return { success: true, method: 'mapped', originalField: fieldName, mappedField, value: result.fieldExtraction.value };
231
+ }
232
+ } catch (error) {
233
+ console.log(` โš ๏ธ Mapped extraction failed: ${error.message}`);
234
+ }
235
+ }
236
+
237
+ // Step 3: Fallback to extractPreimage
238
+ console.log(` ๐Ÿ†˜ Trying fallback extraction...`);
239
+ try {
240
+ const extracted = bsv.SmartContract.extractPreimage(preimageHex);
241
+ const value = extracted[fieldName] || extracted[mappedField];
242
+
243
+ if (value) {
244
+ console.log(` โœ… Fallback extraction successful: ${value.toString('hex').substring(0, 16)}...`);
245
+ return { success: true, method: 'fallback', value: value.toString('hex'), warning: 'No ASM generated' };
246
+ }
247
+ } catch (error) {
248
+ console.log(` โŒ Fallback extraction failed: ${error.message}`);
249
+ }
250
+
251
+ console.log(` โŒ All extraction methods failed for: ${fieldName}`);
252
+ return { success: false, field: fieldName, error: 'All methods exhausted' };
253
+ }
254
+
255
+ // Test with various field names
256
+ const testFields = ['version', 'nVersion', 'amount', 'value', 'invalid_field'];
257
+
258
+ testFields.forEach(field => {
259
+ const result = robustExtraction(preimageHex, field);
260
+ console.log(`Result: ${result.success ? 'โœ… Success' : 'โŒ Failed'} (${result.method || 'none'})\n`);
261
+ });
262
+
263
+ return { demonstrated: true };
264
+ }
265
+
266
+ /**
267
+ * Example 5: Complete Working Covenant
268
+ * Demonstrates real-world usage for smart contract development
269
+ */
270
+ function demonstrateCovenantUsage() {
271
+ console.log('\nโšก Example 5: Complete Covenant Development\n');
272
+
273
+ const example = bsv.SmartContract.Preimage.createExample();
274
+ const preimageHex = example.preimage.toString('hex');
275
+
276
+ console.log('๐Ÿ—๏ธ Building covenant that validates minimum amount...\n');
277
+
278
+ try {
279
+ // Extract value field for covenant logic
280
+ const valueResult = bsv.SmartContract.testFieldExtraction(preimageHex, 'value');
281
+
282
+ if (valueResult.success) {
283
+ const valueHex = valueResult.fieldExtraction.value;
284
+ const valueSats = parseInt(valueHex.match(/.{2}/g).reverse().join(''), 16);
285
+
286
+ console.log(`๐Ÿ“Š Extracted value: ${valueSats} satoshis`);
287
+ console.log('๐Ÿ“œ Generated ASM for value extraction:');
288
+ console.log(valueResult.fieldExtraction.asmGenerated);
289
+
290
+ // Build covenant script
291
+ console.log('\n๐Ÿ”’ Building covenant script:');
292
+ const covenantScript = `
293
+ # Covenant: Minimum Amount Validator
294
+ ${valueResult.fieldExtraction.asmGenerated}
295
+
296
+ # Convert extracted value to number
297
+ OP_BIN2NUM
298
+
299
+ # Check minimum amount (50000 satoshis)
300
+ 50000
301
+ OP_GREATERTHANOREQUAL
302
+ OP_VERIFY
303
+
304
+ # If we get here, amount is valid
305
+ OP_TRUE
306
+ `.trim();
307
+
308
+ console.log(covenantScript);
309
+
310
+ console.log('\nโœ… Covenant successfully created!');
311
+ console.log(' โ€ข Extracts value field from preimage');
312
+ console.log(' โ€ข Validates minimum amount of 50,000 satoshis');
313
+ console.log(' โ€ข Uses generated ASM for field extraction');
314
+ console.log(' โ€ข Ready for smart contract deployment');
315
+
316
+ return {
317
+ success: true,
318
+ covenant: covenantScript,
319
+ extractedValue: valueSats,
320
+ asm: valueResult.fieldExtraction.asmGenerated
321
+ };
322
+ }
323
+ } catch (error) {
324
+ console.log(`โŒ Covenant development failed: ${error.message}`);
325
+ return { success: false, error: error.message };
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Main demonstration function
331
+ */
332
+ function runAllExamples() {
333
+ console.log('๐Ÿš€ SmartLedger-BSV v3.3.4 Usage Examples');
334
+ console.log('=' .repeat(50));
335
+
336
+ try {
337
+ demonstrateFieldNames();
338
+ demonstrateCustomTransaction();
339
+ compareExtractionMethods();
340
+ demonstrateErrorHandling();
341
+ demonstrateCovenantUsage();
342
+
343
+ console.log('\n๐ŸŽ‰ All examples completed successfully!');
344
+ console.log('\n๐Ÿ“š Key Takeaways:');
345
+ console.log(' 1. Use correct field names: nVersion, value, nSequence, nLocktime, sighashType');
346
+ console.log(' 2. For custom transactions: ensure proper UTXO structure and FORKID sighash');
347
+ console.log(' 3. For ASM generation: use testFieldExtraction()');
348
+ console.log(' 4. For data analysis: use extractPreimage()');
349
+ console.log(' 5. Always implement robust error handling with fallbacks');
350
+ console.log(' 6. Both naming conventions are valid - just use consistently');
351
+
352
+ console.log('\n๐Ÿ“– See docs/SMARTLEDGER_BSV_USAGE_GUIDE.md for complete documentation');
353
+
354
+ } catch (error) {
355
+ console.error('โŒ Example execution failed:', error.message);
356
+ }
357
+ }
358
+
359
+ // Export functions for individual testing
360
+ module.exports = {
361
+ demonstrateFieldNames,
362
+ demonstrateCustomTransaction,
363
+ compareExtractionMethods,
364
+ demonstrateErrorHandling,
365
+ demonstrateCovenantUsage,
366
+ runAllExamples
367
+ };
368
+
369
+ // Run examples if called directly
370
+ if (require.main === module) {
371
+ runAllExamples();
372
+ }