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:

  1. With a peer ID in the link (p): live first, if you pass libp2p.
  2. Then mailbox (offline), if you pass ricochet and identityKey (the private key of the Ricochet client's libp2p node, which createPaymentNode returns). 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.
  3. PeerPay when the link has only a key (k). After live and mailbox failed safely, only with peerPay: { 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.

StatusPathMeaning
completedliveThe phone checked the payment by SPV and the network holds it.
sentliveThe 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-offmailboxThe 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).
deliveredPeerPayYour 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 */ }
}
CodeStageMeaning
bad-link, bad-key, bare-key, own-key, network-mismatch, amount-invalid, no-routeprepareNothing was asked of anyone.
link-changedprepareThe link's signature does not match its fields (LinkChangedError): it was changed after the payee signed it. Do not pay it.
domain-refusedprepareThe 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-unreachableconnectThe payee, or the Ricochet server, could not be reached.
no-invoice, bad-invoice, anchor-missing, anchor-invalid, anchor-other-network, prekeys-*requestNo usable invoice (live), or anchor and pre-keys (mailbox). Nothing was built.
funding-failedpayThe wallet could not build it. pay() does not fall back: another path would fail the same way.
invoice-expired, frame-too-large, beef-unusablepayBuilt, then aborted before it left (aborted: true).
mailbox-refuseddeliverThe mailbox refused it; aborted.
delivery-unknowndeliverThe answer to the submission was lost. It may be in the mailbox: the inputs stay reserved.
not-confirmed, payee-refusedsettleHanded 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-refusedsettleThe 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-undeliveredpay, deliverPeerPay: 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:

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:

  1. 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;
  2. signs a reclaim of that coin back to itself, and keeps it;
  3. 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 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.

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:

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:

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:

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:

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.

ServiceUsed forWhat it could do wrongWhen it is downYour 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 mailboxSee 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 checkedNo live or mailbox payments. pay() fails before anything is handed over. A payee cannot be reachedrelays 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
WhatsOnChainThe payee's SPV check of the merkle roots in a payment's proofSay a root is in the chain when it is not, so the payee takes a payment built on coins that do not existThe payee refuses the payment as not checked; nothing is broadcast and the payer keeps the coinschainTracker: 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 thereLose a payment, or say the network has seen it when it has not. Only a block proves the network took itnot-broadcast, or unsettled: watch the txid before handing over goodsbroadcaster, or arcBroadcaster(network, { url, apiKey })
BSVA's message box (DEFAULT_MESSAGE_BOX_HOST)Carrying a PeerPay token to the payeeSee who pays whom. Drop the token, so the payee never learns of the paymentA 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 websiteThe link's website checkWhoever runs the domain can list any payee. The check proves the domain names the payee, not that the payer meant that domainpay() refuses the link with domain-refuseddomainFetch
Your walletFunding, broadcasting PeerPay payments, reclaiming uncollected mailbox paymentsWhatever its own services do (the wallet toolbox uses WhatsOnChain and a broadcaster)No payment can be builtYour 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

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.

  1. Pick a key file outside the repository: export SPIFFYVAULT_E2E_KEY=~/.spiffyvault-e2e/testnet.key, then node tools/e2e-pay.ts info. It prints the wallet's identity key and a funding address.
  2. Send some 20,000 testnet satoshis to it, wait for one confirmation, then node tools/e2e-pay.ts fund <txid>.
  3. 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.
  4. With the app open: node tools/e2e-pay.ts pay '<link>' --dry-run checks everything and spends nothing. Then --path live, --path offline or --path peerpay (the link needs k). 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.