Script
Overview
The Script class in the BSV TypeScript SDK provides a comprehensive implementation of Bitcoin Script, the stack-based programming language used to define spending conditions for Bitcoin transactions. It enables creation, manipulation, parsing, and execution of Bitcoin scripts with support for all opcodes, script templates, and advanced scripting patterns.
Purpose
Create and parse Bitcoin scripts (locking and unlocking scripts)
Execute Bitcoin Script operations with a stack-based virtual machine
Support all Bitcoin opcodes including arithmetic, cryptographic, and flow control operations
Serialize scripts to binary, hexadecimal, and ASM (assembly) formats
Parse scripts from various formats (hex, binary, ASM)
Build custom spending conditions and smart contracts
Implement standard script templates (P2PKH, P2PK, OP_RETURN, etc.)
Basic Usage
import { Script, OP } from '@bsv/sdk';
// Create a simple script using opcodes
const script = new Script()
.writeOpCode(OP.OP_DUP)
.writeOpCode(OP.OP_HASH160)
.writeBin(Buffer.from('89abcdefabbaabbaabbaabbaabbaabbaabbaabba', 'hex'))
.writeOpCode(OP.OP_EQUALVERIFY)
.writeOpCode(OP.OP_CHECKSIG);
// Serialize to hex
console.log('Script hex:', script.toHex());
// Parse from hex
const parsedScript = Script.fromHex('76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac');
// Convert to ASM (assembly format)
console.log('Script ASM:', parsedScript.toASM());
// Output: "OP_DUP OP_HASH160 89abcdefabbaabbaabbaabbaabbaabbaabbaabba OP_EQUALVERIFY OP_CHECKSIG"
// Get script binary
const binary = script.toBinary();
console.log('Script length:', binary.length);Key Features
1. Script Construction with Opcodes
Build scripts using the complete set of Bitcoin opcodes:
2. Script Parsing and Serialization
Convert scripts between different formats:
3. Script Execution and Validation
Execute scripts with the Bitcoin Script interpreter:
4. Advanced Script Patterns
Implement complex spending conditions:
API Reference
Constructor
Creates a new empty Script instance.
Static Methods
Script.fromHex(hex: string): Script
Script.fromHex(hex: string): ScriptParses a script from hexadecimal string.
Parameters:
hex: string- Hexadecimal representation of the script
Returns: Script - The parsed script
Example:
Script.fromBinary(bin: number[]): Script
Script.fromBinary(bin: number[]): ScriptParses a script from binary array.
Parameters:
bin: number[]- Binary representation of the script
Returns: Script - The parsed script
Script.fromASM(asm: string): Script
Script.fromASM(asm: string): ScriptParses a script from ASM (assembly) string.
Parameters:
asm: string- ASM representation (e.g., "OP_DUP OP_HASH160 ... OP_CHECKSIG")
Returns: Script - The parsed script
Example:
Instance Methods
writeOpCode(opcode: number): Script
writeOpCode(opcode: number): ScriptAppends an opcode to the script.
Parameters:
opcode: number- The opcode to append (from OP enum)
Returns: Script - The script instance (for chaining)
Example:
writeBin(data: number[] | Buffer): Script
writeBin(data: number[] | Buffer): ScriptAppends data to the script with appropriate push operation.
Parameters:
data: number[] | Buffer- The data to append
Returns: Script - The script instance (for chaining)
Example:
writeNumber(num: number): Script
writeNumber(num: number): ScriptAppends a number to the script.
Parameters:
num: number- The number to append
Returns: Script - The script instance (for chaining)
Example:
toHex(): string
toHex(): stringConverts the script to hexadecimal string.
Returns: string - Hexadecimal representation
toBinary(): number[]
toBinary(): number[]Converts the script to binary array.
Returns: number[] - Binary representation
toASM(): string
toASM(): stringConverts the script to ASM (assembly) format.
Returns: string - Human-readable ASM representation
Example:
isPublicKeyHashOutput(): boolean
isPublicKeyHashOutput(): booleanChecks if the script is a standard P2PKH output.
Returns: boolean - True if P2PKH format
isPublicKeyHashInput(): boolean
isPublicKeyHashInput(): booleanChecks if the script is a standard P2PKH input.
Returns: boolean - True if P2PKH input format
isPushOnly(): boolean
isPushOnly(): booleanChecks if the script contains only data push operations.
Returns: boolean - True if push-only
Instance Properties
Script Chunk Structure
Common Patterns
Pattern 1: Creating Standard Transaction Scripts
Build standard Bitcoin transaction scripts:
Pattern 2: Script Templates for Smart Contracts
Create reusable script templates:
Pattern 3: Script Analysis and Validation
Analyze and validate scripts:
Security Considerations
Script Size Limits: BSV allows larger scripts than BTC, but validate reasonable limits for your use case.
Disabled Opcodes: Some opcodes were disabled in early Bitcoin but are being re-enabled in BSV. Verify which opcodes are available on your target network.
Stack Size: The maximum stack size is 1,000 elements. Design scripts that stay within this limit.
Push Data Size: Individual data pushes are limited to 520 bytes in standard transactions.
Script Validation: Always validate scripts before broadcasting to prevent rejection and fee loss.
OP_RETURN Data: While BSV allows large OP_RETURN outputs, miners may have different policies. Verify with your mining pool.
Performance Considerations
Script Complexity: More complex scripts require more computation. Keep scripts as simple as possible.
Data Size: Large data outputs increase transaction size and fees. Consider using overlay networks for large data.
Branching: IF/ELSE statements add complexity. Minimize branching when possible.
Push Operations: Multiple small pushes are less efficient than fewer larger pushes.
Parsing Overhead: ASM parsing is slower than binary parsing. Use binary format when performance matters.
Related Components
Transaction - Use scripts in transaction inputs and outputs
ScriptTemplate - Pre-built script templates
Signature - Create signatures for scripts
TransactionInput - Scripts in transaction inputs
TransactionOutput - Scripts in transaction outputs
Code Examples
See complete working examples in:
Best Practices
Use standard templates when possible (P2PKH, P2PK) for better compatibility
Test scripts thoroughly before deploying with real funds
Validate script size before broadcasting transactions
Use OP_RETURN for data storage, not other opcodes
Document custom scripts with clear comments explaining logic
Minimize script complexity to reduce validation time and potential bugs
Use ASM format for human readability during development
Store scripts as hex in production for efficiency
Implement proper error handling for script parsing and execution
Follow BRC standards for script templates and protocols
Troubleshooting
Issue: Script parsing fails
Solution: Ensure the hex/binary format is valid and complete.
Issue: Script too large
Solution: Optimize script or split data across multiple outputs.
Issue: OP_RETURN data not extracted correctly
Solution: Ensure proper parsing of OP_RETURN chunks.
Issue: Script execution fails
Solution: Verify all required data is on the stack and opcodes are valid.
Further Reading
Bitcoin Script - Complete Bitcoin Script documentation
Opcodes - All Bitcoin Script opcodes
Script Examples - Common script patterns
Genesis Upgrade - Restored opcodes in BSV
BSV SDK Documentation - Official SDK docs
OP_RETURN Protocol - BRC-8: Transaction envelopes
Status
✅ Complete
Last updated
