<>ts-stack
Get StartedArchitecturePackagesSpecsGuides
⌘K
Reference
Home
Get StartedOverviewInstallChoose your stackKey concepts
ArchitectureOverviewStack layersBEEF (BRC-62)BRC-100 Wallet InterfaceIdentity & AuthConformance pipeline
PackagesOverviewSDKWalletNetworkOverlaysMessagingMiddlewareHelpers
@bsv/simple@bsv/templates@bsv/did@bsv/wallet-helper@bsv/amountinator@bsv/air-gap@bsv/fund-wallet
InfrastructureOverviewmessage-box-serveroverlay-serveruhrp-server-basicuhrp-server-cloud-bucketwabwallet-infrachaintracks-serverwebrtpay-relay
SpecsOverviewBRC-100 Wallet InterfaceOverlay HTTPMessage-box HTTPAuthsocket (WebSocket)BRC-31 Auth HandshakeBRC-29 Peer PaymentBRC-121 / HTTP 402ARC BroadcastMerkle ServiceStorage AdapterGASP SyncUHRPAir-Gap Optical (BRC-141)
ConformanceOverviewVector catalogTS runnerContributing vectors
GuidesOverviewIdentity, DIDs and credentialsIdentity migrationBuild a wallet-aware appRun an overlay nodePeer-to-peer messagingHTTP 402 payments
ReferenceOverviewBRC indexRepository health
AboutVersioningContributingDoc agentDocumentation sources
npmhttps://www.npmjs.com/package/@bsv/templatesv2.3.0API reference (TypeDoc) ↗
Loading…
Edit this page on GitHub
© 2026 BSV Blockchain. ts-stack is open-source.
GitHubContributingVersioning

@bsv/templates

This source candidate declares SDK peer ^2.1.6 || ^3.0.0 || ^4.0.1. SDK3 remains a coordinated proposal; see the qualification and migration limits before adopting it.

Low-level BSV script templates library — provides reusable locking/unlocking script implementations (OpReturn, MultiPushDrop, P2MSKH) for common and advanced Bitcoin SV patterns without abstracting away control.

The 2.3.0 source candidate is additive and needs no migration. It adds the subpath @bsv/templates/R1Comb.ts, the R1C vault lock of the BSV Wallet (see below); the root entry is unchanged.

2.2.0 (published) is additive and needs no migration. It adds the BRC-162 1Color attribute reader (readOneColorAttributes, reqMatchesDeploy, isProfileId, needsEmptyPayloadMarker), OneColor.lockRemainder, which writes an explicit OP_0 OP_DROP when a remainder starts with <push> OP_DROP and no payload is given, and the preferred 36-byte-aware id helpers oneColorTokenIdFromString/oneColorTokenIdToString. tokenIdFromString/tokenIdToString stay 32-byte only, and Bsv21Binary, Bsv21Token and every existing export are unchanged.

The 2.0.0 source candidate is a breaking release: MandalaToken, MandalaAdmin and ADMIN_PROTOCOL are removed, and BRC-162 token outputs and their strict CBOR payloads move to Bsv21Binary. The SDK peer range is unchanged in source, and 2.0.0 is the first release to publish ^3.0.0 alongside ^2.1.6.

The 1.10.3 source candidate fixes the CommonJS build: require('@bsv/templates') consumers can construct scripts again instead of failing with LockingScript.default is not a constructor (#571). The ESM build and browser bundle size are unchanged; no API migration is required.

Install

bash
npm install @bsv/templates

Quick start

typescript
import { OpReturn } from '@bsv/templates'

const opReturn = new OpReturn()
const lockingScript = opReturn.lock(['APP', JSON.stringify({ action: 'vote' })])

console.log(lockingScript.toHex())

const decodedData = OpReturn.decode(lockingScript)
console.log(decodedData) // ['APP', '{"action":"vote"}']

CommonJS compatibility

Since 1.10.3, SDK classes are imported by name, so CommonJS consumers no longer hit SDK default-import double wrapping. Both module formats export the same root and subpath entries and build the same script bytes.

What it provides

  • OpReturn — Non-spendable data storage; create and decode OP_RETURN scripts
  • MultiPushDrop — Encrypted data tokens with multiple trusted owners; BRC-95 format
  • P2MSKH — Pay-to-Multisig-Key-Hash; M-of-N threshold signing with wallet support
  • Bsv21Binary — BRC-162 (BSV-21 binary) token outputs with one canonical encoding per value, bigint amounts, and a strict CBOR payload codec (encodeStrictCbor, decodeStrictCbor, tryDecodeStrictCbor)
  • R1K1Wallet — Salted P-256 hardware signing with independent secp256k1 recovery
  • R1Comb (subpath @bsv/templates/R1Comb.ts) — 1-of-N (N = 1..5) P-256 vault lock, byte-identical to the BSV Wallet Vault; about 45 KB per lock
  • Script utilities — Type detection, parsing, serialization helpers
  • Wallet integration — Templates accept WalletInterface for BRC-29/BRC-42 derivation

Common patterns

Create and decode an OP_RETURN script

typescript
import { OpReturn } from '@bsv/templates'

const script = new OpReturn().lock(['my-app', 'invoice-paid'])
const fields = OpReturn.decode(script)

console.log(fields) // ['my-app', 'invoice-paid']

Create MultiPushDrop token with 2 trusted owners

typescript
import { SecurityLevel, Utils, type WalletInterface } from '@bsv/sdk'
import { MultiPushDrop } from '@bsv/templates'

declare const creatorWallet: WalletInterface
declare const ownerWallet: WalletInterface

const counterparties = [
  '02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5',
  '03f028892bad7ed57d2fb57bf33081d5cfcf6f9ed3d3d7f159c2e2fff579dc341a'
]
const protocolID: [SecurityLevel, string] = [0, 'example token']
const keyID = 'ticket-1'

const pushDrop = new MultiPushDrop(creatorWallet)
const lockingScript = await pushDrop.lock(
  [Utils.toArray('ticket', 'utf8'), [1, 2, 3]],
  protocolID,
  keyID,
  counterparties
)

const decoded = MultiPushDrop.decode(lockingScript)
console.log(decoded.lockingPublicKeys.length) // 2

// The first owner can build the unlock template for a spending transaction.
const { publicKey: creatorIdentityKey } = await creatorWallet.getPublicKey({ identityKey: true })
const unlocker = new MultiPushDrop(ownerWallet).unlock(protocolID, keyID, creatorIdentityKey)

Lock and decode a BRC-162 token output

typescript
import { PrivateKey } from '@bsv/sdk'
import { Bsv21Binary, encodeStrictCbor, tokenIdToString } from '@bsv/templates'

const pubKeyHash = PrivateKey.fromRandom().toPublicKey().toHash() as number[]
const template = new Bsv21Binary()

// A deploy output has a null token id and carries a strict-CBOR payload.
const deploy = template.lock(null, 0n, pubKeyHash, encodeStrictCbor({ sym: 'USD', dec: 2n }))
console.log(Bsv21Binary.decode(deploy).role) // 'deploy'

// Later outputs name the token by `<deploy txid>_0`; amounts are bigint.
const tokenId = `${'ab'.repeat(32)}_0`
const decoded = Bsv21Binary.decode(template.lock(tokenId, 1_000_000n, pubKeyHash))
console.log(decoded.role, decoded.amount) // 'value' 1000000n
console.log(decoded.tokenId !== undefined && tokenIdToString(decoded.tokenId) === tokenId) // true

decode throws Bsv21BinaryError for a script that starts <push> <push> OP_2DROP but is not canonical (for example amount 5 pushed as 01 05); isTokenShaped distinguishes that from an ordinary script. decodeStrictCbor throws StrictCborError on floats, tags, negative integers, arrays, unsorted keys, non-minimal headers, trailing bytes, nesting deeper than 4 or more than 4096 bytes; tryDecodeStrictCbor returns undefined instead.

Create 2-of-3 multisig

typescript
import { PublicKey, type WalletInterface } from '@bsv/sdk'
import { P2MSKH } from '@bsv/templates'

declare const wallet: WalletInterface

const pubkey1 = '02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5'
const pubkey2 = '03f028892bad7ed57d2fb57bf33081d5cfcf6f9ed3d3d7f159c2e2fff579dc341a'
const pubkey3 = '02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9'
const pubkeys = [
  PublicKey.fromString(pubkey1),
  PublicKey.fromString(pubkey2),
  PublicKey.fromString(pubkey3)
]

const address = P2MSKH.address(pubkeys, 2)
const lockingScript = new P2MSKH().lock(address)

// Spending uses wallet-derived signatures. Each signer applies the same
// customInstructions and passes the prior partial unlocking script onward.
const customInstructions = {
  keyID: 'escrow-1',
  counterparty: 'self',
  pubkeys: pubkeys.map(pubkey => pubkey.toString())
}
const unlocker = new P2MSKH().unlock(wallet, customInstructions)

Create an R1-K1 hardware-backed output

typescript
import { Hash, type PrivateKey, Utils } from '@bsv/sdk'
import { R1K1Wallet } from '@bsv/templates'

declare const compressedP256PublicKeyHex: string
declare const k1RecoveryPrivateKey: PrivateKey
declare const signWithYubiKeyPiv: (digest: Uint8Array) => Promise<Uint8Array>

const template = new R1K1Wallet()
const r1PublicKey = Utils.toArray(compressedP256PublicKeyHex, 'hex')
const salt = crypto.getRandomValues(new Uint8Array(32))
const lockingScript = await template.lock(
  Hash.hash160([...r1PublicKey, ...salt]),
  Hash.hash160(k1RecoveryPrivateKey.toPublicKey().encode(true) as number[])
)

const normalSpend = template.unlock({
  path: 'r1',
  publicKey: r1PublicKey,
  salt,
  signDigest: signWithYubiKeyPiv
})
const recoverySpend = template.unlock({
  path: 'k1',
  privateKey: k1RecoveryPrivateKey
})

The R1 signer receives the final 32-byte transaction digest. A PIV adapter must submit it unchanged to GENERAL AUTHENTICATE and return either the DER ECDSA signature produced by the device or raw 64-byte r || s; applying SHA-256 again creates an invalid signature. Preserve each private 32-byte salt with the wallet metadata. The salt hides a reused PIV public key only until the R1 output is spent.

The generated locking script is 959,632 bytes after both commitments are baked, above common 500 KB miner policy. Confirm target-miner policy before funding it.

An R1 unlocking script also pushes the BIP-143 preimage, whose scriptCode contains roughly 960 KB of the contract after OP_CODESEPARATOR. The R1 path therefore involves about 2 MB of locking-plus-unlocking script material, and the witness alone adds roughly 960 KB to the spending transaction. Account for the resulting fees and confirm any maximum-transaction policy; estimateLength includes this preimage push. The K1 unlocking script remains small.

PIV proves that the hardware key signed the supplied digest, but a YubiKey does not display or independently validate the Bitcoin transaction. PIN and touch policies protect key use, not transaction intent; review the transaction on a trusted host before approving it.

Lock an R1C vault output to 1..5 P-256 keys

ts
import type { Transaction } from '@bsv/sdk'
import * as R1Comb from '@bsv/templates/R1Comb.ts'

declare const p256PublicKeysHex: string[] // 1..5 keys, 33- or 65-byte SEC1
declare const saltHex64: string // 32 random bytes per output; keep it with the wallet
declare const signWithYubiKeyPiv: (digestHex: string) => Promise<number[]> // DER ECDSA
declare const tx: Transaction // version 1; input 0 spends the locked output
declare const sourceSatoshis: number

const keys = p256PublicKeysHex.map(k => R1Comb.compressPubkey(k))
const lockingScript = R1Comb.buildLock({
  commitments: keys.map(k => R1Comb.commitment(k, saltHex64)),
  saltHex64
})
const preimage = R1Comb.sighashPreimage(tx, 0, sourceSatoshis)
const derSig = await signWithYubiKeyPiv(R1Comb.signerDigest(preimage))
const unlockingScript = R1Comb.buildUnlock({ preimage, derSig, pubkeyHex33: keys[0], saltHex64 })
R1Comb.verifyVaultInput({ tx, inputIndex: 0, sourceSatoshis, lockingScript, unlockingScript })

Any one committed key opens the output alone. No key appears on the chain until it spends. Every refusal throws R1CombError.

Key concepts

  • ScriptTemplate Interface — Implements lock() to create locking script and unlock() to sign/spend
  • OP_RETURN — Immutable, non-spendable data storage; standard for metadata
  • PushDrop — Encrypted data format with multi-trusted-owner support; fields are encrypted
  • Multisig — M-of-N threshold signing; requires m private keys to unlock
  • Wallet Integration — Templates accept WalletInterface for wallet-compatible key derivation (BRC-29, BRC-42)
  • Direct Key Mode — Can also use raw public/private keys without wallet
  • Hardware Digest Signer — R1K1Wallet accepts DER output from a PIV signer without exposing the P-256 private key
  • Protocol ID — Identifier for script family; used in wallet derivation contexts
  • Reasonableness Limit — Anti-DoS measure for PushDrop templates

When to use this

  • Creating standard locking scripts for transactions
  • Building applications that need multisig payment flows (P2PKH itself is in @bsv/sdk)
  • Storing data on-chain with OP_RETURN
  • Implementing multi-owner token systems with PushDrop
  • Building hardware-backed outputs with an intentionally inconvenient K1 recovery path
  • Locking funds to any one of up to five P-256 hardware keys (R1Comb)
  • Learning Bitcoin Script patterns

When NOT to use this

  • For ultra-high-level operations — use @bsv/simple
  • For fluent transaction building — use @bsv/wallet-helper
  • When you only need pre-signed transactions — skip templates
  • For testing scripts — use @bsv/sdk Script execution directly

Spec conformance

  • OP_RETURN — Standard Bitcoin data format
  • BRC-95 — PushDrop token format
  • BRC-29 — Hierarchical key derivation (in wallet context)
  • BRC-42 — Public key derivation (in wallet context)
  • Bitcoin Script — All scripts are valid Bitcoin SV scripts

Common pitfalls

  • OP_RETURN is read-only — Cannot spend OP_RETURN outputs; used for data only
  • Lock/Unlock consistency — Lock and unlock must use same protocol ID, key ID, and counterparty parameters
  • Wallet context required — Some templates require WalletInterface if using wallet derivation; pass explicitly
  • Signature generation async — All unlock().sign() calls are async; use await
  • R1 salt backup — Losing an output's private salt makes its R1 path unusable; retain the K1 recovery key and salt metadata separately
  • Miner policy — R1K1Wallet's synthesized P-256 script exceeds common 500 KB policy limits
  • R1C transaction version — An R1Comb spend must be a version-1 transaction; buildUnlock refuses any other preimage. Losing the output's salt makes it unspendable
  • OP_RETURN encoding — Data is UTF-8 by default; encode as hex first and specify enc: 'hex' for binary

Related packages

  • @bsv/wallet-helper — Higher-level abstraction over these templates
  • @bsv/simple — Wallet-level operations
  • @bsv/sdk — Core transaction building and script execution

Reference

  • API reference (TypeDoc)
  • Source on GitHub
  • npm

The SDK4 peer alternative now requires @bsv/sdk ^4.0.1 for the numeric wallet result and legacy wire hotfix. Existing SDK2/3 alternatives and lower bounds remain unchanged. No wire or data migration is required.