The BSV TypeScript SDK is the foundational cryptographic and transaction library for the BSV blockchain. It provides low-level primitives (keys, signatures, hashing), script construction and execution, transaction creation and signing, and integration interfaces for wallets and overlay networks. Every other ts-stack package builds on top of this.
PrivateKey— Elliptic curve private key for ECDSA signatures; methods:toPublicKey(),toAddress(),toWif(),fromWif(),sign(),fromRandom()PublicKey— Public key point; methods:toHash()(P2PKH hash),toAddress(),verify(message, signature)Hash— Hash utilities:hash256(data),hash160(data)for SHA-256 and RIPEMD-160BigNumber— Arbitrary precision arithmetic for satoshi amountsTransactionSignature— ECDSA signature with sighash typeCurve— secp256k1 elliptic curve operationsEntropy— Random number generation for key derivation
Script— Base class for locking/unlocking scripts; methods:toHex(),toArray(),fromHex(),chunks()LockingScript— Output lock constraints; immutable once attached to outputUnlockingScript— Signature data to satisfy locking scriptScriptChunk— Individual operation code and data; methods:toHex(),toBN()OP— Bitcoin script operation codes (enum-like):OP.OP_DUP,OP.OP_HASH160,OP.OP_EQUAL, etc.
P2PKH— Pay-to-Public-Key-Hash; methods:lock(pubKeyHash),unlock(privateKey)for standard paymentsP2PK— Pay-to-Public-Key (legacy)P2SH— Pay-to-Script-HashPushDrop— Proof-carrying data envelope for overlay protocols; methods:createFromFields(...)to encode multi-field data
Transaction— Complete transaction builder; constructor signature:new Transaction(version?, inputs?, outputs?); methods:addInput(sourceTransaction, sourceOutputIndex, unlockingScriptTemplate)addOutput(lockingScript, satoshis, outputDescription?)sign()— Requires wallet implementation viaSignableTransactionfee()— Estimate/calculate feesbroadcast()— Send to networktoHex(),fromHex(hex),id(txid getter)
Input— Single input reference with script templateOutput— Single output with locking script and satoshi amountMerklePath— Merkle inclusion proof for SPV verificationBeef— BRC-62 "BEEF" envelope for atomic transaction batches; constants:BEEF_V1, methods:fromHex(),toHex()BroadcastResponse— Standardized response from broadcasters (ARC, WhatsOnChain, etc.)
SatoshisPerKilobyte— Linear fee rate; constructor:new SatoshisPerKilobyte(satoshisPerKb)LivePolicy— Network-aware fee estimation from chain trackers
ARC— Arc Network transaction submission; methods:broadcast(tx)→Promise<BroadcastResponse>WhatsOnChainBroadcaster— WhatsOnChain API integrationTeranode— Teranode broadcasterBroadcaster— Base interface for all broadcasters
DefaultChainTracker— In-memory blockchain state trackingWhatsOnChainChainTracker— Remote chain state via WhatsOnChain APIBlockHeadersService— Lightweight header service for SPV
DefaultHttpClient— Node.js HTTP client for remote servicesBinaryFetchClient— Browser fetch-based HTTP client
Message— Signed message container- Message signing/verification for BRC-18 and other standards
WalletInterface— BRC-100 standardized wallet interface (peer dependency)CreateActionArgs,CreateActionResult— Transaction creation request/responseSignActionArgs,SignActionResult— Signing request/responseListOutputsArgs,ListActionsArgs— UTXO and action history queriesProtoWallet— Minimal in-memory wallet for testing and local useWalletClient()— Factory for connecting to standard BRC-100 wallets (desktop/browser)
Certificate— X.509-like certificate for peer authenticationIdentityKey— Public identity verificationAuthModule— Pluggable authentication mechanisms
Substrate— Pluggable signature provider interface- Implementation adapters for hardware wallets, custody services, etc.
Storage— KV store interfaceLocalStorageAdapter— Browser localStorageInMemoryStorage— Ephemeral storage for testing
KVStore— Distributed key-value store interface for immutable data
Remittance— Payment protocol for overlay services
Identity— Identity verification and discoveryIdentityResolver— Lookup services
Registry— Protocol/certificate registration- Overlay service discovery
fromUtxo(utxo)— Adapter to convert legacy UTXO format to SDK Input- Backward compatibility helpers
generateTOTP(secret)— Time-based one-time password for 2FAverifyTOTP(token, secret)— Validate TOTP token
TopicBroadcaster— Broadcast messages to topic-based overlay networksTopicListener— Subscribe to overlay topics- Overlay service integration
import { PrivateKey, P2PKH, Transaction } from '@bsv/sdk'
const privKey = PrivateKey.fromWif('L5EY1SbTvvPNSdCYQe1EJHfXCBBT4PmnF6CDbzCm9iifZptUvDGB')
const sourceTransaction = Transaction.fromHex('0200000001...') // Previous tx hex
const tx = new Transaction(1, [
{
sourceTransaction,
sourceOutputIndex: 0,
unlockingScriptTemplate: new P2PKH().unlock(privKey)
}
], [
{
lockingScript: new P2PKH().lock(privKey.toAddress()),
satoshis: 5000,
change: true
}
])
await tx.fee()
await tx.sign()
const broadcast = await tx.broadcast()import { WalletClient, Transaction, CreateActionArgs } from '@bsv/sdk'
const wallet = WalletClient() // Connect to browser/desktop wallet
const tx = new Transaction()
tx.addOutput({ satoshis: 1000, ... })
// Use wallet for signing instead of local key
const actionResult = await wallet.createAction({
description: 'Payment transaction',
outputs: tx.outputs.map(o => ({ ...o, outputDescription: 'payment' }))
})
const signResult = await wallet.signAction({
actionReference: actionResult.signableTransaction.reference
})import { MerklePath, Transaction } from '@bsv/sdk'
const tx = Transaction.fromHex('...')
const merklePath = MerklePath.fromHex('...')
if (merklePath.verify(tx.id, blockHeight, blockHeaderHash)) {
console.log('Transaction is SPV-proven')
}import { PushDrop, Script } from '@bsv/sdk'
const tokenFields = ['myAssetId', '100', JSON.stringify({ name: 'MyToken' })]
const tokenScript = PushDrop.createFromFields(tokenFields)
const output = { lockingScript: tokenScript, satoshis: 1 }import { DefaultChainTracker, SatoshisPerKilobyte, Transaction } from '@bsv/sdk'
const tracker = new DefaultChainTracker()
const feeModel = new SatoshisPerKilobyte(1) // 1 sat/byte
const tx = new Transaction()
// ... add inputs/outputs ...
const estimatedFee = await tx.fee(feeModel, tracker)- Private Key — 256-bit value from which all wallet operations derive. Never exposed in network traffic.
- Public Key — Elliptic curve point derived from private key; used for address generation and signature verification.
- Script — Combination of operation codes and data that define spending conditions. Locking scripts constrain outputs; unlocking scripts unlock them.
- Transaction — Atomic unit of blockchain state change. Inputs reference previous outputs (UTXOs); outputs create new UTXOs.
- UTXO — Unspent Transaction Output; identified by (txid, outputIndex). Spending requires a valid unlocking script.
- Signature — ECDSA signature with sighash byte indicating which transaction fields are committed to.
- Merkle Proof — Proof of inclusion in a block; enables SPV without downloading full blocks.
- BEEF — BRC-62 envelope; atomic bundle of transactions with merkle proofs for offline verification.
- Wallet Interface (BRC-100) — Standardized interface for wallet RPC between apps and wallet services. Abstracts away key management.
- Overlay — Second-layer protocol using on-chain anchors (PushDrop) to build services without blockchain modifications.
- None (SDK is intentionally standalone for browser and Node.js)
- Uses built-in Node.js crypto in server context, WebCrypto in browser
ws— For WebSocket overlay connections (optional)qrcode— For QR code generation in wallet pairing (optional)
- None (SDK is at the base; other packages depend on this)
-
Sighash commit mismatch — Unlocking script hash commits only to parts of the transaction. If you modify tx after signing, signature becomes invalid. Always sign last.
-
Fee estimation timing —
tx.fee()may vary if mempool conditions change. Estimate early and buffer for volatility, or use live fee trackers. -
UTXO reuse across parallel transactions — If two transactions reference the same UTXO, only one will confirm. Wallet implementations must track pending outputs.
-
Script evaluation order — Unlocking script is evaluated first, then locking script. Stack must be left with true atop for success.
-
Broadcast endpoint differences — ARC, WhatsOnChain, Teranode have different response formats and rate limits. Implement retry logic and fallback chains.
-
Key derivation paths — Different protocols (BRC-42, BRC-43) use different paths. Verify derivation matches wallet's expectations to avoid fund loss.
-
Browser vs Node.js API — Some transaction methods (broadcast, network calls) behave differently in browser due to CORS. Test both contexts.
-
Merkle proof validity —
MerklePath.verify()requires exact block height and header hash. Off-by-one errors or header mismatch will fail verification. -
Input spending order — Scripts are evaluated in input order. If an early input fails, later inputs aren't executed. Order matters for deterministic behavior.
-
Satoshi precision — Use
BigNumberfor satoshi arithmetic to avoid floating-point errors. Direct number arithmetic can lose precision above 2^53.
- BRC-18 — Signed messages
- BRC-29 — Bitcoin Envelope (UTXO-addressed messages)
- BRC-42, BRC-43 — Key derivation protocols
- BRC-62 — BEEF (transaction envelope format)
- BRC-100 — Wallet interface standard (exposed but not implemented)
- SPV — Full merkle proof verification support
- Bitcoin Script — Full consensus-rule-compliant interpreter
src/primitives/— Cryptographic primitives (keys, hashes, signatures)src/script/— Script classes and OP code definitionssrc/script/templates/— Standard script templates (P2PKH, P2SH, PushDrop, etc.)src/transaction/— Transaction building, signing, broadcastingsrc/transaction/fee-models/— Fee estimation strategiessrc/transaction/broadcasters/— Network integration (ARC, WhatsOnChain, Teranode)src/transaction/chaintrackers/— Blockchain state trackingsrc/transaction/http/— HTTP client abstractionssrc/messages/— Message signing and verificationsrc/wallet/— BRC-100 wallet interface definitionssrc/auth/— Authentication and certificatessrc/storage/— Storage adapterssrc/kvstore/— KV store interfacesrc/remittance/— Payment protocolssrc/identity/— Identity verificationsrc/registry/— Protocol registrysrc/compat/— Legacy format adapterssrc/totp/— Two-factor authenticationsrc/overlay-tools/— Overlay network integrationmod.ts— Main entry point exporting all public APIs
- @bsv/wallet-toolbox — Builds persistent wallet storage and signing on top of SDK; uses SDK's
WalletInterfaceand transaction APIs - @bsv/btms — Token issuance/transfer via PushDrop script encoding; uses SDK's Transaction and Script APIs
- @bsv/btms-permission-module — BTMS wallet integration; uses SDK's wallet interface
- @bsv/wallet-relay — Mobile wallet pairing protocol; uses SDK's cryptography and wallet interface
- Direct app usage — Any BSV app can import SDK directly for standalone transaction creation without wallet integration