@smartledger/bsv 3.1.1 → 3.2.0

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 (67) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/README.md +233 -277
  3. package/bsv.bundle.js +39 -0
  4. package/bsv.min.js +8 -8
  5. package/docs/ADVANCED_COVENANT_DEVELOPMENT.md +533 -0
  6. package/docs/COVENANT_DEVELOPMENT_RESOLVED.md +169 -0
  7. package/docs/CUSTOM_SCRIPT_DEVELOPMENT.md +320 -0
  8. package/docs/README.md +201 -0
  9. package/docs/block.md +46 -0
  10. package/docs/ecies.md +102 -0
  11. package/docs/index.md +104 -0
  12. package/docs/nchain.md +958 -0
  13. package/docs/networks.md +55 -0
  14. package/docs/preimage.md +126 -0
  15. package/docs/script.md +139 -0
  16. package/docs/transaction.md +174 -0
  17. package/docs/unspentoutput.md +32 -0
  18. package/examples/README.md +200 -0
  19. package/examples/basic/transaction-creation.js +534 -0
  20. package/examples/basic/transaction_signature_api_gap.js +178 -0
  21. package/examples/covenants/advanced_covenant_demo.js +219 -0
  22. package/examples/covenants/covenant_interface_demo.js +270 -0
  23. package/examples/covenants/covenant_manual_signature_resolved.js +212 -0
  24. package/examples/covenants/covenant_signature_template.js +117 -0
  25. package/examples/covenants2/covenant_bidirectional_example.js +262 -0
  26. package/examples/covenants2/covenant_utils_demo.js +120 -0
  27. package/examples/covenants2/preimage_covenant_utils.js +287 -0
  28. package/examples/covenants2/production_integration.js +256 -0
  29. package/examples/data/covenant_utxos.json +28 -0
  30. package/examples/data/utxos.json +26 -0
  31. package/examples/preimage/README.md +178 -0
  32. package/examples/preimage/extract_preimage_bidirectional.js +421 -0
  33. package/examples/preimage/generate_sample_preimage.js +208 -0
  34. package/examples/preimage/generate_sighash_examples.js +152 -0
  35. package/examples/preimage/parse_preimage.js +117 -0
  36. package/examples/preimage/test_preimage_extractor.js +53 -0
  37. package/examples/preimage/test_varint_extraction.js +95 -0
  38. package/examples/scripts/custom_script_helper_example.js +273 -0
  39. package/examples/scripts/custom_script_signature_test.js +344 -0
  40. package/examples/scripts/script_interpreter.js +193 -0
  41. package/examples/smart_contract/complete_workflow_demo.js +343 -0
  42. package/examples/smart_contract/covenant_builder_demo.js +176 -0
  43. package/examples/smart_contract/script_testing_integration.js +198 -0
  44. package/index.js +3 -0
  45. package/lib/covenant-interface.js +713 -0
  46. package/lib/opcode.js +14 -7
  47. package/lib/smart_contract/API_REFERENCE.md +754 -0
  48. package/lib/smart_contract/DOCUMENTATION_SUMMARY.md +201 -0
  49. package/lib/smart_contract/EXAMPLES.md +751 -0
  50. package/lib/smart_contract/QUICK_START.md +549 -0
  51. package/lib/smart_contract/README.md +395 -0
  52. package/lib/smart_contract/builder.js +452 -0
  53. package/lib/smart_contract/covenant.js +336 -0
  54. package/lib/smart_contract/covenant_builder.js +512 -0
  55. package/lib/smart_contract/index.js +311 -0
  56. package/lib/smart_contract/opcode_list.js +30 -0
  57. package/lib/smart_contract/opcode_map.js +1174 -0
  58. package/lib/smart_contract/opcodes.md +1173 -0
  59. package/lib/smart_contract/preimage.js +903 -0
  60. package/lib/smart_contract/script_tester.js +487 -0
  61. package/lib/smart_contract/script_utils.js +609 -0
  62. package/lib/smart_contract/sighash.js +310 -0
  63. package/lib/smart_contract/smartledger-opcode_review.md +70 -0
  64. package/lib/smart_contract/test_integration.js +269 -0
  65. package/lib/smart_contract/utxo_generator.js +367 -0
  66. package/package.json +43 -10
  67. package/utilities/blockchain-state.json +20478 -3
@@ -0,0 +1,754 @@
1
+ # SmartContract API Reference
2
+
3
+ **SmartLedger-BSV v3.2.0** - Complete JavaScript-to-Bitcoin Script Framework
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Quick Start](#quick-start)
8
+ 2. [Core Classes](#core-classes)
9
+ 3. [Interface Functions (29 Total)](#interface-functions)
10
+ 4. [JavaScript-to-Script Framework](#javascript-to-script-framework)
11
+ 5. [CovenantBuilder API (61 Methods)](#covenantbuilder-api)
12
+ 6. [Opcode Mapping System](#opcode-mapping-system)
13
+ 7. [Real-World Examples](#real-world-examples)
14
+ 8. [Error Handling](#error-handling)
15
+
16
+ ---
17
+
18
+ ## Quick Start
19
+
20
+ ```javascript
21
+ const SmartContract = require('bsv-elliptic-fix').SmartContract
22
+
23
+ // 🚀 Write covenant logic in JavaScript
24
+ const builder = SmartContract.createCovenantBuilder()
25
+ const covenant = builder
26
+ .extractField('value') // Extract value from preimage
27
+ .push('50c3000000000000') // Expected minimum value
28
+ .greaterThanOrEqual() // Ensure value >= minimum
29
+ .verify() // Assert condition
30
+ .build()
31
+
32
+ console.log('Generated ASM:', covenant.cleanedASM)
33
+ console.log('Generated Hex:', covenant.hex)
34
+
35
+ // 🧪 Simulate script execution
36
+ const result = SmartContract.simulateScript(['OP_1', 'OP_2', 'OP_ADD'])
37
+ console.log('Final stack:', result.finalStack) // ['03']
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Core Classes
43
+
44
+ ### SmartContract.Covenant
45
+ **Production-ready covenant creation and management**
46
+
47
+ ```javascript
48
+ const privateKey = bsv.PrivateKey.fromRandom()
49
+ const covenant = SmartContract.createCovenant(privateKey, {
50
+ storageDir: './covenants'
51
+ })
52
+
53
+ // Create covenant from P2PKH UTXO
54
+ const result = covenant.createFromP2PKH({
55
+ txid: 'abc123...',
56
+ vout: 0,
57
+ satoshis: 100000,
58
+ script: 'p2pkh_script_hex'
59
+ })
60
+
61
+ // Complete workflow
62
+ const flow = covenant.completeFlow(p2pkhUtxo, (tx, phase) => {
63
+ console.log(`${phase} transaction:`, tx.id)
64
+ })
65
+ ```
66
+
67
+ ### SmartContract.Preimage
68
+ **BIP-143 preimage parsing with enhanced CompactSize varint support**
69
+
70
+ ```javascript
71
+ const preimage = SmartContract.extractPreimage(preimageHex, {
72
+ strategy: 'DYNAMIC' // AUTO-DETECT best extraction method
73
+ })
74
+
75
+ const fields = preimage.extract()
76
+ console.log('Script code:', fields.scriptCode.toString('hex'))
77
+ console.log('Amount:', fields.amount.toString('hex'))
78
+
79
+ // Handle the "zero hash mystery"
80
+ const sighashInfo = preimage.getSighashInfo()
81
+ if (sighashInfo.hasZeroHashes) {
82
+ console.log('Zero hash explanation:', SmartContract.explainZeroHashes())
83
+ }
84
+ ```
85
+
86
+ ### SmartContract.SIGHASH
87
+ **SIGHASH flag analysis and zero hash behavior explanation**
88
+
89
+ ```javascript
90
+ const sighash = SmartContract.analyzeSIGHASH(0x41) // SIGHASH_ALL | FORKID
91
+ const analysis = sighash.analyze()
92
+
93
+ console.log('Flag name:', analysis.flagName)
94
+ console.log('Has ANYONECANPAY:', analysis.anyoneCanPay)
95
+ console.log('Zero hash behavior:', sighash.getZeroHashBehavior())
96
+
97
+ // Educational demonstrations
98
+ const allTypes = SmartContract.getAllSIGHASHTypes()
99
+ const demos = SmartContract.demonstrateAllSIGHASH()
100
+ ```
101
+
102
+ ### SmartContract.CovenantBuilder
103
+ **High-level JavaScript-to-Bitcoin Script API**
104
+
105
+ ```javascript
106
+ const builder = SmartContract.createCovenantBuilder()
107
+
108
+ // Fluent API with 61 methods
109
+ const covenant = builder
110
+ .comment('Check minimum value requirement')
111
+ .extractField('value')
112
+ .push('1000000') // 1M satoshis
113
+ .greaterThanOrEqual()
114
+ .verify()
115
+ .build()
116
+ ```
117
+
118
+ ---
119
+
120
+ ## Interface Functions
121
+
122
+ ### Core Operations (5 functions)
123
+
124
+ #### `createCovenant(privateKey, options)`
125
+ Creates a new Covenant instance for covenant management.
126
+
127
+ ```javascript
128
+ const covenant = SmartContract.createCovenant(privateKey, {
129
+ storageDir: './my-covenants',
130
+ network: 'mainnet'
131
+ })
132
+ ```
133
+
134
+ #### `extractPreimage(preimageHex, options)`
135
+ Parses BIP-143 preimage with advanced field extraction.
136
+
137
+ ```javascript
138
+ const preimage = SmartContract.extractPreimage(preimageHex, {
139
+ strategy: 'DYNAMIC', // LEFT, RIGHT, or DYNAMIC
140
+ validateFields: true, // Validate extracted fields
141
+ detectSIGHASH: true // Analyze SIGHASH flags
142
+ })
143
+
144
+ const fields = preimage.extract()
145
+ console.log('Extracted fields:', Object.keys(fields))
146
+ ```
147
+
148
+ #### `analyzeSIGHASH(sighashType)`
149
+ Analyzes SIGHASH flags and explains zero hash behavior.
150
+
151
+ ```javascript
152
+ const analysis = SmartContract.analyzeSIGHASH(0x41)
153
+ console.log('Flag details:', analysis.analyze())
154
+ console.log('Zero behavior:', analysis.getZeroHashBehavior())
155
+ ```
156
+
157
+ #### `buildCovenant(privateKey, options)`
158
+ Creates advanced covenant builder with multi-field validation.
159
+
160
+ ```javascript
161
+ const builder = SmartContract.buildCovenant(privateKey, {
162
+ validateFields: ['hashPrevouts', 'amount'],
163
+ customRules: [/* custom validation functions */]
164
+ })
165
+ ```
166
+
167
+ #### `completeCovenantFlow(privateKey, p2pkhUtxo, broadcastCallback)`
168
+ Executes complete covenant workflow from creation to spending.
169
+
170
+ ```javascript
171
+ const result = SmartContract.completeCovenantFlow(
172
+ privateKey,
173
+ p2pkhUtxo,
174
+ (transaction, phase) => {
175
+ console.log(`Broadcasting ${phase} transaction...`)
176
+ // Your broadcast logic here
177
+ }
178
+ )
179
+ ```
180
+
181
+ ### JavaScript-to-Script Framework (7 functions)
182
+
183
+ #### `createCovenantBuilder()`
184
+ Creates a new CovenantBuilder instance for fluent script construction.
185
+
186
+ ```javascript
187
+ const builder = SmartContract.createCovenantBuilder()
188
+
189
+ // Chain operations fluently
190
+ const script = builder
191
+ .push('deadbeef')
192
+ .sha256()
193
+ .push('expected_hash')
194
+ .equal()
195
+ .verify()
196
+ .build()
197
+ ```
198
+
199
+ #### `createValueLockCovenant(expectedValue)`
200
+ Creates a covenant that validates minimum value requirements.
201
+
202
+ ```javascript
203
+ const valueLock = SmartContract.createValueLockCovenant('50c3000000000000')
204
+ const script = valueLock.build()
205
+
206
+ console.log('Value lock ASM:', script.cleanedASM)
207
+ // Output: OP_SIZE 22 OP_SUB OP_SPLIT OP_DROP OP_8 OP_SPLIT OP_DROP 50c3000000000000 OP_GREATERTHANOREQUAL OP_VERIFY
208
+ ```
209
+
210
+ #### `createHashLockCovenant(expectedHash)`
211
+ Creates a covenant that validates hash preimage requirements.
212
+
213
+ ```javascript
214
+ const hashLock = SmartContract.createHashLockCovenant('abcd1234')
215
+ const script = hashLock.build()
216
+
217
+ console.log('Hash lock operations:', script.operations.length)
218
+ ```
219
+
220
+ #### `createComplexValidationCovenant(rules)`
221
+ Creates a covenant with multiple validation rules.
222
+
223
+ ```javascript
224
+ const complex = SmartContract.createComplexValidationCovenant({
225
+ fields: {
226
+ value: { equals: '50c3000000000000' },
227
+ hashPrevouts: { notEquals: '0000000000000000000000000000000000000000000000000000000000000000' }
228
+ },
229
+ customLogic: builder => builder.push('custom_data').verify()
230
+ })
231
+ ```
232
+
233
+ #### `getOpcodeMap()`
234
+ Returns the complete mapping of 121 Bitcoin Script opcodes.
235
+
236
+ ```javascript
237
+ const opcodes = SmartContract.getOpcodeMap()
238
+
239
+ console.log('Total opcodes:', Object.keys(opcodes).length) // 121
240
+ console.log('OP_ADD details:', opcodes.OP_ADD)
241
+ // { code: 0x93, action: function, description: 'Add two numbers', category: 'arithmetic' }
242
+ ```
243
+
244
+ #### `simulateScript(operations, initialStack)`
245
+ Simulates Bitcoin Script execution with step-by-step debugging.
246
+
247
+ ```javascript
248
+ const simulation = SmartContract.simulateScript(['OP_1', 'OP_2', 'OP_ADD'], [])
249
+
250
+ console.log('Final stack:', simulation.finalStack) // ['03']
251
+ console.log('Execution steps:', simulation.history) // Detailed step history
252
+ console.log('Success:', simulation.success) // true
253
+ ```
254
+
255
+ #### `createASMFromJS(operations)`
256
+ Converts JavaScript operation array to Bitcoin Script ASM.
257
+
258
+ ```javascript
259
+ const asm = SmartContract.createASMFromJS(['OP_DUP', 'OP_HASH160', 'deadbeef', 'OP_EQUALVERIFY'])
260
+
261
+ console.log('Generated ASM:', asm)
262
+ // Output: "OP_DUP OP_HASH160 deadbeef OP_EQUALVERIFY"
263
+ ```
264
+
265
+ ### Testing & Debugging (5 functions)
266
+
267
+ #### `testScript(unlockingScript, lockingScript, options)`
268
+ Tests script execution with unlocking and locking scripts.
269
+
270
+ ```javascript
271
+ const result = SmartContract.testScript('OP_1', 'OP_VERIFY', {
272
+ enableDebug: true,
273
+ strict: true
274
+ })
275
+
276
+ console.log('Script valid:', result.valid)
277
+ console.log('Execution trace:', result.trace)
278
+ ```
279
+
280
+ #### `testCovenant(preimageHex, constraints, options)`
281
+ Tests covenant validation against preimage data.
282
+
283
+ ```javascript
284
+ const result = SmartContract.testCovenant(preimageHex, {
285
+ value: { min: 1000000 },
286
+ hashPrevouts: { notZero: true }
287
+ }, { enableLogging: true })
288
+
289
+ console.log('Covenant valid:', result.success)
290
+ console.log('Validation details:', result.validations)
291
+ ```
292
+
293
+ #### `testFieldExtraction(preimageHex, fieldName, options)`
294
+ Tests specific field extraction from preimage.
295
+
296
+ ```javascript
297
+ const result = SmartContract.testFieldExtraction(preimageHex, 'value', {
298
+ strategy: 'DYNAMIC',
299
+ validateResult: true
300
+ })
301
+
302
+ console.log('Extracted value:', result.extracted)
303
+ console.log('Extraction strategy used:', result.strategyUsed)
304
+ ```
305
+
306
+ #### `debugScript(config, options)`
307
+ Provides detailed script debugging and analysis.
308
+
309
+ ```javascript
310
+ const debug = SmartContract.debugScript({
311
+ script: ['OP_1', 'OP_2', 'OP_ADD'],
312
+ breakpoints: [1, 2],
313
+ watchStack: true
314
+ })
315
+
316
+ console.log('Debug info:', debug.analysis)
317
+ console.log('Stack snapshots:', debug.stackSnapshots)
318
+ ```
319
+
320
+ #### `createTestEnvironment(options)`
321
+ Creates comprehensive testing environment with real UTXOs.
322
+
323
+ ```javascript
324
+ const testEnv = SmartContract.createTestEnvironment({
325
+ generateUTXO: true,
326
+ createPreimage: true,
327
+ network: 'testnet'
328
+ })
329
+
330
+ console.log('Test UTXO:', testEnv.utxo)
331
+ console.log('Test preimage:', testEnv.preimage)
332
+ ```
333
+
334
+ ### Educational Resources (4 functions)
335
+
336
+ #### `explainZeroHashes()`
337
+ Explains the "zero hash mystery" in Bitcoin preimages.
338
+
339
+ ```javascript
340
+ const explanation = SmartContract.explainZeroHashes()
341
+
342
+ console.log('Title:', explanation.title)
343
+ console.log('Problem:', explanation.problem)
344
+ console.log('Reality:', explanation.reality)
345
+ console.log('Solution:', explanation.solution)
346
+ ```
347
+
348
+ #### `getAllSIGHASHTypes()`
349
+ Returns all SIGHASH flag types with descriptions.
350
+
351
+ ```javascript
352
+ const types = SmartContract.getAllSIGHASHTypes()
353
+
354
+ types.forEach(type => {
355
+ console.log(`${type.name}: 0x${type.value.toString(16)} - ${type.description}`)
356
+ })
357
+ ```
358
+
359
+ #### `demonstrateAllSIGHASH()`
360
+ Generates educational demonstrations for all SIGHASH types.
361
+
362
+ ```javascript
363
+ const demos = SmartContract.demonstrateAllSIGHASH()
364
+
365
+ demos.forEach(demo => {
366
+ console.log(`${demo.typeName}:`)
367
+ console.log(' Behavior:', demo.demonstration.behavior)
368
+ console.log(' Zero hashes:', demo.demonstration.zeroHashes)
369
+ })
370
+ ```
371
+
372
+ #### `getEducationalResources()`
373
+ Returns comprehensive educational materials.
374
+
375
+ ```javascript
376
+ const resources = SmartContract.getEducationalResources()
377
+
378
+ console.log('Zero hash mystery:', resources.zeroHashMystery)
379
+ console.log('SIGHASH types:', resources.sighashTypes.length)
380
+ console.log('Example demos:', resources.exampleDemonstrations.length)
381
+ ```
382
+
383
+ ### Utility Functions (8 functions)
384
+
385
+ #### Constructor Classes (4 functions)
386
+ - `Covenant` - Covenant management class
387
+ - `Preimage` - Preimage parsing class
388
+ - `SIGHASH` - SIGHASH analysis class
389
+ - `Builder` - Advanced covenant builder class
390
+
391
+ #### Generators (4 functions)
392
+ - `UTXOGenerator` - Real UTXO generation class
393
+ - `ScriptTester` - Script testing utilities class
394
+ - `CovenantBuilder` - JavaScript-to-Script builder class
395
+ - `OpcodeMap` - Opcode mapping utilities class
396
+
397
+ ---
398
+
399
+ ## JavaScript-to-Script Framework
400
+
401
+ The revolutionary framework allows you to write covenant logic in JavaScript and automatically generate Bitcoin Script.
402
+
403
+ ### Basic Workflow
404
+
405
+ ```javascript
406
+ // 1. Create builder
407
+ const builder = SmartContract.createCovenantBuilder()
408
+
409
+ // 2. Write logic in JavaScript
410
+ const covenant = builder
411
+ .comment('Validate transaction value')
412
+ .extractField('value') // Get value from preimage
413
+ .push('1000000') // 1M satoshis minimum
414
+ .greaterThanOrEqual() // value >= 1M
415
+ .verify() // Assert condition
416
+ .build()
417
+
418
+ // 3. Get Bitcoin Script output
419
+ console.log('ASM:', covenant.cleanedASM)
420
+ console.log('Hex:', covenant.hex)
421
+ console.log('Size:', covenant.operations.length, 'operations')
422
+ ```
423
+
424
+ ### Advanced Example: Multi-condition Covenant
425
+
426
+ ```javascript
427
+ const builder = SmartContract.createCovenantBuilder()
428
+
429
+ const covenant = builder
430
+ .comment('Multi-condition covenant validation')
431
+
432
+ // Condition 1: Check minimum value
433
+ .extractField('value')
434
+ .push('1000000')
435
+ .greaterThanOrEqual()
436
+ .verify()
437
+
438
+ // Condition 2: Verify hash preimage
439
+ .push('deadbeef')
440
+ .sha256()
441
+ .push('expected_hash_of_deadbeef')
442
+ .equalVerify()
443
+
444
+ // Condition 3: Time lock validation
445
+ .extractField('nLockTime')
446
+ .push('1609459200') // Jan 1, 2021
447
+ .greaterThan()
448
+ .verify()
449
+
450
+ .build()
451
+
452
+ console.log('Complex covenant ASM:', covenant.cleanedASM)
453
+ ```
454
+
455
+ ---
456
+
457
+ ## CovenantBuilder API
458
+
459
+ The CovenantBuilder provides 61 methods for fluent covenant construction:
460
+
461
+ ### Stack Operations (12 methods)
462
+ ```javascript
463
+ builder
464
+ .push('data') // Push data onto stack
465
+ .dup() // Duplicate top item
466
+ .drop() // Remove top item
467
+ .swap() // Swap top two items
468
+ .over() // Copy second item to top
469
+ .rot() // Rotate top three items
470
+ .pick(depth) // Copy item at depth to top
471
+ .roll(depth) // Move item at depth to top
472
+ .depth() // Push stack depth
473
+ .size() // Push size of top item
474
+ .left(n) // Take left n bytes
475
+ .right(n) // Take right n bytes
476
+ ```
477
+
478
+ ### Arithmetic Operations (10 methods)
479
+ ```javascript
480
+ builder
481
+ .add() // Add top two numbers
482
+ .sub() // Subtract: second - first
483
+ .mul() // Multiply top two numbers
484
+ .div() // Divide: second / first
485
+ .mod() // Modulo: second % first
486
+ .abs() // Absolute value
487
+ .negate() // Negate number
488
+ .min() // Minimum of two numbers
489
+ .max() // Maximum of two numbers
490
+ .within() // Check if x is within min/max
491
+ ```
492
+
493
+ ### Comparison Operations (8 methods)
494
+ ```javascript
495
+ builder
496
+ .equal() // Check equality
497
+ .equalVerify() // Check equality and verify
498
+ .numEqual() // Numeric equality
499
+ .numNotEqual() // Numeric inequality
500
+ .lessThan() // Less than comparison
501
+ .lessThanOrEqual() // Less than or equal
502
+ .greaterThan() // Greater than comparison
503
+ .greaterThanOrEqual() // Greater than or equal
504
+ ```
505
+
506
+ ### Logical Operations (6 methods)
507
+ ```javascript
508
+ builder
509
+ .and() // Bitwise AND
510
+ .or() // Bitwise OR
511
+ .xor() // Bitwise XOR
512
+ .not() // Bitwise NOT
513
+ .boolAnd() // Boolean AND
514
+ .boolOr() // Boolean OR
515
+ ```
516
+
517
+ ### Cryptographic Operations (5 methods)
518
+ ```javascript
519
+ builder
520
+ .hash160() // RIPEMD160(SHA256(x))
521
+ .hash256() // SHA256(SHA256(x))
522
+ .sha256() // SHA256(x)
523
+ .ripemd160() // RIPEMD160(x)
524
+ .invert() // Bitwise inversion
525
+ ```
526
+
527
+ ### Control Flow (4 methods)
528
+ ```javascript
529
+ builder
530
+ .if() // Conditional execution
531
+ .else() // Else branch
532
+ .endif() // End conditional
533
+ .verify() // Assert top item is true
534
+ ```
535
+
536
+ ### Data Manipulation (8 methods)
537
+ ```javascript
538
+ builder
539
+ .split() // Split data at position
540
+ .cat() // Concatenate two items
541
+ .substr(start, length) // Extract substring
542
+ .size() // Get size of data
543
+ .left(n) // Take left n bytes
544
+ .right(n) // Take right n bytes
545
+ .extractField(name) // Extract preimage field
546
+ .validateField(name, expected) // Validate field value
547
+ ```
548
+
549
+ ### Utility Methods (8 methods)
550
+ ```javascript
551
+ builder
552
+ .comment(text) // Add documentation comment
553
+ .document(section) // Add documentation section
554
+ .simulate() // Simulate script execution
555
+ .build() // Build final script
556
+ .validateFields(fields) // Validate multiple fields
557
+ .validateRange(min, max) // Validate numeric range
558
+ .return() // Return from script
559
+ ._analyzeStructure() // Internal: analyze script structure
560
+ ```
561
+
562
+ ---
563
+
564
+ ## Opcode Mapping System
565
+
566
+ All 121 Bitcoin Script opcodes are mapped to JavaScript functions:
567
+
568
+ ### Categories
569
+
570
+ 1. **Constants (16 opcodes)**: `OP_FALSE`, `OP_TRUE`, `OP_1` through `OP_16`
571
+ 2. **Push Data (4 opcodes)**: `OP_PUSHDATA1`, `OP_PUSHDATA2`, `OP_PUSHDATA4`
572
+ 3. **Flow Control (6 opcodes)**: `OP_IF`, `OP_ELSE`, `OP_ENDIF`, `OP_VERIFY`, `OP_RETURN`
573
+ 4. **Stack Operations (17 opcodes)**: `OP_DUP`, `OP_DROP`, `OP_SWAP`, etc.
574
+ 5. **String Operations (8 opcodes)**: `OP_CAT`, `OP_SPLIT`, `OP_SIZE`, etc.
575
+ 6. **Bitwise Logic (4 opcodes)**: `OP_AND`, `OP_OR`, `OP_XOR`, `OP_INVERT`
576
+ 7. **Arithmetic (11 opcodes)**: `OP_ADD`, `OP_SUB`, `OP_MUL`, `OP_DIV`, etc.
577
+ 8. **Comparison (8 opcodes)**: `OP_EQUAL`, `OP_LESSTHAN`, `OP_GREATERTHAN`, etc.
578
+ 9. **Cryptographic (6 opcodes)**: `OP_SHA256`, `OP_HASH160`, `OP_CHECKSIG`, etc.
579
+ 10. **Reserved (3 opcodes)**: `OP_RESERVED`, `OP_VER`, `OP_VERIF`
580
+ 11. **Splice Operations (4 opcodes)**: `OP_LEFT`, `OP_RIGHT`, `OP_SUBSTR`
581
+ 12. **Numeric (17 opcodes)**: `OP_1ADD`, `OP_1SUB`, `OP_NEGATE`, etc.
582
+ 13. **Disabled (18 opcodes)**: Previously disabled opcodes now mapped
583
+
584
+ ### Usage Example
585
+
586
+ ```javascript
587
+ const opcodes = SmartContract.getOpcodeMap()
588
+
589
+ // Get specific opcode
590
+ console.log('OP_ADD:', opcodes.OP_ADD)
591
+ // { code: 0x93, action: function, description: 'Add two numbers', category: 'arithmetic' }
592
+
593
+ // Simulate specific opcode
594
+ const stack = ['02', '03'] // [2, 3]
595
+ const newStack = opcodes.OP_ADD.action(stack)
596
+ console.log('Result stack:', newStack) // ['05'] (2 + 3 = 5)
597
+ ```
598
+
599
+ ---
600
+
601
+ ## Real-World Examples
602
+
603
+ ### Example 1: Value-Preserving Covenant
604
+
605
+ ```javascript
606
+ // Ensure transaction doesn't reduce value
607
+ const covenant = SmartContract.createCovenantBuilder()
608
+ .comment('Value preservation covenant')
609
+ .extractField('value') // Get current transaction value
610
+ .push('original_value_hex') // Expected original value
611
+ .greaterThanOrEqual() // Ensure value >= original
612
+ .verify() // Assert condition
613
+ .build()
614
+
615
+ console.log('Generated script size:', covenant.operations.length)
616
+ console.log('ASM:', covenant.cleanedASM)
617
+ ```
618
+
619
+ ### Example 2: Hash Lock with Time Delay
620
+
621
+ ```javascript
622
+ const covenant = SmartContract.createCovenantBuilder()
623
+ .comment('Hash lock with time delay')
624
+
625
+ // Check if correct preimage is provided
626
+ .push('secret_data')
627
+ .sha256()
628
+ .push('expected_hash')
629
+ .equal()
630
+
631
+ // OR check if enough time has passed
632
+ .if()
633
+ .push(1) // Valid preimage path
634
+ .else()
635
+ .extractField('nLockTime')
636
+ .push('1640995200') // Jan 1, 2022
637
+ .greaterThan()
638
+ .endif()
639
+
640
+ .verify()
641
+ .build()
642
+
643
+ // Test the covenant
644
+ const simulation = SmartContract.simulateScript(covenant.operations)
645
+ console.log('Simulation result:', simulation.success)
646
+ ```
647
+
648
+ ### Example 3: Multi-Signature with Spending Conditions
649
+
650
+ ```javascript
651
+ const covenant = SmartContract.createCovenantBuilder()
652
+ .comment('Multi-sig with spending conditions')
653
+
654
+ // Require 2-of-3 signatures (simplified)
655
+ .push('sig1')
656
+ .push('sig2')
657
+ .push('sig3')
658
+ .push(2) // Require 2 signatures
659
+ // ... multi-sig verification logic ...
660
+
661
+ // AND require minimum output value
662
+ .extractField('value')
663
+ .push('100000') // 100k satoshis minimum
664
+ .greaterThanOrEqual()
665
+ .verify()
666
+
667
+ .build()
668
+
669
+ console.log('Multi-sig covenant ASM:', covenant.cleanedASM)
670
+ ```
671
+
672
+ ---
673
+
674
+ ## Error Handling
675
+
676
+ ### Script Validation
677
+
678
+ ```javascript
679
+ try {
680
+ const covenant = builder.build()
681
+
682
+ // Validate generated script
683
+ const validation = SmartContract.validateScript(covenant.operations)
684
+ if (!validation.valid) {
685
+ console.log('Script validation errors:', validation.errors)
686
+ }
687
+
688
+ } catch (error) {
689
+ console.log('Build error:', error.message)
690
+ }
691
+ ```
692
+
693
+ ### Simulation Error Handling
694
+
695
+ ```javascript
696
+ const simulation = SmartContract.simulateScript(['OP_1', 'OP_VERIFY'])
697
+
698
+ if (!simulation.success) {
699
+ console.log('Simulation failed:', simulation.error)
700
+ console.log('Failed at step:', simulation.failedStep)
701
+ console.log('Stack at failure:', simulation.stackAtFailure)
702
+ }
703
+ ```
704
+
705
+ ### Preimage Extraction Errors
706
+
707
+ ```javascript
708
+ try {
709
+ const preimage = SmartContract.extractPreimage(preimageHex)
710
+ const fields = preimage.extract()
711
+
712
+ // Check for warnings
713
+ const validation = preimage.validate()
714
+ if (validation.warnings.length > 0) {
715
+ console.log('Extraction warnings:', validation.warnings)
716
+ }
717
+
718
+ } catch (error) {
719
+ console.log('Preimage extraction failed:', error.message)
720
+ }
721
+ ```
722
+
723
+ ---
724
+
725
+ ## Performance Considerations
726
+
727
+ ### Script Size Optimization
728
+
729
+ ```javascript
730
+ // Use built-in optimization (if available)
731
+ const optimized = SmartContract.optimizeScript(covenant.operations)
732
+ console.log('Original size:', covenant.operations.length)
733
+ console.log('Optimized size:', optimized.length)
734
+
735
+ // Estimate script execution cost
736
+ const metrics = SmartContract.scriptMetrics(covenant.operations)
737
+ console.log('Estimated cost:', metrics.estimatedCost)
738
+ ```
739
+
740
+ ### Simulation Performance
741
+
742
+ ```javascript
743
+ // For large scripts, use step limits
744
+ const simulation = SmartContract.simulateScript(operations, [], {
745
+ maxSteps: 10000,
746
+ enableLogging: false // Disable for performance
747
+ })
748
+ ```
749
+
750
+ ---
751
+
752
+ This API reference provides comprehensive coverage of all SmartContract functionality. The JavaScript-to-Bitcoin Script framework enables developers to write complex covenant logic in familiar JavaScript syntax while automatically generating optimized Bitcoin Script output.
753
+
754
+ For additional examples and tutorials, see the `/docs` directory in the repository.