Developers · JavaScript
Payments reference
The details of @spiffyvault/payments that the other pages leave out: how a payment chooses its path, every error and what to do, what the package asks of your wallet, and what each payee does, with its limits and timers.
Start with Live payments in JavaScript. If you take payments for orders, read Match payments to your orders and Run the payee safely first: those checks are yours, not the package's. Testnet only for now.
How pay() chooses a path
pay() follows the app's own pay-link screen:
- With a peer ID in the link (
p): live first, if you passlibp2p. - Then mailbox (offline), if you pass
ricochetandidentityKey(the private key of the Ricochet client's libp2p node, whichcreatePaymentNodereturns). Only when live failed before any transaction was handed over: the phone could not be reached, or sent no usable invoice. A failure after that point stops there, so the payee is never paid twice. - PeerPay when the link has only a key (
k). After live and mailbox failed safely, only withpeerPay: { fallback: true }: the app offers this to the user, and never does it on its own.
Before anything is asked of anyone, pay() checks the link with the app's rules (parsePaymentLink), refuses a link or key for another network than the wallet's, refuses a bare BRC-100 key from a testnet wallet unless allowBareKey is set (keys outside links carry a testnet: or regtest: label off mainnet), takes the link's amount, and puts ref <r> into the note for a payment-request link.
The result names the path, the txid and the status. result.attempts lists the paths that failed safely before.
| Status | Path | Meaning |
|---|---|---|
completed | live | The phone checked the payment by SPV and the network holds it. |
sent | live | The phone checked it and the broadcaster took it, but the network had not answered within timeouts.networkMs (60 s). Do not pay again; watch the txid. |
handed-off | mailbox | The sealed payment is in the payee's mailbox. The payee broadcasts it when it collects it. Not collected by result.reclaimAt (3 days on), it is reclaimed (below). |
delivered | PeerPay | Your wallet broadcast it and the token is in the payee's message box. |
To take one path with no fallback, call payLive, payOffline or payViaPeerPay:
import { payOffline, payViaPeerPay } from '@spiffyvault/payments';
// identityKey: the Ed25519 private key of ricochet's libp2p node
const offline = await payOffline(
{ payeePeerId, amountSats: 1000, note: 'Coffee', network: 'testnet' },
{ wallet, ricochet, identityKey });
const peerpay = await payViaPeerPay(
{ paymentKey, amountSats: 1000, note: 'Coffee' },
{ wallet, host: 'https://messagebox.bsvblockchain.tech' });
The PeerPay host defaults to BSVA's https://messagebox.bsvblockchain.tech, which the app reads. @bsv/message-box-client on its own defaults to an older host that the app reads only until 14 November 2026. The token goes to the host you choose; there is no overlay lookup.
Errors
Every failure is a PaymentError with a code, the path, the stage it reached, the txid once there is one, and canPayAnotherWay. The one rule that matters: when canPayAnotherWay is false, the payee may hold the transaction. Never pay again; watch e.txid.
import { PaymentError } from '@spiffyvault/payments';
try {
await pay(/* … */);
} catch (e) {
if (!(e instanceof PaymentError)) throw e;
if (e.canPayAnotherWay) { /* nothing left anyone: safe to try again, or another way */ }
else { /* the payee may hold it: do not pay again; watch e.txid */ }
}
| Code | Stage | Meaning |
|---|---|---|
bad-link, bad-key, bare-key, own-key, network-mismatch, amount-invalid, no-route | prepare | Nothing was asked of anyone. |
link-changed | prepare | The link's signature does not match its fields (LinkChangedError): it was changed after the payee signed it. Do not pay it. |
domain-refused | prepare | The link's website does not vouch for its payee (DomainError, with domain and problem): the link may have been changed. Do not pay it. |
payee-unreachable, server-unreachable | connect | The payee, or the Ricochet server, could not be reached. |
no-invoice, bad-invoice, anchor-missing, anchor-invalid, anchor-other-network, prekeys-* | request | No usable invoice (live), or anchor and pre-keys (mailbox). Nothing was built. |
funding-failed | pay | The wallet could not build it. pay() does not fall back: another path would fail the same way. |
invoice-expired, frame-too-large, beef-unusable | pay | Built, then aborted before it left (aborted: true). |
mailbox-refused | deliver | The mailbox refused it; aborted. |
delivery-unknown | deliver | The answer to the submission was lost. It may be in the mailbox: the inputs stay reserved. |
not-confirmed, payee-refused | settle | Handed to the payee, with no good answer. The inputs stay reserved. Release them only once the txid is known not to be on the network. |
network-refused | settle | The payee took it, then the network refused it (a double spend, for one): the payee was not paid. The inputs stay reserved until the txid is known not to be on the network. |
broadcast-failed, peerpay-undelivered | pay, deliver | PeerPay: the broadcast failed, or the token was not delivered after it. PeerPayUndeliveredError keeps the token: send it again with deliverPeerPayToken(), do not pay again. |
Your wallet
With a BRC-100 wallet (WalletInterface from @bsv/sdk), the package asks createAction for the exact outputs a path needs, with randomizeOutputs: false:
- Live and mailbox:
noSend: true, since the payee broadcasts. The wallet's Atomic BEEF is converted to BEEF V1 with the payment last, the only form the payee takes. A payment given up before it left is aborted withabortAction(the txid as reference). After it left, it is never aborted. - PeerPay: your wallet broadcasts (
acceptDelayedBroadcast: false). The token carries the Atomic BEEF, checked for txid-only entries, which the app refuses.
For a wallet that is not BRC-100, pass a funder (live and mailbox only; PeerPay needs a BRC-100 wallet):
import type { Funder } from '@spiffyvault/payments';
// Build, sign, do NOT broadcast, return BEEF.
const funder: Funder = async (outputs, info) => {
// outputs: [{ lockingScript (hex), satoshis, address? }]; info.broadcast is false
const beef = await build(outputs); // BEEF V1 preferred; V2 and Atomic BEEF are converted
return { beef, abort: release }; // abort(): the payment was given up before it left
};
The package checks that the funded transaction pays every output it asked for. It does not check the fee: the payee's broadcaster refuses a fee that is too low, after the payment was handed over. The app pays 100 satoshis per kilobyte (SatoshisPerKilobyte(100) in @bsv/sdk). Every input must chain back, inside the BEEF, to a transaction with a merkle proof. Your own wallet lists what a funder must keep track of.
Uncollected mailbox payments
A mailbox payment waits until the payee collects and broadcasts it, and until then it is a valid payment the payee could still broadcast. The app gives the payee 3 days, then spends the payment's coins back to itself, so the payee's copy can no longer go through. The package asks your wallet to do the same: a mailbox payment's createAction carries the BRC-177 label p nosend expiry seconds 259200 (OFFLINE_RECLAIM_SECONDS). The wallet then:
- broadcasts a small transaction that makes one coin for this payment, and pays the payment from that coin alone, so no other coins are held;
- signs a reclaim of that coin back to itself, and keeps it;
- after the deadline, broadcasts the reclaim, but only when the network has never seen the payment. A payment the payee broadcast in time is left alone.
It waits for clear answers and defers on anything else, so the reclaim can go out some minutes after the deadline. The reclaimed coins count in the balance once the reclaim is in a block. result.reclaimAt says when (milliseconds since 1970). What it needs:
- A wallet with BRC-177: Wallet Toolbox 2.14.7 or later. A wallet without it refuses the payment, and
pay()fails withfunding-failedbefore anything is handed over. - The wallet's monitor running: the toolbox's
Monitorkeeps the deadline. A wallet on remote storage has the server's monitor do it. - A little more fee: one more transaction per mailbox payment.
A delivery that fails after the payment was built calls abortAction; for these payments the toolbox broadcasts the reclaim at once. offlineReclaimSeconds sets another deadline; offlineReclaimSeconds: false leaves the label out, for a wallet without BRC-177, and then you reclaim stranded payments yourself. With a funder, the package cannot reclaim: at info.reclaimAt, if the network has not seen the payment, spend its inputs back to yourself. Freeing your marks on the inputs is not enough. Live and PeerPay payments carry no label: they are broadcast at once.
Checking links in code
import { linkMismatch, noteToSend, parsePaymentLink, linkSignatureValid, checkPayeeDomain }
from '@spiffyvault/payments';
const link = parsePaymentLink(text); // null when it is not a valid SpiffyVault link
const wrongNetwork = linkMismatch(link, 'mainnet') !== null;
const note = noteToSend(link, link.memo); // adds "ref <r>" for a payment-request link
const signed = linkSignatureValid(link); // pay() checks this too
const check = await checkPayeeDomain({ domain: link.domain, network: link.network, peerId: link.peerId });
if (!check.verified) { /* refuse: check.problem says why ('not-listed', 'unreachable', …) */ }
pay() makes the same checks: a link whose website does not vouch for its payee fails with domain-refused, and a paid one comes back with result.payeeDomain. The website check:
- reads
https://<d>/.well-known/spiffyvault.jsonover HTTPS, follows no redirect, waits 5 s and reads at most 16 KiB; - in a browser, needs the site to send
Access-Control-Allow-Originfor the file; without it the answer isunreachable, and the link is refused; - never reaches a private network, since whoever makes a link chooses its domain. A domain at or under
localhost,local,internal,home.arpa,lan,home,corporintranetisunreachableand nothing is fetched. In Node.js,nodeDomainFetchlooks the name up once, refuses it when any address is loopback, private, link-local, shared or unique-local, and connects to the address it looked up. Pass your ownfetch, ordomainFetchtopay(), only if it does the same.
A shop's server writes its file with the payee's libp2p key; the entry is the app's, byte for byte:
import { domainEntry, domainFileText } from '@spiffyvault/payments';
const entry = await domainEntry(
{ domain: 'shop.example', peerId, paymentKey, networks: ['testnet'], name: 'Corner Shop' }, peerKey);
const file = domainFileText([entry]); // serve at https://shop.example/.well-known/spiffyvault.json
A link with a peer ID that is not signed is still paid, but pay() never falls back from the peer ID to its payment key, since only the signature ties the key to the peer ID. A link written by hand, without s, should at least carry d. See Payment links and QR codes for the fields.
The live payee
What acceptLivePayments does, as the app's payee does:
- Invoices. It calls
screen, theninvoiceAddress, and answers with an invoice for that address and the amount the request asks, or with a refusal. The invoice is held for 60 s (sessionMs). - Limits (
limits, defaultPAYEE_LIMITS): 3 unpaid invoices per payer and 64 in all, 10 requests a minute per payer and 300 in all. A request past a limit is refused asbusybeforescreenorinvoiceAddressis called. - Checks. It takes a payment only for that invoice, from the same payer, while the invoice is held. It reads the BEEF V1, checks that the outputs to the invoice's address pay at least the amount, and checks the transaction by SPV (
chainTracker). - Broadcast. It broadcasts the unproven ancestors, then the payment (
broadcaster, defaultarcBroadcaster: the BSV Association's Arcade). - Seen on the network (
SEEN_ON_NETWORKor better): it callsonPayment, then tells the payer it is done. - Taken, not seen yet: it tells the payer at once that the payment is on its way (event
on-the-way), then waits.arcBroadcasterasks every second for up to 30 s (followMs). Once the network has it,onPaymentruns and the payer is told. If the network refuses it, nothing is kept (not-broadcast). With no answer afternetworkWaitMs(4 minutes), the event isunsettled:onPaymenthas not run, the payer sees the payment as sent, and you watchpayment.txidyourself. onPaymentthrows: the payer still hears success, because the payment is on the network. The eventkeep-failedcarries the whole payment.- Refused: a payment that does not check out is refused, and one the network refuses at once is reported as not broadcast. Nothing is kept for either.
Being found: before every live payment the app asks the Ricochet server's DHT for the payee's peer ID and dials the relay address it gets back. The server learns that address only if the payee tells it after its relay reservation is made, so a payee needs identify push. createPaymentNode turns it on; waitUntilReachable(node) waits for the reservation, and isReachable(node) tells you whether you still have it.
The PeerPay payee
acceptPeerPayPayments reads your payment_inbox on the message box, as the app does:
- Every 10 seconds it lists the inbox. For each token it checks that the output it names pays your wallet's BRC-29 key (counterparty: the sender's identity key) exactly the amount the token says, checks the transaction by SPV, and sends it to the network once more to learn that the network has it. Then it calls
onPayment. - Only after
onPaymentreturns is the message acknowledged, which deletes it from the server. If acknowledging fails, it acknowledges on the next pass without callingonPaymentagain, but only while it runs: after a restart the same payment can come toonPaymentagain. - A step that may work later (the inbox, the chain or the broadcaster could not be reached, the wallet could not open a message) is tried again next pass. After
giveUpMs(one hour) the message is deleted with arefusedornot-broadcastevent. A message that is not a payment token, or does not pay your wallet, is deleted at once withrefused. A payment on the network is never dropped: ifonPaymentkeeps failing, it is offered again every pass. - It needs no
internalizeActionfor this: aProtoWalletmade from the identity key signs in to the server (BRC-103) and opens the messages. Take the payment in wherever you keep coins.
To take the coins into a BRC-100 wallet, in onPayment:
await wallet.internalizeAction({
tx: Array.from(p.atomicBeef),
outputs: p.outputs.map(o => ({
outputIndex: o.outputIndex,
protocol: 'wallet payment',
paymentRemittance: { derivationPrefix: o.derivationPrefix,
derivationSuffix: o.derivationSuffix, senderIdentityKey: o.senderIdentityKey },
})),
description: 'PeerPay payment',
});
The mailbox payee
acceptOfflinePayments does the payee's side of mailbox payments:
- Keys. It publishes a signed pre-key bundle (a new signed pre-key every 7 days), a claim mailbox of signed one-time pre-keys (topped up to 50 once fewer than 25 are left), and an anchor record signed with the node's key. The anchor is the wallet's identity key. It checks these every hour.
- Collecting. Every 30 seconds it reads
wallet/offline-payments. Opening a message uses up its one-time pre-key, so what it says is saved in your store at once. Then it checks the sender, the outputs that pay your wallet, and SPV, broadcasts the payment, and callsonPaymentonce the network has it. Only then is the message deleted. - Failures. A step that may work later is tried again next pass, from what was saved. A payment that does not open, pays nothing to your wallet, or still fails after
maxAttemptspasses (5) is deleted with arefusedornot-broadcastevent; the payer's wallet reclaims it. A payment on the network is never dropped. - The store holds private keys.
offlinePayeeFileStore(path)writes it readable by its owner only. Back it up.
Take the coins in as for PeerPay, with tx: p.transaction.toAtomicBEEF() and description: 'Offline payment'.
What you trust
None of these services can take the coins. Some can stop a payment, and some are taken at their word about what the network did. Each can be replaced by an option, except where it says otherwise.
| Service | Used for | What it could do wrong | When it is down | Your own |
|---|---|---|---|---|
SpiffyVault's Ricochet server, ricochet.spiffyvault.net (152.42.240.103 when DNS fails) | The relay and DHT for live payments; the payee's anchor record, pre-key bundle and one-time pre-keys; the mailbox | See who pays whom, and when. Drop or hold back a payment or a record. Hold back one-time pre-keys, so a payment is sealed with the bundle alone. It cannot read a live payment (encrypted end to end through the relay) or a sealed one, and cannot forge a record, bundle or pre-key: each is signed by the payee's key and checked | No live or mailbox payments. pay() fails before anything is handed over. A payee cannot be reached | relays and the ricochet client you pass. But the app finds payees only through this server, so for payments from the app there is no running your own yet |
| WhatsOnChain | The payee's SPV check of the merkle roots in a payment's proof | Say a root is in the chain when it is not, so the payee takes a payment built on coins that do not exist | The payee refuses the payment as not checked; nothing is broadcast and the payer keeps the coins | chainTracker: any ChainTracker from @bsv/sdk, best of all block headers you keep |
The BSV Association's Arcade (DEFAULT_ARC) | Putting a checked payment on the network, and following it there | Lose a payment, or say the network has seen it when it has not. Only a block proves the network took it | not-broadcast, or unsettled: watch the txid before handing over goods | broadcaster, or arcBroadcaster(network, { url, apiKey }) |
BSVA's message box (DEFAULT_MESSAGE_BOX_HOST) | Carrying a PeerPay token to the payee | See who pays whom. Drop the token, so the payee never learns of the payment | A payment can be on the network with its token undelivered (PeerPayUndeliveredError): send it again with deliverPeerPayToken() | peerPay.host, but the app reads only BSVA's |
| The payee's website | The link's website check | Whoever runs the domain can list any payee. The check proves the domain names the payee, not that the payer meant that domain | pay() refuses the link with domain-refused | domainFetch |
| Your wallet | Funding, broadcasting PeerPay payments, reclaiming uncollected mailbox payments | Whatever its own services do (the wallet toolbox uses WhatsOnChain and a broadcaster) | No payment can be built | Your choice |
ARC is retired on 30 November 2026, so the payee broadcasts to Arcade, which serves the same API: https://arcade-v2-us-1.bsvblockchain.tech on mainnet and https://arcade-v2-testnet-us-1.bsvblockchain.tech on testnet. @spiffyvault/sign-in uses no outside service.
What the package does, and does not do
- It checks the payee's anchor record as the app does, reads the payee's pre-key bundle and claims one of its one-time pre-keys. The bundle's identity key must be the key in the payee's peer ID, and a claimed key must be signed by it. With no one-time pre-key to claim, it seals with the bundle alone, as the app does.
- It seals every mailbox payment as the first message of its own session, from
identityKey; the payee opens it only when that key is the key of the peer ID that sent it. It never reads a reply. - It uses a random live session id, not the app's.
- It writes each live frame in one piece and keeps it under 64 KiB, less on a relayed connection with a byte allowance. A payment too large for that is aborted, and
pay()falls back to the mailbox. - It builds and sends within the payee's 60 s invoice window; when building takes too long it aborts.
- It does not follow a payment on the network after handing it over: no indexer lookups. A mailbox payment the payee never collects is reclaimed by your wallet after 3 days (above).
- It knows nothing of your orders: see Match payments to your orders.
A real payment on testnet
The repository's tools/e2e-pay.ts pays a phone's payment link from a Wallet Toolbox testnet wallet and prints every step. Run it from packages/payments with Node.js 22, after npm install at the repository root.
- Pick a key file outside the repository:
export SPIFFYVAULT_E2E_KEY=~/.spiffyvault-e2e/testnet.key, thennode tools/e2e-pay.ts info. It prints the wallet's identity key and a funding address. - Send some 20,000 testnet satoshis to it, wait for one confirmation, then
node tools/e2e-pay.ts fund <txid>. - On a phone with a testnet build: Home, Get paid, My code, SpiffyVault, Ask for an amount, type an amount, Share link. Send the link to the computer.
- With the app open:
node tools/e2e-pay.ts pay '<link>' --dry-runchecks everything and spends nothing. Then--path live,--path offlineor--path peerpay(the link needsk).status <txid>follows any payment.
If a run ends in not-confirmed or delivery-unknown, do not pay again: the phone may hold the payment. abort <txid> releases the inputs only when you know the phone did not take it.