BSV blockchainBSV blockchain

ServerWallet class

ServerWallet is the @bsv/simple wallet object for Node.js code that signs transactions on its own, such as a backend or an agent. In the code, it is a TypeScript type returned by the factory ServerWallet.create(), with no constructor to call with new. It wraps a Wallet from @bsv/wallet-toolbox built from a private key your server holds, and has every method of BrowserWallet plus the deprecated receivePayment(). This page was written against @bsv/simple 0.7.2 with @bsv/sdk 4.0.1.

Create a server wallet

Install @bsv/simple with its peer dependency, @bsv/sdk. Both need Node.js 22 or later:

npm install @bsv/simple @bsv/sdk

Import ServerWallet from @bsv/simple/server, the entry point for Node.js, and call ServerWallet.create(). Pass network: 'testnet' while you build, because the network is main when you leave it out.

The private key controls every coin of the server wallet. Read it from an environment variable and keep it out of your repository and your logs.

wallet.ts
import { ServerWallet } from '@bsv/simple/server'

const wallet = await ServerWallet.create({
  privateKey: process.env.SERVER_PRIVATE_KEY!,
  network: 'testnet',
  storageUrl: process.env.STORAGE_URL!
})

console.log(wallet.getStatus())

Run it with node --env-file=.env wallet.ts on Node.js 24 or with a TypeScript runner such as tsx. It prints the status of the new wallet, here with the identity key shortened:

{
  isConnected: true,
  identityKey: '03addccf...31d5f9',
  network: 'testnet'
}

SERVER_PRIVATE_KEY holds the key in hex, and generatePrivateKey() from @bsv/simple/server returns a new random one. STORAGE_URL is a testnet storage server, since the package has no testnet default. To run one on your machine, see Run a wallet backend.

Options and defaults

ServerWallet.create() takes the first three fields. It passes only network on to the wallet’s defaults, so every other field keeps the package value below:

FieldDefaultWhat it does
privateKeyNone, requiredThe private key in hex.
networkmainmain or testnet. Sets the network of the toolbox wallet, and the value getStatus() reports.
storageUrlhttps://storage.babbage.systemsThe storage server that keeps the wallet’s records. The default serves Mainnet.
descriptionBSV-Simplify transactionThe transaction description when a method sets none.
outputDescriptionBSV-Simplify outputThe output description when a method sets none.
tokenBaskettokensThe basketA named group of outputs that a wallet tracks together for tokens.
tokenProtocolID[0, 'token']The key derivation protocol for tokens.
tokenKeyID1The key ID for tokens.
messageBoxHosthttps://messagebox.babbage.systemsThe message boxA server that holds messages and payments for a recipient until the recipient collects them host.
registryUrlNoneThe identity registry for the tag methods.
registryFetchNoneA transport for registry requests.

create() cannot set registryUrl, registryFetch or messageBoxHost, so pass registryUrl to each tag method. The message box host stays the default, except for the host argument of certifyForMessageBox().

create() throws a TypeError with the message Invalid server wallet configuration when config is not a plain object or privateKey is not a string, Invalid server wallet network for any other network, and Invalid server wallet storage URL when storageUrl is not a string. Errors from reading the key or reaching the storage server pass to your code unchanged.

Wallet and identity

These methods come from WalletCore, the base class of both wallet objects. The object also has two read-only properties, identityKey (the identity keyThe public key that identifies a wallet to apps and other users, a compressed public key in hex) and defaults:

MethodWhat it does
getClient(): WalletInterfaceReturns the toolbox Wallet typed as the BRC-100BSV Request for Comments 100, the standard interface between apps and wallets WalletInterface, for libraries that take a BRC-100 wallet or for wallet methods the object does not wrap.
getIdentityKey(): stringReturns identityKey.
getAddress(): stringReturns the P2PKHPay to Public Key Hash, the standard script that locks coins to an address address of the identity key, always in the Mainnet format, even on testnet.
getStatus(): WalletStatusReturns identityKey (typed string | null), network (the value passed to create()) and isConnected, which is always true.
getWalletInfo(): WalletInfoReturns the same values as getStatus(), plus address.
getBalance(basket?: string): Promise<BalanceResult>Returns the balance in satoshisThe smallest unit of BitcoinSV (BSV): 1 BSV is 100,000,000 satoshis. Without basket, both satoshi fields hold the wallet balance and both output counts are 0. With basket, it reads every output and throws when the basket holds more than 100,000 outputs or changes during the read.
derivePublicKey(protocolID, keyID, counterparty?, forSelf?): Promise<string>Returns a derived public key in hex. counterparty defaults to anyone and forSelf to false.
derivePaymentKey(counterparty: string, invoiceNumber?: string): Promise<string>Returns the key a payment to counterparty goes to, with the BRC-29BSV Request for Comments 29, payments to a key derived for each payment protocol. invoiceNumber defaults to 8 random bytes in base64.

Transactions and payments

These methods come from WalletCore, except receivePayment(), which only ServerWallet has. The ones that pay send the transaction with no one approving it.

A server wallet signs and sends every transaction on its own, and a broadcast transaction cannot be undone.

MethodWhat it does
send(options: SendOptions): Promise<SendResult>Builds and broadcasts one transaction from 1 to 1,000 outputs, in order. Per output, to alone makes a P2PKH output and needs satoshis, data alone makes an OP_RETURNA script that stores data in a transaction and can never be spent output with 0 satoshis, and both make a PushDropA script that stores data fields and locks them to a public key, used for tokens token locked to a key derived for to. Errors start with Send failed:.
pay(options: PaymentOptions): Promise<TransactionResult>Sends a payment to an identity key through its message box. With @bsv/message-box-client 2.7.0, which the package installs, txid is an empty string and tx is undefined, and memo and description are ignored. Errors start with Payment failed:.
createPaymentRequest(options: { satoshis: number; memo?: string }): PaymentRequestReturns a request for a payment to this wallet, with the BRC-29 derivation data the payer needs. Runs locally. Throws WERR_INVALID_PARAMETER from @bsv/sdk when satoshis is not a whole number of at least 1 or memo is over 2,000 bytes.
sendDirectPayment(request: PaymentRequest): Promise<DirectPaymentResult>Pays a request with a P2PKH output to the key derived for the recipient, plus an OP_RETURN output for a memo. Send the result to the recipient for receiveDirectPayment(). Errors start with Direct payment failed:.
receiveDirectPayment(payment: IncomingPayment): Promise<void>Adds a payment made with sendDirectPayment() to the spendable balance, with the label direct_payment. Errors start with Failed to receive direct payment:.
fundServerWallet(request: PaymentRequest, basket?: string): Promise<TransactionResult>Pays a request that a server wallet created with createPaymentRequest(), to fund that server wallet: output 0 pays satoshis to the key derived for the server, and an OP_RETURN output carries the memo. basket keeps the payment output in a basket of the paying wallet. Returns txid, tx and outputs. To credit the payment, the server calls receiveDirectPayment() with tx, the payer’s identity key as senderIdentityKey, the derivationPrefix and derivationSuffix of the request and outputIndex: 0. Errors start with Server wallet funding failed:.
receivePayment(payment: IncomingPayment): Promise<void>Deprecated Use receiveDirectPayment(). Adds the payment with the label server_funding. Throws a TypeError for an invalid field and an Error with Receiving wallet did not accept the payment.

Tokens

The tokens module adds these methods. A token is a PushDrop output whose data the wallet encrypts, so only the wallet that holds the key reads it. The methods that spend a token find it by its outpointThe transaction ID and output index of an output, written as txid.index:

MethodWhat it does
createToken(options: TokenOptions): Promise<TokenResult>Encrypts data (at most 1 MiB as JSON) and creates a token output, 1 satoshi by default, locked to this wallet or to to. basket, protocolID and keyID default to the token fields of defaults. Errors start with Token creation failed:.
listTokenDetails(basket?: string): Promise<TokenDetail[]>Lists and decrypts the tokens of a basket, defaults.tokenBasket by default. Skips outputs it cannot decrypt, and throws when the basket holds more than 10,000 outputs or changes during the read.
sendToken(options: SendTokenOptions): Promise<TransactionResult>Spends a token and locks the same data to the key of to. It does not deliver the transaction, which the recipient needs to use the token. Errors start with Token send failed:.
redeemToken(options: RedeemTokenOptions): Promise<TransactionResult>Spends a token with no new token output, so the token no longer exists. Errors start with Token redeem failed:.
sendTokenViaMessageBox(options: SendTokenOptions): Promise<TransactionResult>Sends a token like sendToken() and delivers the transaction to the recipient’s message box. When the transaction completed but the delivery failed, the error says so, and a retry without checking that transaction sends the token twice. Errors start with Token MessageBox send failed:.
listIncomingTokens(): Promise<any[]>Lists up to 1,000 tokens waiting in the message box. Each item has messageId, sender, transaction, protocolID, keyID, outputIndex and, when the box gives it, createdAt.
acceptIncomingToken(token: any, basket?: string): Promise<any>Adds an item of listIncomingTokens(), matched by its messageId, to a basket, then removes the message from the inbox. Returns accepted, basket and sender. Throws when the item is not in the inbox exactly once. Errors start with Failed to accept incoming token:.

Inscriptions

The inscriptions module adds these methods. Each one calls send() with one OP_RETURN output, so a failed transaction throws Send failed:.

Inscribed data is public, and once the transaction is broadcast it stays on chain: this cannot be undone. Do not inscribe personal data or secrets.

The last argument is optional. Pass it as an object literal with basket and description (5 to 2,000 characters), since its type InscriptionMethodOptions is not exported. The result has lockingScript set to an empty string in each output.

MethodWhat it does
inscribeText(text: string, opts?): Promise<InscriptionResult>Writes text, basket text by default. Throws a RangeError over 1 MiB in UTF-8.
inscribeJSON(data: object, opts?): Promise<InscriptionResult>Writes an object as JSON, basket json by default. Throws a TypeError when it cannot be serialized and a RangeError over 1 MiB.
inscribeFileHash(hash: string, opts?): Promise<InscriptionResult>Writes a SHA-256 hash, basket hash-document by default. Throws Invalid SHA-256 hash format when hash is not 64 hexadecimal characters.
inscribeImageHash(hash: string, opts?): Promise<InscriptionResult>Same as inscribeFileHash(), with the type image-hash and the basket hash-image.

Message box payments and identity tags

The MessageBox module adds these methods. The tag methods call the identity registry at their registryUrl argument, and throw without one, except getMessageBoxHandle(), which returns null. The registry does not check that a caller controls the identity key it registers, so confirm a key from a lookup another way before you pay it:

MethodWhat it does
certifyForMessageBox(handle: string, registryUrl?: string, host?: string): Promise<{ txid; handle }>Advertises this wallet on a message box host, host or the default, and registers handle in the registry. Errors start with MessageBox certification failed:.
getMessageBoxHandle(registryUrl?: string): Promise<string | null>Returns the first handle registered for this wallet, or null when there is none or the request fails. Does not throw.
revokeMessageBoxCertification(registryUrl?: string): Promise<void>Revokes every handle of this wallet. Errors start with MessageBox revocation failed:.
sendMessageBoxPayment(to: string, satoshis: number): Promise<any>Sends a payment to the recipient’s payment_inbox. Returns txid, amount and recipient, where txid is sent or an empty string, not a transaction ID. Errors start with MessageBox payment failed:.
listIncomingPayments(): Promise<any[]>Lists up to 1,000 waiting payments. Each item has messageId, sender and token, which holds amount, transaction, outputIndex and the derivation data. Errors start with Failed to list incoming payments:.
acceptIncomingPayment(payment: any, basket?: string): Promise<any>Adds an item of listIncomingPayments(), matched by its messageId, to the spendable balance, or to basket, then removes the message from the inbox. Throws a TypeError for a missing messageId, an Error when the item is not in the authenticated inbox exactly once, and Internalization failed when the wallet refuses it, which leaves the message in the inbox.
registerIdentityTag(tag: string, registryUrl?: string): Promise<{ tag }>Registers a tag for this wallet’s identity key. Errors start with Tag registration failed:.
lookupIdentityByTag(query: string, registryUrl?: string): Promise<Array<{ tag; identityKey }>>Returns the tags that match query, with their identity keys. Errors start with Tag lookup failed:.
listMyTags(registryUrl?: string): Promise<Array<{ tag; createdAt }>>Lists this wallet’s tags. Errors start with Failed to list tags:.
revokeIdentityTag(tag: string, registryUrl?: string): Promise<void>Revokes one tag. Errors start with Tag revocation failed:.

Certificates and credentials

The certification and credentials modules add these methods, which get certificates from a certifierA server that checks a claim about a user and signs a certificate for their identity key and keep them in the wallet:

MethodWhat it does
acquireCertificateFrom(config: RemoteCertificateRequest): Promise<CertificateData>Calls the HTTPS serverUrl with ?action=info, then ?action=certify, checks the certificate and adds it to the wallet. Then it relinquishes older certificates of the same type from the same certifier, unless replaceExisting is false. Errors start with Certificate acquisition failed:.
listCertificatesFrom(config: { certifiers; types; limit? })Returns totalCertificates and the certificates from those certifiers and types. limit defaults to 100. Errors start with Failed to list certificates:.
relinquishCert(args: { type; serialNumber; certifier }): Promise<void>Removes a certificate from the wallet. Errors start with Failed to relinquish certificate:.
acquireCredential(config: RemoteCertificateRequest): Promise<BRC52Envelope>Gets a certificate like acquireCertificateFrom() and returns it as a verifiable credential. Throws a CredentialError whose message starts with Credential acquisition failed:.
listCredentials(config: { certifiers; types; limit? }): Promise<BRC52Envelope[]>Lists the certificates as verifiable credentials. Throws a CredentialError whose message starts with Failed to list credentials:.

DIDs

The DID module adds these methods. They work offline from the identity key, and a DIDDecentralized identifier, a W3C identifier that the holder controls here does not prove that anyone controls the key now:

MethodWhat it does
getDID(): DidDocumentReturns the DID document of the identity key, with a did:key identifier.
resolveDID(did: string): DidResolutionResultResolves a did:key identifier. For another method, didDocument is null and the error is methodNotSupported, and for a malformed DID, invalidDid. Does not throw.

Overlays

The overlay module adds these methods, which publish to overlay servicesServices that track selected transactions and answer queries about them. broadcastAction() and withRetry() take an Overlay you create with Overlay.create():

MethodWhat it does
advertiseSHIP(domain: string, topic: string, basket?: string): Promise<TransactionResult>Creates a 1 satoshi SHIPServices Host Interconnect Protocol, the record that says which host accepts a topic advertisement for your host at domain. Throws when topic does not start with tm_.
advertiseSLAP(domain: string, service: string, basket?: string): Promise<TransactionResult>Creates a 1 satoshi SLAPServices Lookup Availability Protocol, the record that says which host answers a lookup service advertisement. Throws when service does not start with ls_.
broadcastAction(overlay, actionOptions: { outputs; description? }, topics?)Creates a transaction from outputs in the createAction() format and sends it to the hosts of topics, or of overlay. Returns txid and broadcast, whose success says whether the hosts accepted it. Throws No tx from createAction when the wallet returns no transaction.
withRetry<T>(operation: () => Promise<T>, overlay: Overlay, maxRetries?: number): Promise<T>Runs operation, and when it fails because an input was already spent, sends the competing transaction to the overlay and runs it again, for at most maxRetries attempts (5 by default). operation must be safe to repeat.

To learn more about server wallets on the BSV blockchain, review these articles: