BrowserWallet class
BrowserWallet is the @bsv/simple wallet object for web apps. In the code, it is a TypeScript type returned by the factory createWallet(), with no constructor to call with new. It connects to the user’s BRC-100BSV Request for Comments 100, the standard interface between apps and wallets wallet, such as BSV Desktop on a computer or BSV Browser on a phone, through WalletClient from @bsv/sdk, so the keys stay in the user’s wallet and your app never holds them. This page was written against @bsv/simple 0.7.2 with @bsv/sdk 4.0.1.
Create a browser wallet
Install @bsv/simple with its peer dependency, @bsv/sdk:
npm install @bsv/simple @bsv/sdkImport createWallet() from @bsv/simple/browser or from the package root, @bsv/simple, and call it in code that runs in the browser:
import { createWallet } from '@bsv/simple/browser'
const wallet = await createWallet({ network: 'testnet' })
console.log(JSON.stringify(wallet.getStatus(), null, 2))With the user’s wallet on testnet, the browser console shows the status of the wallet object, here with the identity key shortened:
{
"isConnected": true,
"identityKey": "0210765c...053fc4",
"network": "testnet"
}createWallet() asks the user’s wallet for its identity keyThe public key that identifies a wallet to apps and other users, so it resolves only once a wallet answers. network: 'testnet' changes what getStatus() and getWalletInfo() report, not the network of the user’s wallet, which the user switches in the wallet itself.
When no wallet answers, createWallet() throws an Error with the message No wallet available over any communication substrate. Install a BSV wallet today!. It throws a TypeError when the options are not a plain object, or when tokenProtocolID or registryFetch has the wrong form.
Options and defaults
createWallet() takes one optional object of defaults, which the wallet keeps as its read-only defaults property. A field you leave out takes the default below:
| Field | Default | What it does |
|---|---|---|
network | main | main or testnet. Only getStatus() and getWalletInfo() read it. |
description | BSV-Simplify transaction | The transaction description when a method sets none. |
outputDescription | BSV-Simplify output | The output description when a method sets none. |
tokenBasket | tokens | The basketA named group of outputs that a wallet tracks together for tokens. |
tokenProtocolID | [0, 'token'] | The key derivation protocol for tokens. |
tokenKeyID | 1 | The key ID for tokens. |
messageBoxHost | https://messagebox.babbage.systems | The message boxA server that holds messages and payments for a recipient until the recipient collects them host. |
registryUrl | None | The identity registry for the tag methods, when a call passes none. |
registryFetch | None | A transport for registry requests, for a local or private registry. |
Wallet and identity
These methods come from WalletCore, the base class of both wallet objects. The object also has the read-only property identityKey, the identity key as a compressed public key in hex:
| Method | What it does |
|---|---|
getClient(): WalletInterface | Returns the WalletClient connected to the user’s wallet, typed as the BRC-100 WalletInterface, for wallet methods the object does not wrap. |
getIdentityKey(): string | Returns identityKey. |
getAddress(): string | Returns 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(): WalletStatus | Returns identityKey (typed string | null), network and isConnected, which is always true. network is the option of createWallet(), main by default, not the network of the user’s wallet. To read that, call getClient().getNetwork({}). |
getWalletInfo(): WalletInfo | Returns 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
The user’s wallet signs each transaction, and a broadcast transaction cannot be undone. While you test, switch the user’s wallet to testnet and fund it, as in Send a payment from a web app. These methods come from WalletCore:
| Method | What 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 }): PaymentRequest | Returns 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:. |
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:
| Method | What 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.
| Method | What 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, or at defaults.registryUrl, and throw without either, except getMessageBoxHandle(), which returns null. The payment methods use defaults.messageBoxHost. 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:
| Method | What 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:
| Method | What 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:
| Method | What it does |
|---|---|
getDID(): DidDocument | Returns the DID document of the identity key, with a did:key identifier. |
resolveDID(did: string): DidResolutionResult | Resolves 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():
| Method | What 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. |
Related articles
To learn more about apps that use the user’s wallet on the BSV blockchain, review these articles: