Standard and custom Bitcoin script patterns available in the BSV TypeScript SDK.
Script templates provide reusable patterns for Bitcoin transaction locking and unlocking scripts:
import { P2PKH } from '@bsv/sdk'
// Use a standard template
const template = new P2PKH()
// Create locking script
const lockingScript = template.lock(publicKeyHash)
// Create unlocking script
const unlockingScript = template.unlock(privateKey, signature)
The most common Bitcoin script pattern:
const p2pkh = new P2PKH()
const lock = p2pkh.lock(publicKeyHash)
const unlock = p2pkh.unlock(privateKey, signature)
Direct payment to a public key:
const p2pk = new P2PK()
const lock = p2pk.lock(publicKey)
const unlock = p2pk.unlock(signature)
Store arbitrary data on-chain:
const opReturn = new OpReturn()
const lock = opReturn.lock(data)
// No unlock needed - unspendable output
Create your own script templates:
class TimeLockTemplate implements ScriptTemplate {
lock(lockTime: number, publicKeyHash: string): Script {
return new Script()
.writeNumber(lockTime)
.writeOpCode(OpCode.OP_CHECKLOCKTIMEVERIFY)
.writeOpCode(OpCode.OP_DROP)
.writeOpCode(OpCode.OP_DUP)
.writeOpCode(OpCode.OP_HASH160)
.writeBin(publicKeyHash)
.writeOpCode(OpCode.OP_EQUALVERIFY)
.writeOpCode(OpCode.OP_CHECKSIG)
}
unlock(signature: string, publicKey: string): Script {
return new Script()
.writeBin(signature)
.writeBin(publicKey)
}
}
All templates implement the ScriptTemplate interface:
interface ScriptTemplate {
lock(...args: any[]): Script
unlock(...args: any[]): Script
estimateLength?(args: any[]): number
}
// Use template in transaction
const output = {
satoshis: 1000,
lockingScript: template.lock(publicKeyHash)
}
const input = {
sourceTransaction: prevTx,
sourceOutputIndex: 0,
unlockingScript: template.unlock(privateKey, signature)
}
// Estimate script size for fee calculation
const estimatedSize = template.estimateLength([publicKeyHash])
const fee = estimatedSize * feePerByte
class MultiSigTemplate implements ScriptTemplate {
lock(threshold: number, publicKeys: string[]): Script {
// Implementation for m-of-n multisig
}
unlock(signatures: string[]): Script {
// Implementation for signature collection
}
}
class ConditionalTemplate implements ScriptTemplate {
lock(condition: Script, trueScript: Script, falseScript: Script): Script {
// Implementation for IF/ELSE logic
}
}