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.)
Why not use a Kenyan exchange's BTC/KES price directly?
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",
That took 1 minute 15 seconds on an M1. If your off-ramp gets a 404 creating its first invoice, this is why.The first surprise: my LND couldn't make hold invoices
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
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 |
The status query: a second shape that will trip you
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":37640,"btcKes":8050119,…}
{"id":"9cca4b5d-…","state":"LOCKED","updatedAt":"2026-11-20T01:50:01.232Z"}
{"id":"9cca4b5d-…","state":"PAYING","updatedAt":"2026-11-20T01:50:01.232Z"}
{"id":"9cca4b5d-…","state":"PAID","receipt":"T7CEB4CB2F","updatedAt":"2026-11-20T01:50:08.139Z"}
{"float":17000}
Three bugs the tests caught
The repo has ten tests that run without any Lightning node (an in-memory LND stands in). Writing them found three real bugs in the first version of this code. Each one would have cost real money.
Bug 1: an Airtel number got a quote. My first phone check assumed 07xx means Safaricom. 0733 123 456 sailed through. Worse, you can't reliably tell a network from a Kenyan prefix, because numbers move between networks. The fix is to accept any Kenyan mobile number and let M-Pesa decide: ResultCode 2040 refunds the customer automatically (run 3 above). Don't build business logic on prefixes.
Bug 2: one sat of overcharge. (10 / 8_000_000) * 1e8 is 125.00000000000001 in JavaScript, so Math.ceil charged 126 sats for a 125-sat payout. One sat is nothing, until it's on every order and someone audits you. Trimming the floating-point noise before rounding up fixed it.
Bug 3: three payouts for one order. setInterval does not wait for an async function. If an LND lookup takes longer than the interval, the next tick starts while the first is still running, both see ACCEPTED, and both pay. The test makes LND slow and runs three ticks at once. Without the fix:
✖ overlapping ticks with a slow LND pay M-Pesa once
actual: 3,
Three B2C requests for one customer. Safaricom documents OriginatorConversationID as the way to avoid double disbursement, but your safety shouldn't depend on someone else's deduplication. One line of state fixed it:
let ticking = false;
async function tick() {
if (ticking) return;
ticking = true;
try { await tickOnce(); } finally { ticking = false; }
}
✔ overlapping ticks with a slow LND pay M-Pesa once
ℹ tests 10
ℹ pass 10
ℹ fail 0
Money you need before you start: the float
An off-ramp pays shillings before it can sell the sats it receives. So it needs shillings sitting in the B2C account (Safaricom calls it the utility account) before the first customer arrives. That money is called the float, and it is the real barrier to entry, more than the code.
How big? Take your expected daily volume and the time it takes you to refill. If customers cash out KSh 200,000 a day and refilling takes a day, you need at least KSh 200,000 sitting there, plus a margin. Every successful payout tells you what's left (B2CUtilityAccountAvailableFunds in the callback), and the code keeps that number in the journal and refuses quotes it can't cover.
Refilling means turning the sats you received back into shillings: selling on an exchange, to an OTC desk, or to people who want to buy sats. In between, you hold bitcoin and its price can move. A 1% fee covers M-Pesa's own B2C charges and a little price movement. It does not cover a 10% drop in a day. Decide in advance how much bitcoin you are willing to hold, and sell down to that.
This is also why one large provider tends to win: float is expensive. Many small providers, each with a modest float and an open-source engine, is a more resilient shape than one provider with a large one.
The law: Kenya's VASP Act
I'm not a lawyer, and this section is not legal advice. It is what someone rebuilding this needs to know exists.
Exchanging bitcoin for shillings for the public is now regulated in Kenya. The Virtual Asset Service Providers Act, 2025 names the Central Bank of Kenya and the Capital Markets Authority as the regulators, and its regulations were gazetted on 22 July 2026 (Legal Notice 134), according to T&L Advocates' summary. That summary also reports:
- licence categories split between the CBK (payment token service providers, stablecoin issuers) and the CMA (exchanges, custodians, wallet providers, transfer service providers, brokers and others),
- minimum paid-up capital per category, for example KSh 10 million for a payment processor and KSh 100 million for an exchange,
- customer due diligence before onboarding and seven years of transaction records,
- and that the transitional window for existing operators closed on 4 November 2026.
What that means for this blueprint:
- The code is not the regulated part. Running it for the public is. Writing, publishing and testing open-source software is not exchanging assets. Taking strangers' sats and paying them shillings as a business is.
- Safaricom will also want a registered business, KRA compliance and its own checks before a B2C shortcode goes live.
- The hold-invoice design helps you here: you never hold a customer's funds unsettled for longer than a payout takes, and every order has a journal entry, a rate, and an M-Pesa receipt. That's the kind of record a regulator asks for.
Every country's rules differ. Before you take a single customer anywhere, talk to a lawyer who knows that country's payments and virtual-asset law.
Every country needs more than one exit
Kenya's problem yesterday isn't unique to Kenya. Wherever bitcoiners rely on one cash-out service, they share my friend's dinner problem. The engine above is deliberately split so that the mobile money side is one small adapter with three functions: pay, status, parseResult. A new country is a new adapter, not a new app.
| Country | Mobile money | Business payout API to build the adapter on |
|---|---|---|
| Kenya | M-Pesa (Safaricom) | Daraja B2C (this post) |
| Uganda, Ghana, Rwanda, Cameroon and others | MTN MoMo | MoMo API "Disbursement" product (/disbursement/v1_0/transfer) |
| Many East and Central African markets | Airtel Money | Airtel Africa's developer APIs |
| Tanzania, DRC, Mozambique | Vodacom M-Pesa | Vodacom M-Pesa Open API |
| Ethiopia | Telebirr | Ethio Telecom's partner APIs |
I've only built and tested the Kenyan adapter. The others are listed so someone in those countries can pick one up. Check each provider's current documentation and each country's law, as above.
The goal is not one off-ramp per country. It is several per country, run by different people, all speaking the same simple protocol: a Lightning address or LNURL-pay endpoint that quotes in local currency. Then a wallet like Ye₿ente can list three, check which ones answer, and route around the one that's down. That's how the internet works, and how money on top of Bitcoin should work too.
When no business is available: the agent mode
Even with several businesses, there will be nights when none of them work, or places none of them reach. Kenya already solved a version of this problem once: the M-Pesa agent, a person with a phone and some float on every corner. Bitcoin can have the same thing without anyone trusting anyone, using the same hold-invoice trick in reverse.
This part is a design, not built yet. It's the most important open task in the repo.
- The customer's app makes a secret and sends only its hash to an agent.
- The agent's wallet creates a hold invoice with that hash. The customer pays it. The sats are now locked: the agent can't take them, because only the customer knows the secret.
- The agent sends M-Pesa from their own line, an ordinary send-money.
- The customer's phone receives the M-Pesa SMS. The customer (or their app, reading the SMS) releases the secret to the agent.
- The agent settles and receives the sats.
The customer's risk is gone: no M-Pesa, no secret, and the sats return when the invoice expires. The agent's risk is a dishonest customer who receives the shillings and never releases the secret. Person-to-person exchanges deal with this with bonds: the customer locks a small extra amount that they lose if a coordinator rules against them, with the M-Pesa receipt as evidence. RoboSats has run that model for years.
What this needs: agents with wallets that support hold invoices, a small coordinator for matching and disputes (which could run over Nostr, so there's no central server to go down), and a clean mobile flow. Every one of those is a contribution someone could make.
The real fix is not needing an exit
Here is the uncomfortable part. My friend didn't need an off-ramp. She needed a restaurant that accepts sats.
Every off-ramp, including the one in this post, is a bridge back into the system Bitcoin was built to replace. Bridges are useful while the far bank is where everyone lives. They are also where the tolls, the outages, the paperwork and the permission all sit. The more people who accept bitcoin directly, the less any of that matters.
It's already happening. Afribit Kibera has onboarded around 50 merchants in Kibera, by Blink's count in March 2026. Across Africa, circular economy projects count over 700 merchants accepting bitcoin daily, according to the Adopting Bitcoin summit organisers. In South Africa, Blink's weekly brief describes Bitcoin Ekasi butchers paying millers in bitcoin. In Kisumu, that is what kTown is for.
So there are two jobs, and they go together:
- Build exits that don't depend on one company, so nobody is ever stuck with money they can't use.
- Make exits less necessary, one merchant at a time, until the day the restaurant takes Lightning and the question of cashing out never comes up.
If you run a business: accepting Lightning takes a free wallet and a printed QR code. If you're a bitcoiner: ask, every time, "Can I pay in sats?" That question is how every circular economy in Africa started.
Help build it
The code is MIT licensed:
altradits
/
offramp
A Lightning to mobile money off-ramp you can run yourself: hold invoices + M-Pesa B2C. Payout fails, sats go back.
offramp
A Lightning to mobile money off-ramp you can run yourself. Someone pays a Lightning invoice from any wallet; a phone number receives shillings on M-Pesa. If the M-Pesa payout fails, the Lightning payment is cancelled and the sats go back to the payer automatically.
This is the reference code for the article "Her sats couldn't pay for dinner: build a Bitcoin to M-Pesa off-ramp that doesn't depend on one company" on dev.to/altradits. The article explains every decision; this README is the short version.
Status: reference implementation, tested on a private regtest network and against a local stand-in for Safaricom's Daraja API. It has not paid a real shilling. Running it for the public needs a Safaricom B2C account and, in Kenya, a licence under the Virtual Asset Service Providers Act 2025. Read "Before production" below.
How it works
customer wallet off-ramp (this code) LND M-Pesa (Daraja B2C)
|…git clone https://github.com/altradits/offramp && cd offramp && npm test
Ten tests, no Lightning node needed, and CI runs them on every push. Each item below is an open issue; comment on one before you start so two people don't build the same thing. Where I'd love help, in order of impact:
- The agent mode above: hold invoices where the customer holds the secret, plus a Nostr coordinator for disputes.
- Payout adapters for other countries: MTN MoMo, Airtel Money, Vodacom M-Pesa, Telebirr. Same three functions each.
- More Lightning backends: Core Lightning and LDK Node next to LND.
- A database journal (SQLite or Postgres) next to the file journal.
-
An LNURL-pay front door, so any wallet can pay
[email protected]and get a shilling quote. -
A health-checked list of off-ramps that wallets can read and route around failures, like
lib/rails.jsin Ye₿ente already does for one partner.
And if you are a lawyer in Kenya, Uganda, Ghana or Nigeria who understands payments and virtual-asset law, a plain-language note on what a small operator needs would help more than any code.
If you're in Kisumu and want to build this in person, find me at altradits.com.
Everything in this post was run on 20 November 2026 on a private regtest network (bitcoind v29.0, LND built from source with invoicesrpc, Node.js 24.19.0, Apple M1), against a local stand-in for Daraja built from Safaricom's published documentation. No real shillings or sats moved. The price figures are live public data from the time stated. Not sponsored.
Top comments (0)