Developers · JavaScript

Live payments in JavaScript

@spiffyvault/payments pays SpiffyVault users from a browser, Node.js or Electron, with the same bytes on the wire as the app. It also lets a web page or a service be paid live, the way one phone pays another: the payment arrives as it happens, with no polling.

The source is at github.com/werkswinkel/spiffyvault-js. Install it with npm install @spiffyvault/payments (@spiffyvault/payments 0.3.0 on npm: a beta for review, testnet only for now). For a checkout page, the checkout widget shows the payment step for you. To see it working, open the browser wallet demo on testnet: a small wallet in a web page that pays links and is paid live by the app.

Three ways to pay

PathHowWho broadcasts
LiveA libp2p stream to the payee, through the Ricochet server's circuit relay. The payee makes an invoice and checks the payment by SPV.The payee
MailboxThe payment, sealed to the payee, waits in their Ricochet mailbox until their app collects it.The payee, when it collects
PeerPayA BRC-29 token on a message box server (BRC-100 PeerPay).The payer

Pay a link

import { RicochetClient } from '@stephanfeb/ricochet/browser';
import { SPIFFYVAULT_RICOCHET, createPaymentNode, pay } from '@spiffyvault/payments/browser';

const { node, privateKey } = await createPaymentNode();
const ricochet = new RicochetClient(node, {
  servers: [{ peerId: SPIFFYVAULT_RICOCHET.peerId, addrs: [SPIFFYVAULT_RICOCHET.wss] }],
});
const result = await pay({ link }, {
  wallet,                              // a BRC-100 WalletInterface
  libp2p: node,                        // live
  relays: [SPIFFYVAULT_RICOCHET.wss],
  ricochet,                            // mailbox, when live is not possible
  identityKey: privateKey,             // the mailbox payment is sealed from the node's key
});
// result.path is 'live', 'offline' or 'peerpay'; result.txid is the payment.

pay() tries live first, then the mailbox, but the mailbox only when nothing was handed over yet, so a payee is never paid twice. It checks the link as the app does first, including its signature and website. In Node.js, import from @spiffyvault/payments/node and use SPIFFYVAULT_RICOCHET.udxIp.

import { acceptLivePayments, createPaymentNode, formatPaymentLink, signPaymentLink }
  from '@spiffyvault/payments/browser';

// The same key every time: the link names this node's peer ID.
const { node } = await createPaymentNode({ privateKey, payee: true });
await acceptLivePayments(node, {
  network: 'testnet',
  screen: request => refuseUnlessOrder(request), // the payer sets the amount: see below
  invoiceAddress: request => addressFor(request.invoiceId), // a new address per invoice
  onPayment: payment => keep(payment),  // checked by SPV and seen on the network; then check the order
  onEvent: event => { if (event.kind === 'keep-failed') keepLater(event.payment); },
});
const link = formatPaymentLink(
  await signPaymentLink({ network: 'testnet', peerId: node.peerId.toString() }, privateKey));

For each payment, acceptLivePayments answers the app's request with an invoice, checks the payment by SPV and broadcasts it. When the network has it, it calls onPayment and tells the app it is paid. When the network has not shown it yet, it tells the app the payment is on its way, waits for the network, and only then calls onPayment. A payment the network refuses is not received.

How the app finds you: before a live payment it asks the Ricochet server for your peer ID, and dials the relay address the server gives back. The server learns that address only if your node tells it after the relay has reserved a slot for it. createPaymentNode turns that on (identify push). A js-libp2p node of your own needs identifyPush from @libp2p/identify, or the app reports it as not online.

Be paid while you are away

When the app cannot reach your node live, it pays another way: by mailbox when your link names your peer ID, or by PeerPay when it names your BRC-100 key (k). Your server collects both, as the app does, and takes the coins into a BRC-100 wallet whose identity key is your payment key:

import { acceptOfflinePayments, acceptPeerPayPayments, offlinePayeeFileStore }
  from '@spiffyvault/payments/node';

// Mailbox payments, left in your Ricochet mailbox while your node was away.
await acceptOfflinePayments({
  network: 'testnet',
  ricochet,                 // a RicochetClient on the node that runs acceptLivePayments
  identityKey: privateKey,  // that node's key
  wallet,                   // the payments go to this wallet; its identity key is the anchor
  store: offlinePayeeFileStore('offline-payee.json'),
  onPayment: async p => takeIn(p),  // on the network now
});

// PeerPay payments, from the app or any BRC-100 wallet.
await acceptPeerPayPayments({
  network: 'testnet',
  wallet,                   // its identity key is the key payers pay
  onPayment: async p => takeIn(p),  // on the network now
});

Both check each payment (it pays your wallet, the amount it claims, and SPV), make sure the network has it, and only then call onPayment. Take the coins in with the wallet's internalizeAction, using p.outputs as BRC-29 payment remittances; the Payments reference shows the call, and each payee's timers and failure rules.

Match payments to your orders

The package knows nothing of your orders. Every check that ties a payment to an order is yours, and the short examples on this page leave them out. A shop that skips them can be paid 1 sat for a 37,000 sat order.

Why: in a live payment, the payer's app sets the amount and the note. A signed link tells an honest app what to send, but nothing makes a payer follow it. acceptLivePayments invoices the amount the request asks for, and onPayment only means that amount arrived. Mailbox and PeerPay payments never pass screen at all.

On the live path, refuse a request that does not match an open order in screen, which runs before invoiceAddress. Return a reason to refuse, or nothing to invoice it:

import { refInNote } from '@spiffyvault/payments';

screen: request => {
  const order = orders.get(refInNote(request.note) ?? '');
  if (order === undefined) return 'Pay from the order’s pay screen.';
  if (order.paidTxid !== undefined) return `Order ${order.id} is paid.`;
  if (request.amountSats !== order.totalSats) return `Order ${order.id} is for ${order.totalSats} sats.`;
},

In every onPayment, live, mailbox and PeerPay, keep the coin first, then check the order again:

const order = orders.get(refInNote(p.note) ?? '');
if (order === undefined) return;                 // no order: the coin is yours; refund it if asked
if (order.paidTxid === p.txid) return;           // the same payment again
if (order.paidTxid !== undefined) return;        // paid already, by another payment: refund it
if (p.paidSats < order.totalSats) return;       // too little: refund it, or ask for the rest
order.paidTxid = p.txid;  // in your database, in the same transaction as the kept coin

The package's examples have this code as tested functions (screenOrder, orderPaid).

Run the payee safely

A payee holds hot keys: the node's key (it signs your links and website file, and opens mailbox payments), the wallet that mailbox and PeerPay payments pay, the keys behind your invoice addresses, and the mailbox store. Whoever takes the server takes the coins on it, and can sign links that send your customers' payments elsewhere.

Staying payable

Your own wallet

With a BRC-100 wallet, the package asks it for the outputs it needs. For any other wallet, pass a funder: a function that builds and signs the transaction, does not broadcast it, and returns it as BEEF. A funder keeps track of its own coins:

What you trust

A payment uses services outside your code and the payee's. None of them 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.

ServiceUsed forWhen it is down
SpiffyVault's Ricochet serverThe relay for live payments, the payee's signed records and keys, and the mailboxNo live or mailbox payments. pay() fails before anything is handed over, so nothing is spent
WhatsOnChainThe payee's SPV check of the merkle roots in a payment's proofThe payee refuses the payment as not checked; the payer keeps the coins
The BSV Association's ArcadePutting a checked payment on the network, on both networksThe payment is not broadcast, or is reported unsettled: watch the txid before handing over goods
BSVA's message boxCarrying a PeerPay token to the payeeA payment can be on the network with its token not delivered. Send the token again with deliverPeerPayToken(); do not pay again
The payee's websiteThe link's website check (/.well-known/spiffyvault.json)pay() refuses the link before anything is asked of the payee

The app finds a payee only through SpiffyVault's Ricochet server, so you cannot run your own for payments from the app yet: live and mailbox payments depend on that one server being up. PeerPay does not use it.

WhatsOnChain can say a root is in the chain when it is not, and the broadcaster can say the network has a payment when it has not. Only a block proves it: one more reason to wait for one before handing over goods of higher value. The Payments reference has the full table: what each service could do wrong, and how to use your own.

Troubleshooting

What you seeWhyWhat to do
The app says your page is not online, though the page shows it is connectedYour node did not tell the server its relay addressUse createPaymentNode, or add identifyPush
A new wallet says WhatsOnChain has no transactionIndexer lagWait a few seconds and try again
A mailbox payment is collected but never reaches the networkIts coins were spent again before the payee broadcast itHold coins until abort(); one payment at a time
The app will not pay a link with only k: no BRC-100 identity foundPeerPay needs the paying app's own BRC-100 payment keyIn the app: avatar, Identity & keys › BRC-100 payment key › Set up
A browser node fails with "Protocol 768 was unknown"The /udx address format is not registeredImport from @spiffyvault/payments/browser, which registers it

The Payments reference has the rest: how pay() chooses a path, every error and what to do with each, and the payees' limits and timers.