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 opcodesconstscript=newScript().writeOpCode(OP.OP_DUP).writeOpCode(OP.OP_HASH160).writeBin(Buffer.from('89abcdefabbaabbaabbaabbaabbaabbaabbaabba','hex')).writeOpCode(OP.OP_EQUALVERIFY).writeOpCode(OP.OP_CHECKSIG);// Serialize to hexconsole.log('Script hex:',script.toHex());// Parse from hexconstparsedScript=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 binaryconstbinary=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
Parses a script from hexadecimal string.
Parameters:
hex: string - Hexadecimal representation of the script
Returns:Script - The parsed script
Example:
Script.fromBinary(bin: number[]): Script
Parses a script from binary array.
Parameters:
bin: number[] - Binary representation of the script
Checks 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
const scriptSize = script.toBinary().length;
if (scriptSize > 10000) {
console.warn('Script exceeds recommended size');
// Consider using overlay network for data storage
}
const opReturnData = ScriptAnalyzer.extractOpReturnData(script);
if (opReturnData.length === 0) {
console.log('No OP_RETURN data found');
}
// Ensure unlocking script provides all required data
const unlockingScript = new Script()
.writeBin(signature)
.writeBin(publicKey);
// Verify script is standard format
if (!lockingScript.isPublicKeyHashOutput()) {
console.warn('Non-standard locking script');
}