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
| Path | How | Who broadcasts |
|---|---|---|
| Live | A 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 |
| Mailbox | The payment, sealed to the payee, waits in their Ricochet mailbox until their app collects it. | The payee, when it collects |
| PeerPay | A 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.
Be paid live
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.
- Keep the coin in
onPaymentbefore it returns:payment.beefV1,payment.voutsand the invoice's key. Store it durably, and make a second call for the samepayment.txiddo nothing. - Watch for
keep-failed. WhenonPaymentthrows, the app is still told it is paid, since the payment is on the network. The event carries the whole payment, so you can keep it another way. - Hand over goods by their value.
onPaymentmeans the payment is valid and seen on the network. That is enough for goods of lower value. For goods of higher value, wait untilpayment.txidis in a block.
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.
- A payment is deleted only after
onPaymentreturns. When it throws, the payment is offered again on the next pass. Keep payments by txid: after a restart the same one can come again. - Use one node for live and mailbox payments. The payer finds your mailbox keys by the link's peer ID.
- The store holds private keys.
offlinePayeeFileStorewrites it readable by its owner only. Back it up: a payment sealed to keys you have lost cannot be opened, and the payer gets it back only after 3 days. - A payment that does not pay you, or cannot be checked or broadcast after several tries, is deleted with a
refusedornot-broadcastevent. Nothing was received, and the payer keeps or reclaims the coins.
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
- A new address for every invoice. With one address for two invoices, one transaction pays both: the payer sends it twice, and the broadcaster reports a transaction it already has as on the network. One txid pays one order.
- Keep the payment before
onPaymentreturns, with the order's new state, in one transaction. Do not hand it to a queue and return. - Make
onPaymentsafe to call twice for one txid. A mailbox or PeerPay payment can come again after a restart. - Handle
keep-failedandunsettled.keep-failed:onPaymentthrew, the payer was told it is paid, and the event carries the payment to keep another way.unsettled: the broadcaster took the payment and went quiet,onPaymenthas not run; watch the txid and mark the order paid when it is in a block. - Keep a payment that pays no order. No ref, an unknown ref, too little, or an order paid already: the coin is still yours. Refund it or ask for the rest; do not drop it.
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.
- Run the payee as its own process, apart from your web application, with only the keys it needs. Your web server asks it for payment requests and reads order state; it does not hold the keys.
- Move received coins to cold storage often, so the hot wallet holds little.
- Back up the keys and the mailbox store. A lost node key makes every link you shared dead; a payment sealed to a lost mailbox key cannot be opened.
- Wait for a block before handing over goods of higher value.
onPaymentmeans checked by SPV and seen on the network, with no confirmation yet. The SPV check takes merkle roots from WhatsOnChain by default; pass your ownchainTracker, from block headers you keep, to trust no one for that. - Answer the order status only for the browser that placed the order. A status carries the order's state and its txid.
- Publish your website file and put your website in your links, signed.
- Pin versions and run
npm auditon every upgrade. And not on mainnet yet: the package is testnet only until the outside review of its fixes is done.
Staying payable
- Keep one peer ID. Pass the same
privateKeyevery time. A new key on each page load breaks every link you shared before. - Stay connected. The relay keeps your slot only while you are connected to it. Check
isReachable(node)now and then, and dial the relay again when it is false. - Add your BRC-100 key. A closed page cannot be paid live. With your key (
k) in the link too, the app can offer to pay by PeerPay instead. A server can also collect mailbox payments (Be paid while you are away). - On the same device, link to PeerPay. A button that opens SpiffyVault on the device your page is on sends your page to the background, where a live payment cannot reach it. Give that button a link with only your BRC-100 key,
formatPaymentLink({ network, paymentKey, amountSats }), and the app pays by PeerPay straight away. That link carries no signature, since a signature needs the peer ID. Keep the signed live link for the QR code, which is scanned from another device, and check your message box when the page is visible again. - Sign the link with the node's key, so that the app refuses a changed link.
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:
- Hold the coins from the moment you build. On the live and mailbox paths the payee broadcasts, at any time after the payment leaves you; a mailbox payment waits until the payee's app collects it. Free the coins only when the package calls your
abort(). - Spend your own change before the network has it. Keep each payment and put it in the next one's BEEF as an unproven parent.
- Never forget a payment the payee may still broadcast. The next payment would spend the same coins, and one of the two payees would not be paid. Build one payment at a time: two tabs on one wallet can pick the same coins.
- Allow for indexer lag. WhatsOnChain lists a new coin a few seconds before it serves the transaction that made it. Retry before telling the user the coin is missing.
- Pay the fee. The app pays 100 satoshis per kilobyte; the payee's broadcast fails when the fee is too low.
- Expect a mailbox payment back after 3 days. A mailbox payment the payee never collects is still valid until then. The app spends its coins back to itself after 3 days, and the package asks a BRC-100 wallet to do the same (the BRC-177 label
p nosend expiry seconds 259200). A funder of your own should do likewise.
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.
| Service | Used for | When it is down |
|---|---|---|
| SpiffyVault's Ricochet server | The relay for live payments, the payee's signed records and keys, and the mailbox | No live or mailbox payments. pay() fails before anything is handed over, so nothing is spent |
| WhatsOnChain | The payee's SPV check of the merkle roots in a payment's proof | The payee refuses the payment as not checked; the payer keeps the coins |
| The BSV Association's Arcade | Putting a checked payment on the network, on both networks | The payment is not broadcast, or is reported unsettled: watch the txid before handing over goods |
| BSVA's message box | Carrying a PeerPay token to the payee | A payment can be on the network with its token not delivered. Send the token again with deliverPeerPayToken(); do not pay again |
| The payee's website | The 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 see | Why | What to do |
|---|---|---|
| The app says your page is not online, though the page shows it is connected | Your node did not tell the server its relay address | Use createPaymentNode, or add identifyPush |
| A new wallet says WhatsOnChain has no transaction | Indexer lag | Wait a few seconds and try again |
| A mailbox payment is collected but never reaches the network | Its coins were spent again before the payee broadcast it | Hold coins until abort(); one payment at a time |
The app will not pay a link with only k: no BRC-100 identity found | PeerPay needs the paying app's own BRC-100 payment key | In 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 registered | Import 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.