The short version, for everyone: Shop no. 4 in Kisumu now takes bitcoin. But a shop that accepts bitcoin needs customers who have some, and in Kisumu almost nobody does yet. This post tells the story of shop no. 4, then goes into the engineering of the other side: how someone with only M-Pesa can buy sats in the Ye₿ente wallet, and the checks that make sure the wallet can always pay out what it owes.
I set out to bring one Kisumu merchant onto bitcoin every week. We're already at four, and it has been amazing.
Shop no. 4 is Lake Basin Mall Hotel, run by Nancy. It's my favourite food spot: delicious local traditional food. My usual is fish and ugali, but if there's omena, my day is made. Today her poster went up on the wall, next to the chapati on the board.
altradits
/
altradits
YeBente is a free Bitcoin Lightning wallet for everyday people. Its AI agency now thinks with Meta Muse.
Altradits
The code behind altradits.com: free Bitcoin tools and learning for people new to Bitcoin, including Ye₿ente, a custodial Bitcoin Lightning wallet for everyday amounts, and the admin dashboard that runs the Lightning node behind it.
What lives here
-
server.mjs,api/: the website and its API (Node.js, no framework). -
lib/: shared code: wallets, Lightning, receipts, mail, security. -
yebente/: the Ye₿ente wallet app (React + Vite). The shipped build inyebente/appis committed with the source that produced it. -
assets/admin.js,admin.html: the node operator dashboard. -
test/: the test suite, including the build-stage security guard. -
docs/: manuals and guides (setup, Lightning, review process). -
deploy/,.github/: signed-merge tooling, deploy and CI.
Quick start
Requirements: Node.js 20 or newer (CI runs 24).
npm ci --ignore-scripts
cp .env.example .env
npm run dev
Open http://localhost:3000 (admin: /admin, token dev on a local machine only)…
Contents
- What Altradits is doing in Kisumu
- How shop no. 4 went
- The missing half: spenders
- Buying sats with M-Pesa: the flow
- Step 1: the quote, and every check before a prompt
- The solvency rule
- Step 2: the STK Push
- Step 3: Safaricom's callback, and why it has a secret in the path
- Step 4: when the callback never comes
- Step 5: crediting exactly once
- What the shop side looks like
- Register your shop, or sponsor the next one
- The honest part: my nightmare
What Altradits is doing in Kisumu
Altradits is my open-source bitcoin learning project. Its first product, kTown, is a QR code that lets any local shop take bitcoin and receive Kenyan shillings in M-Pesa.
- The customer scans the QR with any Lightning wallet and pays in sats.
- The shop gets shillings in M-Pesa. No new app, no exchange account, no jargon.
- A correction to what I first wrote here: the payment does not run through my own Lightning node. kTown is a thin front: the customer's sats go straight to Tando (bitcoin.co.ke), which pays the shop's M-Pesa number for a 1% fee. kTown never holds the money. The full flow is in the $1 QR post.
The community I'm building for is ordinary Kisumu: food vendors, small hotels, kiosks, and the people who buy from them. Most of them have only heard of bitcoin as a scam or a gamble. I want them to see it working at a till they already trust.
How shop no. 4 went
- The poster is made for her shop. Shop name, her own QR, "Bitcoin accepted here".
- It's laminated so it survives rain, flour and busy hands.
- I carry it across Kisumu and put it up on her wall.
- I pay first. I convert part of my own shillings into sats and buy something with the QR, so the merchant sees the money land in M-Pesa.
That demo is always the moment. Every merchant is amazed, and every one asks why more people don't use this.
The missing half: spenders
A shop that accepts bitcoin needs someone who spends it. Right now that's mostly me, with sats I bought with my own shillings.
Most people in Kisumu have M-Pesa, not bitcoin. So the first door has to be: I have shillings on my phone; give me sats. That door is the "Buy" button in Ye₿ente, the open-source Lightning wallet I build. The rest of this post is how that button works, because it is the part of the system where a bug costs real people real money.
All code is in lib/ywallet.js and api/yebente.js, pinned to commit 05a129d.
Buying sats with M-Pesa: the flow
1. User taps Buy, enters 200 KES -> server builds a quote, runs every check
2. Server sends an STK Push -> Safaricom shows a PIN prompt on the phone
3. User enters their M-Pesa PIN -> Safaricom moves the shillings
4. Safaricom posts the result -> POST /api/yebente/mpesa/callback/<secret>
(or the app asks, if it never came) -> Daraja STK query
5. Paid? -> sats credited to the wallet, exactly once
STK Push ("SIM Toolkit Push") is Safaricom's API for asking a customer to approve a payment: the user never types a till number, they just see "Pay 200 KES to … Enter PIN". It is the most familiar payment moment in Kenya, which is exactly why it's the right door.
Step 1: the quote, and every check before a prompt
A payment prompt lands on someone's phone and moves their money, so everything that could refuse the purchase is checked before the prompt is sent. quoteBuy does it in order:
export async function quoteBuy(wallet, kes) {
if (deadmanActive()) throw err("Buying sats is temporarily paused for a security check. Your sats are safe.", 503);
kes = Number(kes);
const B = buyLimits();
if (!Number.isInteger(kes) || kes < B.minKes || kes > B.maxKes) throw err(`Buy between ${B.minKes} and ${B.maxKes.toLocaleString("en-US")} KES.`);
const { btcKes, outboundSats } = await import("./lightning.js");
// The price feed is down: plain words, so a first deposit never meets a technical error.
const rate = await btcKes().catch(() => { throw err("The current price couldn't be reached. Try again in a minute.", 503); });
const sats = Math.floor((kes / rate) * 1e8 * (1 - B.spreadPct / 100));
if (sats < 1) throw err("That amount is too small.");
if (wallet.balance + (await incoming(wallet.id)) + sats > limits().maxBalance) throw err("This would take the wallet over its limit.");
...
if (bought + kes > B.dailyKes) throw err(`The daily buying limit is ${B.dailyKes.toLocaleString("en-US")} KES.`);
const outbound = await outboundSats();
const owed = (await liabilities()).sats + (await pendingBuySats());
if (outbound === null || owed + sats > outbound * 0.9) throw err("Buying is paused for now. Please try again later.", 503);
return { kes, sats, rate: Math.round(rate), spreadPct: B.spreadPct };
}
The checks, and why each exists:
| Check | Why |
|---|---|
| Dead man's switch | If a security check is in progress, nothing new comes in |
| 10 to 5,000 KES per buy (configurable) | Keeps the custodial exposure small while the wallet is young |
| Live rate, or a plain refusal | A first-time user should never see a stack trace; they see "try again in a minute" |
Math.floor on sats |
Rounding always favours the wallet's solvency, never creates sats from nothing |
| Wallet balance limit, counting pending incoming | A wallet can't be pushed over its cap by stacking unfinished buys |
| Daily limit across every rail | M-Pesa, card and the Bitika rail share one daily shilling limit, including buys still pending, so splitting a purchase across rails doesn't get around it |
| Solvency | Next section |
The rate is BTC/USD from two exchanges (Coinbase, then Kraken, the first sane answer wins, cached 5 minutes) times USD/KES (cached an hour). A spread is configurable and defaults to 0.
The solvency rule
Ye₿ente is custodial: wallet balances are ledger entries, and the bitcoin sits in my Lightning node. That creates one rule the code must never break: the node must always be able to pay out what the wallets hold. If it couldn't, the last people to withdraw would find nothing there.
So before any sats are sold:
const outbound = await outboundSats(); // what the node can send now
const owed = (await liabilities()).sats + (await pendingBuySats()); // every wallet + every unfinished buy
if (outbound === null || owed + sats > outbound * 0.9) throw err("Buying is paused for now. Please try again later.", 503);
outboundSats is the sum over active channels of local balance minus the channel reserve that Lightning never lets you spend. liabilities sums every wallet balance and also sanity-checks the ledger itself (every balance a safe non-negative integer, the total below 21 million BTC). And pendingBuySats counts buys whose prompts are still open, because those sats are already promised.
The 10% margin covers routing fees and rate movement. If the node can't be read at all (null), buying stops: "unknown" is treated as "no".
Step 2: the STK Push
The prompt itself is one Daraja call. Its password is Safaricom's scheme: base64 of shortcode, passkey and a timestamp:
const stkPassword = (ts) => Buffer.from(`${env("MPESA_SHORTCODE")}${env("MPESA_PASSKEY")}${ts}`).toString("base64");
const { ok, data } = await daraja("/mpesa/stkpush/v1/processrequest", {
BusinessShortCode: env("MPESA_SHORTCODE"), Password: stkPassword(ts), Timestamp: ts,
TransactionType: "CustomerPayBillOnline",
Amount: Math.round(Number(amount)), PartyA: formatted, PartyB: env("MPESA_SHORTCODE"), PhoneNumber: formatted,
CallBackURL: `${site()}/api/yebente/mpesa/callback/${env("YEBENTE_CALLBACK_SECRET")}`,
AccountReference: String(accountReference || "yebente").slice(0, 12),
TransactionDesc: String(transactionDesc || "Bitcoin Settlement").slice(0, 13),
});
Two rate limits sit in front of it, because a payment prompt is something that happens to a phone:
// A payment prompt lands on someone's phone: at most 5 an hour to one number, and a
// generous cap per connection (many people share one: an office, Safaricom's mobile addresses).
if ((await hit(`rl:yb:stkp:${formatted}`, 3600)) > 5) return json({ ..., error: "Too many M-Pesa prompts to this number. Try again in an hour." }, 429);
if ((await hit(`rl:yb:stk:${ipKey}`, 3600)) > 60) return json({ ..., error: "Too many M-Pesa prompts from this network. Try again later." }, 429);
Without the per-number limit, anyone could spam a stranger's phone with payment prompts. The per-network limit is generous on purpose: Safaricom's mobile data shares addresses between many customers, so a tight IP limit would block whole neighbourhoods. The IP is hashed before it becomes a key.
Only after Safaricom accepts the request is the buy recorded as pending, keyed by Safaricom's CheckoutRequestID:
export async function startBuy(wallet, quote, checkoutRequestId) {
await setJSON(`ywbuy:${checkoutRequestId}`, { walletId: wallet.id, ...quote, at: now(), state: "pending" });
await pushId("ywbuyopen", checkoutRequestId);
}
The quote is stored with it, so the sats credited later are the sats quoted, whatever the rate does in the meantime.
Step 3: Safaricom's callback, and why it has a secret in the path
When the user enters their PIN (or cancels, or ignores the prompt), Safaricom POSTs the result to the callback URL. That URL is public on the internet, so anyone could POST a fake "paid" result to it. Safaricom's STK callback carries no signature to verify, so the defence is a long random secret in the URL itself, known only to us and Safaricom:
async function callback(request, secret) {
const want = env("YEBENTE_CALLBACK_SECRET");
if (!want || secret.length !== want.length || !crypto.timingSafeEqual(Buffer.from(secret), Buffer.from(want))) {
if (want && secret) {
await recordAttack("secret_guess", { where: "/api/yebente/mpesa/callback", detail: "wrong callback secret" }).catch(() => {});
}
return json({ ResultCode: 1, ResultDesc: "Rejected" }, 403);
}
const stk = (await readBody(request))?.Body?.stkCallback;
const id = safeId(stk?.CheckoutRequestID);
if (id) {
const receipt = (stk.CallbackMetadata?.Item || []).find((i) => i?.Name === "MpesaReceiptNumber")?.Value;
await setJSON(`yb:cb:${id}`, { resultCode: stk.ResultCode, resultDesc: ..., mpesaReceiptNumber: receipt ? String(receipt) : null, at: ... });
await finishBuy(id, { resultCode: stk.ResultCode, receipt: receipt ? String(receipt) : null });
}
return json({ ResultCode: 0, ResultDesc: "Accepted" });
}
Details that matter:
-
Constant-time comparison (
timingSafeEqual, after a length check, which it requires), so the secret can't be guessed byte by byte from response times. -
Every wrong guess is logged as a
secret_guesssecurity event. - Only the result is stored: the result code, the description and the M-Pesa receipt number. The callback also contains the payer's phone number; it is deliberately not kept.
-
A
CheckoutRequestIDonly matters if we created it.finishBuylooks upywbuy:<id>; an unknown id changes nothing.
An earlier endpoint, a bare mpesa/stkpush not tied to a wallet, is switched off in the code with an honest comment: "off: it took shillings and delivered nothing (buy into a wallet instead)". Money endpoints that aren't attached to a ledger shouldn't exist.
Step 4: when the callback never comes
Callbacks get lost: a timeout, a deploy at the wrong second, a network blip between Safaricom and the server. If the wallet waited only for the callback, a user could pay and never get their sats.
So the app polls its own buy (GET wallet/buy/<id>), and while the buy is pending, the server asks Daraja directly with an STK query:
if (rec.state === "pending" && buyOn() && (await hit(`rl:yb:bq:${w.id}`, 600)) <= 60) {
// Safaricom's callback may not have arrived: ask Daraja directly.
const q = await (await stkQuery(...)).json();
if (q.success && q.resultCode !== undefined) await yw.finishBuy(buy[1], { resultCode: q.resultCode, receipt: q.mpesaReceiptNumber });
}
Only the wallet that created the buy can ask about it (rec.walletId !== w.id returns 404), and each wallet may ask at most 60 times in 10 minutes, so the app can't hammer Safaricom. "Still processing" answers from Daraja (the user hasn't entered their PIN yet) are normalised to one internal pending code, so the app keeps showing "Enter your PIN on your phone".
Step 5: crediting exactly once
Both paths, the callback and the poll, end in finishBuy:
// Safaricom's result for a buy: paid -> the sats are credited once (keyed by the
// M-Pesa receipt); cancelled or failed -> closed, nothing credited.
export async function finishBuy(checkoutRequestId, { resultCode, receipt }) {
const b = await getJSON(`ywbuy:${checkoutRequestId}`);
if (!b || b.state !== "pending") return b?.state || null;
if (String(resultCode) === "0") {
await credit({ walletId: b.walletId, sats: b.sats, kind: "buy", ref: `MPESA-${receipt || checkoutRequestId}`, counterparty: "M-Pesa", meta: { kes: b.kes } });
b.state = "paid"; b.receipt = receipt || null;
} else if (String(resultCode) !== "49") b.state = "failed";
else return "pending";
...
}
And credit itself is idempotent by reference, inside the ledger lock:
export async function credit({ walletId, sats, kind, ref, counterparty = "", meta = {} }) {
sats = Math.floor(Number(sats));
if (!(sats > 0) || !ref) throw err("Nothing to credit.");
if (!Number.isSafeInteger(sats) || sats > MAX_MONEY) throw err("That amount isn't possible."); // 2010 overflow lesson
return withLedger(async () => {
if (await getJSON(`ywref:${ref}`)) return { duplicate: true };
const w = await getJSON(`yw:${walletId}`);
w.balance += sats;
await setJSON(`yw:${w.id}`, w);
await setJSON(`ywref:${ref}`, { walletId, sats, at: now() });
await record(w.id, { kind, sats, fee: 0, counterparty, status: "completed", ref, ...meta });
return { wallet: publicWallet(w) };
});
}
Three mechanisms guard against crediting twice: the buy's own state (only a pending buy is finished), the reference record (ywref:<ref> is written once), and the ledger lock that makes each credit's check-and-write atomic. Getting exactly-once right across two independent signals (a callback and a poll) is the hardest part of this flow, and it is where I'd most like other eyes. The amount is also bounds-checked: a credit larger than all the bitcoin that can exist is refused, a nod to Bitcoin's 2010 value-overflow bug.
The card rail follows the same pattern with one extra rule worth copying: a provider's "completed" only credits if the shillings match the quote exactly, never the buyer's own words. The fiat-buy tests cover it by name: card status: Completed credits once; a repeat confirmation never pays twice, an unclear provider answer never credits, and never closes, a different amount than quoted never credits, card and M-Pesa buys share one daily shilling limit.
git clone https://github.com/altradits/altradits
cd altradits && npm install
node --test test/fiatbuy.test.mjs # 12 tests
npm test # the whole repo: 783 tests at 05a129d
What the shop side looks like
For Nancy, none of this exists. She registered at https://altradits.com/ktown/ with her M-Pesa number, her shop name and the M-Pesa name as M-Pesa shows it, and set a 6-digit PIN. Registration proves the number can receive (kTown asks the payout partner for that number's payment terms and refuses if they aren't M-Pesa shillings). When a payment arrives, her kTown app shows the shillings and the M-Pesa confirmation code, and the first matching payment marks her shop name as verified for customers.
Register your shop, or sponsor the next one
If you run a shop in Kisumu, or anywhere you have M-Pesa:
- Open https://altradits.com/ktown/
- Enter your M-Pesa number, shop name and the M-Pesa name as M-Pesa shows it, and set a 6-digit PIN.
- Your shop QR is ready. Print it, or message me and I'll bring a laminated poster.
Merchants don't pay me anything. Each QR poster costs me about $1 to make. I have no sponsor. I pay for it myself.
- Donate in sats (straight to my own node): https://altradits.com/donate.html
- Sponsor a shop onboarding: $1 covers one poster. More covers my transport and the sats I spend in the demo.
- Collaborate: if you build on Lightning, run a bitcoin community, or employ people who could be paid in bitcoin, talk to me.
- Review the code: the buy flow above handles people's shillings. Careful eyes on it are the most valuable help there is.
The honest part: my nightmare
Today was hard. I'm balancing class work, learning to contribute to open-source bitcoin projects, and looking for a paying job so I can keep this dream for Kisumu alive.
I'm not stopping. I'm using everything I have so merchants have what they need to take bitcoin.
But one question keeps me up every night: where do people in Kisumu earn bitcoin? Buying sats with M-Pesa is a door, not an economy. A shop that accepts bitcoin needs people who are paid in it.
So I need help on the other side too:
- Remote work, bounties or gigs that pay in sats
- Employers or projects willing to pay Kenyan contributors in bitcoin
- Developers and educators who want to teach people here to build and earn
It starts with one merchant and one bitcoin spender. We have four merchants. Help me find the spenders.
Not sponsored. No paid posts.
Earlier in the journey
Watch and follow
- YouTube Short: https://youtube.com/shorts/gX8zwYqfg2Q
- X thread: https://x.com/altradits/status/2120571962887913816
- LinkedIn: https://www.linkedin.com/posts/stanmobitech_bitcoin-lightning-mpesa-ugcPost-7526338080111439872-1f8q/
- Facebook: https://www.facebook.com/reel/1797704094871190
- Instagram Reel: https://www.instagram.com/reel/DfnDGNeMJvT/
- TikTok: https://www.tiktok.com/@altradits/video/7706971903646338318
Top comments (0)