The short version: Yesterday a friend had sats in Wallet of Satoshi and dinner to pay for. The service most of us in Kenya use to turn sats into M-Pesa was down, and she had no other way out. This post is the full blueprint for a second way: a Lightning to M-Pesa off-ramp you can run yourself, where a failed M-Pesa payout refunds the sats automatically. Everything here was run on a private Bitcoin network today, the code is MIT licensed, and the parts I haven't built yet are open for anyone to pick up. Not sponsored.
Contents
- Dinner, and a single point of failure
- Three ways sats become shillings
- The trick that makes it safe: hold invoices
- The architecture on one page
- Step 1: a price nobody can fake alone
- Step 2: a private Lightning network to test on
- Step 3: the hold invoice
- Step 4: paying M-Pesa with Daraja B2C
- Step 5: the state machine and the journal
- Five runs, five outcomes
- Three bugs the tests caught
- Money you need before you start: the float
- The law: Kenya's VASP Act
- Every country needs more than one exit
- When no business is available: the agent mode
- The real fix is not needing an exit
- Help build it
Dinner, and a single point of failure
Yesterday evening a friend reached out. She had sats in Wallet of Satoshi, a bill for dinner in front of her, and a restaurant that takes M-Pesa, not Lightning. Normally that is a thirty-second problem: you send the sats to a service that pays a phone number in shillings, and M-Pesa arrives.
That service was down. There was no second one she knew about. Her money was fine, sitting in her wallet, and completely useless for the next hour.
Nothing was hacked and nobody did anything wrong. Services go down. What it showed is a design problem that Bitcoin is supposed to have solved: we had rebuilt a single point of failure on top of a system that has none. Bitcoin kept running. Lightning kept running. The bridge between them and the money the restaurant accepts was one company, and when it paused, every Kenyan who needed that bridge paused with it.
I build two Bitcoin projects in Kisumu that depend on that same bridge: Ye₿ente, a wallet whose "Send Mobile" button pays M-Pesa numbers, and kTown, where shops get paid in sats and receive shillings. Both stopped being able to pay out at the same moment my friend did. So this post answers one question properly:
What would it take for anyone, in any country, to turn sats into local mobile money without depending on any single company?
The answer has three parts: a way to do it automatically (the code in this post), a way for people to do it for each other when no business is available, and the long-term way, which is not needing to do it at all.
Three ways sats become shillings
There are only three ways bitcoin becomes money a restaurant accepts. Each has a different weakness.
| Path | How it works | Single point of failure | Who can run it |
|---|---|---|---|
| Spend directly | The restaurant accepts Lightning | None, if the merchant has a wallet | Any merchant, today |
| A business pays out | You pay a Lightning invoice, a business with an M-Pesa B2C account pays your number | That business | Anyone with a B2C shortcode, float, and a licence |
| A person pays out | You pay a person, they send M-Pesa from their own line | That person, but there can be thousands | Anyone with a phone and sats |
Today almost all Kenyan cash-out goes through the middle row, and through very few businesses. The fix is not to replace one business with another. It is to make the middle row easy enough that several can exist, and to make the bottom row safe enough that it works when they all fail. The top row is the goal.
The rest of this post builds the middle row from scratch, with code you can run, then designs the bottom row.
The trick that makes it safe: hold invoices
Every off-ramp has the same frightening moment. The customer has paid sats. You have not yet paid shillings. If the shilling side fails, someone has to send the sats back, and that someone is usually a support inbox.
Lightning has a tool that removes this moment: the hold invoice.
A normal Lightning invoice settles the instant it is paid. The receiver's node knows the secret (the preimage) whose hash is in the invoice, reveals it, and the money moves.
A hold invoice is created with only the hash. When the customer pays it, the payment arrives at your node and stops there. LND reports the invoice as ACCEPTED: the sats are locked in the channel, the customer can't take them back, and you can't spend them. Then you decide:
- settle by revealing the preimage, and the sats become yours, or
- cancel, and the payment unwinds back to the customer's wallet as if it never happened.
So the off-ramp becomes simple and fair:
- Lock the customer's sats with a hold invoice.
- Pay the shillings.
- If M-Pesa confirms, settle. If M-Pesa refuses, cancel.
The customer can never lose sats to a payout that didn't happen, and you never pay shillings without the sats already locked. The same idea powers escrow in person-to-person exchanges like RoboSats, which locks the seller's sats in a hold invoice until the fiat arrives.
What stops the customer from waiting forever?A held payment has a deadline: the HTLC's CLTV expiry, in blocks. In this code the invoice asks for 144 blocks (about a day), far longer than an M-Pesa payout takes (seconds). If the node gets close to that deadline without a decision, LND cancels the payment back to protect the channel. That is why the code below never leaves a payment undecided for long: it asks M-Pesa for the status of any payout that hasn't answered within a minute.
The architecture on one page
customer wallet off-ramp LND M-Pesa (Daraja B2C) | POST /quote {phone, kes} ->| | | | |-- add HOLD invoice -------->| | |<-- invoice + sats + rate ---| | | |-- pays the invoice ------------------------------------->| ACCEPTED (locked) | | |<-- lookup: ACCEPTED -------| | | |-- journal: PAYING, then pay KES ---------------->| | |<----------------------------- result callback ---| | | ResultCode 0 -> settle (we receive the sats) | | | failure -> cancel (the sats go back) | |<-- M-Pesa receipt ----------| | | Five small files, no dependencies outside Node.js 22+:
| File | Lines | Job |
|---|---|---|
rate.mjs | 53 | The BTC/KES price from five public sources |
lnd.mjs | 47 | Hold invoices over LND's REST API |
daraja.mjs | 99 | M-Pesa B2C payout, status query, result parsing |
offramp.mjs | 169 | The state machine, journal, limits, HTTP API |
mock-daraja.mjs | 66 | A local stand-in for Safaricom's API, for testing only |
Step 1: a price nobody can fake alone
The quote is where an off-ramp is easiest to rob. If one price feed is wrong for a minute, every customer in that minute gets paid the wrong number of shillings. So the price comes from several independent sources, and the code refuses to quote when they disagree.
export const BTC_USD = { kraken: async () => Number((await get("https://api.kraken.com/0/public/Ticker?pair=XBTUSD")).result.XXBTZUSD.c[0]), coinbase: async () => Number((await get("https://api.coinbase.com/v2/prices/BTC-USD/spot")).data.amount), bitstamp: async () => Number((await get("https://www.bitstamp.net/api/v2/ticker/btcusd/")).last), }; export const USD_KES = { erapi: async () => Number((await get("https://open.er-api.com/v6/latest/USD")).rates.KES), fawaz: async () => Number((await get("https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json")).usd.kes), }; // Refuse to quote when sources are missing or disagree by more than 2%: // a wrong price is worse than no price. export async function btcKes({ minSources = 2, maxSpread = 0.02 } = {}) { /* median of each, checked */ } Here is what it returned this morning (20 Nov 2026, 01:46 UTC):
{ "btcUsd": 61928.3, "usdKes": 129.99096397, "btcKes": 8050119.414023351, "sources": { "usd": { "kraken": 61928.3, "coinbase": 61958.155, "bitstamp": 61924.34 }, "kes": { "erapi": 129.983881, "fawaz": 129.99804694 } } } The three exchanges agreed within 0.06%. One bitcoin was KSh 8,050,119. The median matters: if one exchange printed 90,000 by mistake, the median of (61,924, 61,928, 90,000) is still 61,928.
Then the sats for a payout, fee included, rounded up so the service never pays out more than it received:
export const satsFor = (kes, btcKes, feePct) => Math.ceil(Number(((kes / btcKes) * 1e8 * (1 + feePct / 100)).toFixed(6))); KSh 1,500 at that rate with a 1% fee is 18,820 sats. (The toFixed(6) is there because of a bug the tests caught; see below.)
You can, and you should add one when you can reach a Kenyan order book with an open API. The rule is the same: it becomes one more source in the median, never the only one. Single-source prices are how a quiet market at 3 a.m. turns into a bad quote.
Step 2: a private Lightning network to test on
Nothing in this post touched real money. Everything ran on regtest, a private Bitcoin network on my laptop where I mine blocks on demand. Two LND nodes play the parts:
-
wallet: the customer, standing in for my friend's Wallet of Satoshi -
svc: the off-ramp
bitcoind -regtest -datadir=$L/btc -daemon -server -txindex \ -rpcuser=lab -rpcpassword=lab -rpcport=18543 -port=18544 -fallbackfee=0.0002 for n in svc:1 wallet:2; do name=${n%%:*}; i=${n##*:} lnd --lnddir=$L/$name --bitcoin.regtest --bitcoin.node=bitcoind \ --bitcoind.rpchost=127.0.0.1:18543 --bitcoind.rpcuser=lab --bitcoind.rpcpass=lab \ --bitcoind.rpcpolling \ --rpclisten=127.0.0.1:1101$i --restlisten=127.0.0.1:809$i --listen=127.0.0.1:974$i \ --noseedbackup --alias=$name & done --bitcoind.rpcpolling lets LND follow bitcoind without ZMQ (my bitcoind build has no ZMQ). Then: mine 101 blocks, send the wallet node 1 BTC, and open a 5,000,000-sat channel from wallet to svc:
"funding_txid": "1d1e5ac74284cb43b9e1f09d81dce88a7d184c08873f46c83dcccb6a8eca7165" "active": true, "capacity": "5000000", "local_balance": "4996530", The first quote failed with
LND 404: Not Found on /v2/invoices/hodl. Hold invoices live in LND's invoicesrpc sub-server, which is only compiled in with a build tag. My LND was built from source without it. The official release binaries include it; if you build your own:go build -tags="invoicesrpc routerrpc signrpc walletrpc chainrpc" -o lnd-lab ./cmd/lnd That took 1 minute 15 seconds on an M1. If your off-ramp gets a 404 creating its first invoice, this is why.
Step 3: the hold invoice
The off-ramp talks to LND over REST with the invoice macaroon, not the admin one. That macaroon can create, settle and cancel invoices. It cannot send a single sat. If the off-ramp server is ever broken into, the attacker can't empty the node through it.
// An invoice LND will accept but not settle: the payer's sats stay locked // in the channel until we either reveal the preimage (settle) or cancel. addHold: ({ hashHex, sats, memo, expirySec, cltvExpiry }) => call("POST", "/v2/invoices/hodl", { hash: b64(hashHex), value: String(sats), memo, expiry: String(expirySec), cltv_expiry: String(cltvExpiry), }), lookup: (hashHex) => call("GET", `/v1/invoice/${hashHex}`), // OPEN, ACCEPTED, SETTLED, CANCELED settle: (preimageHex) => call("POST", "/v2/invoices/settle", { preimage: b64(preimageHex) }), cancel: (hashHex) => call("POST", "/v2/invoices/cancel", { payment_hash: b64(hashHex) }), The quote creates a fresh 32-byte secret, keeps it, and gives LND only its hash:
const preimage = crypto.randomBytes(32); const hashHex = crypto.createHash("sha256").update(preimage).digest("hex"); const inv = await lnd.addHold({ hashHex, sats, memo: `KES ${kes} to M-Pesa ${phone.slice(0, 6)}***${phone.slice(-2)}`, expirySec: 600, cltvExpiry: 144 }); The memo shows the customer what they are paying for in their own wallet, with the middle of the phone number hidden. Decoded from the customer's side:
"num_satoshis": "18820", "description": "KES 1500 to M-Pesa 254712***78", "cltv_expiry": "144", Step 4: paying M-Pesa with Daraja B2C
Safaricom's API for businesses is called Daraja. Paying a phone number is B2C (business to customer), the same API companies use for salaries and loan disbursements. Here is what you need before you can call it in production, from Safaricom's B2C documentation:
- A Daraja account and an app on developer.safaricom.co.ke, which gives you a consumer key and secret.
- A shortcode that can disburse: a Bulk Disbursement Account, or an existing paybill or till converted to "one account" that can receive and disburse.
- An initiator: an API operator created by your business administrator on the M-Pesa org portal, with a password.
- Safaricom's public certificate, to encrypt that password.
- HTTPS callback URLs that answer quickly.
The call is two steps. First an OAuth token, then the payment request. The initiator password never travels in the clear; it is RSA-encrypted with Safaricom's certificate:
const securityCredential = () => crypto.publicEncrypt( { key: fs.readFileSync(certPath), padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(initiatorPassword), ).toString("base64"); pay: ({ originatorId, phone, kes, remarks }) => post("/mpesa/b2c/v3/paymentrequest", { OriginatorConversationID: originatorId, // unique per payout, reused on retries InitiatorName: initiator, SecurityCredential: securityCredential(), CommandID: "BusinessPayment", Amount: String(kes), PartyA: shortcode, // your B2C shortcode PartyB: phone, // 2547XXXXXXXX Remarks: remarks, QueueTimeOutURL: timeoutUrl, ResultURL: resultUrl, Occassion: "offramp", // sic: Safaricom's spelling }), The API is asynchronous. The response only says "request accepted". The real answer comes later as a POST to your ResultURL:
{ "Result": { "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "OriginatorConversationID": "…", "TransactionID": "SG632NMUAB", "ResultParameters": { "ResultParameter": [ { "Key": "TransactionAmount", "Value": 10 }, { "Key": "TransactionReceipt", "Value": "SG632NMUAB" }, { "Key": "B2CUtilityAccountAvailableFunds", "Value": 8959269.60 } ] } } } ResultCode 0 is the only success. These are the failures that matter to an off-ramp, from Safaricom's table. Every one of them means no money moved, so every one of them cancels the hold invoice and refunds the customer:
| ResultCode | Meaning | What it means for you |
|---|---|---|
| 1 | Balance insufficient | Your float ran out: refill it |
| 2 / 3 | Below minimum / above maximum amount | Your limits are wrong |
| 4 | Would exceed the customer's daily limit (KSh 500,000) | Tell the customer to try tomorrow |
| 8 | Would exceed the customer's maximum balance (KSh 500,000) | Same |
| 2001 | Initiator information invalid | Wrong password or certificate |
| 2040 | Customer type can't be supported | The number has no M-Pesa account |
| 8006 | Security credential locked | Your admin must unlock the API user |
When a result never arrives (your server was down, a network blip), you ask M-Pesa with the Transaction Status API. Its answer arrives on a callback too, but in a different shape: the top-level
OriginatorConversationID is the ID of your query, and the payout it describes is named inside ResultParameters, next to TransactionStatus: "Completed" and ReceiptNo. Read the wrong one and you will match the answer to nothing, or to the wrong order. The parser handles both:if ("TransactionStatus" in params) { return { ok: Number(r.ResultCode) === 0 && params.TransactionStatus === "Completed", final: Number(r.ResultCode) === 0 && ["Completed", "Failed", "Cancelled", "Expired"].includes(params.TransactionStatus), originatorId: params.OriginatorConversationID, // the payout, not the query receipt: params.ReceiptNo || null, }; } I have not called Safaricom's live API for this post. To test without a shortcode, the repo has mock-daraja.mjs, a local stand-in built from the request and callback shapes in Safaricom's documentation. It checks the OAuth token and decrypts the initiator password with a private key, like the real service, and it can be told to succeed, run out of float, or pay without ever calling back. It exists for tests. The production client is the same daraja.mjs pointed at https://api.safaricom.co.ke.
Step 5: the state machine and the journal
This is the part that decides whether an off-ramp loses money. Every order moves through these states, and every state change is written to disk before the action it describes:
INVOICED --(customer pays)--> LOCKED --(journal first)--> PAYING --(result 0)--> PAID (settle) | |----(failure)---> REFUNDED (cancel) '--(invoice expires)--> EXPIRED '----(silence)---> ask M-Pesa for the status The two lines that matter most:
async function payout(o) { // Write PAYING first. If we crash after this line we will ask M-Pesa what // happened (status query) instead of paying a second time. save(o, { state: "PAYING" }); try { await daraja.pay({ originatorId: o.id, phone: o.phone, kes: o.kes, remarks: "Bitcoin off-ramp" }); } catch (e) { // We don't know whether M-Pesa took the request: leave it PAYING and let the status query decide. } } If the process dies before writing PAYING, nothing was sent, and paying on restart is safe. If it dies after, the restart never pays again; it asks. That ordering is the whole difference between "occasionally pays twice" and "never pays twice".
The result handler only acts on orders that are waiting for M-Pesa:
async function onResult(body) { const r = parseResult(body); const o = orders.get(r.originatorId); if (!o || !["PAYING", "LOCKED"].includes(o.state)) return; // unknown or already final if (r.ok) { await lnd.settle(o.preimageHex); save(o, { state: "PAID", receipt: r.receipt }); } else if (r.final) { await lnd.cancel(o.hashHex); save(o, { state: "REFUNDED", why: `${r.code} ${r.desc}` }); } } That guard matters for security. Your callback URL is public. Someone who forges a "success" callback for an order that is still INVOICED gets nothing, because there is nothing locked to settle. In production, also put the callback on a secret path and allow only Safaricom's published callback IP addresses.
Before any quote, three checks protect the service and the customer:
if (!phone) throw httpErr(400, "That is not a Kenyan mobile number."); if (typeof kes !== "number" || !Number.isInteger(kes) || kes < minKes || kes > maxKes) throw httpErr(400, "..."); if (paidToday(phone) + kes > dailyKesPerPhone) throw httpErr(429, "Daily limit for this number reached."); if (kes > float - reserved()) throw httpErr(503, "Not enough shillings in the payout account right now."); The last line counts shillings already promised to open orders (reserved()), so ten customers can't all be quoted the same last KSh 5,000.
Five runs, five outcomes
Every output below is copied from the terminal. The customer's wallet is the wallet node; the phone is a placeholder number.
1. A normal payout: KSh 1,500.
quote: {"state": "INVOICED", "kes": 1500, "sats": 18820, "rate": 8050119, "invoice": "lnbcrt188200n1p40lfc5pp5…"} Payment status: SUCCEEDED payinvoice returned after 2.8 s order: {"state":"PAID","kes":1500,"sats":18820,"receipt":"TCE3CAD0E5"} wallet channel balance: 4977710 -> 4958890 (change -18820) 01:49:08 [4ab0550a] INVOICED 01:49:10 [4ab0550a] LOCKED 01:49:10 [4ab0550a] PAYING [M-Pesa mock] paid KES 1500 to 254712345678, receipt TCE3CAD0E5, utility balance 18500 01:49:11 [4ab0550a] PAID receipt TCE3CAD0E5 The customer's wallet shows the payment as succeeded only after M-Pesa paid. Under three seconds, end to end.
2. M-Pesa refuses (the payout account is short): KSh 2,000.
Payment status: FAILED, reason: FAILURE_REASON_INCORRECT_PAYMENT_DETAILS order: {"state":"REFUNDED","kes":2000,"sats":25093,"receipt":null} wallet channel balance: 4958890 -> 4958890 (change 0) 01:49:16 [084fa4d2] REFUNDED (1 The balance is insufficient for the transaction.) The customer's balance changed by zero. Nobody had to email support.
3. A number with no M-Pesa account: KSh 500 to an 0733 number.
order: {"state":"REFUNDED","kes":500,"sats":6274} wallet channel balance: 4949956 -> 4949956 (change 0) REFUNDED (2040 Credit Party customer type (Unregistered or Registered Customer) can't be supported by the service.) (In the lab, the mock treats 0733 numbers as "no M-Pesa account".) See bug 1 below for why the code doesn't try to guess this from the prefix.
4. Asking for more than the float, or nonsense.
{"error": "Not enough shillings in the payout account right now. Try a smaller amount or later."} {"error": "Amount must be a whole number of shillings from 10 to 50000."} {"error": "That is not a Kenyan mobile number."} 5. The server dies in the middle of a payout. M-Pesa pays but never calls back, and I kill -9 the service while the order is PAYING:
01:50:00 [9cca4b5d] INVOICED 01:50:01 [9cca4b5d] LOCKED 01:50:01 [9cca4b5d] PAYING [M-Pesa mock] paid KES 3000 to 254712345678, receipt T7CEB4CB2F, utility balance 17000 -- service killed (kill -9) while PAYING. invoice state at LND: "state": "ACCEPTED" -- restart 01:50:06 [9cca4b5d] no result yet: asked M-Pesa for the payout's status 01:50:08 [9cca4b5d] PAID receipt T7CEB4CB2F -- payer: Payment status: SUCCEEDED -- wallet change: -37640 -- M-Pesa payouts made: 1 While the service was dead, the customer's 37,640 sats sat safely locked at the node (ACCEPTED). The restarted service read its journal, saw an order stuck in PAYING, asked M-Pesa instead of paying again, got the original receipt back, and settled. One payout, not two. The journal that made this possible:
{"id":"9cca4b5d-…","state":"INVOICED","phone":"254712345678","kes":3000,"sats":3764...