Functions
Each exported function.
Function: marketingMetadata
- Purpose: Title, description, and the Open Graph image stay the same English sentences on every language URL. Only the canonical URL, which is also the Open Graph URL, and the reciprocal hreflang links change with the language. Filipino pages are linked with
hreflang="tl"because Google Search accepts only ISO 639-1 codes in hreflang and lists Filipino astl. The URL prefix stays/fil. - Inputs: Unprefixed path, English title, English description, and an optional locale for Home, About, Donate, and Rules.
HREFLANG_BY_LOCALEmaps each UI locale to its hreflang code (fil→tl;en,de, andesstay themselves). - Returns / side effects: Next.js
Metadata; no I/O. Localized Home, About, Donate, and Rules alternates use that map, so the Filipino alternate ishreflang="tl"with href/fil…, plusx-defaulton the unprefixed path. - Used by: Home, About, Donate, Rules, Stats, Legal, and Handbook pages.
Function: PosPage
- Purpose: App Router page for
/pos. WrapsPosScreeninAppShellandOnboardingGate screen="profile". - Inputs: None.
- Returns / side effects: The page element. No direct I/O.
- Used by: Route
/pos.
Function: PosAmountPage
- Purpose: App Router page for
/pos/amount. WrapsPosAmountinAppShellandOnboardingGate screen="profile". The top-left arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none. It does not jump to/pos. - Inputs: None.
- Returns / side effects: The page element. No direct I/O.
- Used by: Route
/pos/amount.
Function: PosScreen
- Purpose: Signed-in QR page on
/pos. RendersPosTill. - Inputs: None.
- Returns / side effects: The till card.
- Used by:
/pos.
Function: PosAmount
- Purpose: Amount-only card on
/pos/amount. Keypad and Create payment. No QR and no address. A failed till load shows the alert and Try again. A created charge, an already open (pending) charge the wallet has not seen paid, or a member who cannot charge returns to/pos. So does a charge this tab's wallet saw paid whose confirmation is not closed yet (a payment that names it, or a Lightning payment that could be its and that a read of the api then shows paid), whether the payment arrived before this page opened or while it is up (for example within the minute after the charge ran out): the till shows it full screen. A paid charge whose confirmation was closed, or one only the api reports paid without such a payment in this tab, does not block a new one. - Inputs: None. Reads the auth store.
- Returns / side effects: React element. Calls
createPosCharge. On success,returnToView('/pos', router): a step back when/posopened this page, otherwise a replace. AWalletRequiredError(apicodewallet_required) shows thepos.needWalletalert, aCannotReceiveError(apicodecannot_receive) shows Your wallet cannot receive this payment right now. Please try again later.; the other refusals keep their own catalog lines. - Used by:
PosAmountPage.
Function: PosTill
- Purpose: The QR card on
/posonly. Centered truncated 21.gifts address, the same Open CryptoPay QR as the profile card including on a smartphone, content-width Set an amount linking to/pos/amountwhen no charge is open, otherwise the open charge (countdown, including 0:00, sat amount, the currency figure stored with the charge (committedFiatFigurewith the visitor's fiat as preferred: the typed figure, else the stored snapshot in that currency; without one the current spot in the viewer's currency, not stored), and Cancel) until it is paid or a read of this session no longer returns it. A charge is paid on this till only on evidence that ties the payment to it: the moment this tab's wallet reports a received, completed payment (onPaymentReceived, before the balance is read again) that names the open charge (a payment of the api's Spark invoice of that charge, memopos:<id>, which the wallet reads asinfo.chargeId) and carries its amount (or that amount plus the fee), or when a read of the api returns the chargepaid. Amount and time alone never pay a charge: a payment that names no charge (the static sticker QR paid with the same amount, a grant or welcome payment, a payment from another member, an older invoice paid late) opens no confirmation, does not vibrate and is not recorded aspos_charge_paid_seen; the charge stays open, and the api lists such a payment underreceived, where it shows as a Received row.GET /posdoes not return the payment hashes of the BOLT11 invoices the api handed out for a charge, so a Lightning payment of the charge is confirmed by the api'spaid: while a Lightning payment that names no charge could be the open charge's (its amount, or amount plus fee, made by the wallet's own payment time, in whole seconds, from the second the charge was created up to one minute after its end, as the api still marks a payment confirmed after the end as paid), the till asksGET /pos/chargeat once and thenPAY_POLL_MS(2 s) after each ask settled, one ask at a time for a payment as every pay poll does (a newer such payment asks at once, also while an ask of the one before is still on its way), each ask a read of its own that cuts no other read off (answers are ordered byapplyRead, a failed ask is quiet), until a read shows the charge paid, cancelled or gone before its end, and at most until one minute after that payment; a newer such payment starts the asks again at once, also after they stopped. Such a payment is tied to the open charge it could be the payment of when it is heard, and to each charge a later read returns as its current charge that it could be the payment of (another tab's newer charge among them, also one that read already shows paid, but not for a payment made after the second the api marked it paid), and, when a failed create or Cancel makes a charge open again, to that charge if it heard the payment while none was open, and the till asks about those charges only. When any read shows one of them paid (also after a create or Cancel made it no longer the open one), and paid no earlier than the second of the payment, the api tied the payment to it: it counts as paid by this tab's wallet (with the api'spaidAt), as a payment that names it does, and the payment is used up, so it counts for that charge only. A charge it was not tied to never takes it, so an earlier charge still in History cannot take a payment of the open one, and a charge whose confirmation was closed takes none; an ask's answer that shows the charge paid counts so even when a read started after it answered first, as a paid charge stays paid. A Spark transfer or on-chain deposit that names no charge asks nothing. While Cancel is on its way the charge takes no payment: one reported meanwhile is kept and pays the charge only if the cancel fails; after a successful Cancel the charge stays cancelled and leaves the till at once, listed as Cancelled, even when the read after it fails (that read's error shows). When the cancel's answer is lost, the till readsGET /pos/chargeonce and makes the charge payable again (with the error) only while that read shows it open (pending) or run out (expired, when a payment made before its end or in the minute after still counts), not cancelled or paid, or when that read fails too. The till listens to the wallet from the first time a signed-in till page opens in the tab, also while the member is on other pages, so a payment that lands meanwhile still counts. What the wallet settled (the last open charge, the charges it saw paid, a lost create the api already showed paid, and the closed confirmations) is kept for the tab and the session, shared withPosAmount: closing the confirmation with Done right after the payment, while the api still returns the charge open, does not show it open again; another session starts it over. A charge that a read of this session no longer returns before its end (cancelled elsewhere), or shows paid or cancelled, stops being payable, and the till stops asking about it; one that only ran out stays open for that minute. A payment that names a charge other than the open one (for example while the till is still reading the next charge) is kept (the 20 newest by the wallet's payment time, so old payments a connection lists never push out a new one) and tried again once the next open charge is known; the 20 newest Lightning payments that name no charge are kept the same way, only to decide whether the till keeps asking the api. While a new charge is being created no charge is open: a payment reported meanwhile that names the charge before pays it at once; any other is kept and, once the new charge is read, pays it if it names it. When the api refuses a create (wallet not set up or cannot receive, amount outside the wallet range, a payment already open, no username), the charge before is open again and tries the kept payments; one it does not take stays kept. When the create's answer is lost (a network error or another failure), the till readsGET /pos/chargeonce: the charge this create made (a charge that a read right before the create did not show; when that read failed, none is taken over, with the amount requested, made no earlier than 30 seconds before the click, as the api's clock may lag, and after the one before) is taken over as the till's charge without an error, with the figure stored on it, and takes a kept payment that names it; when it is already paid, the amount page stays, because this tab's wallet did not see that payment, and the till remembers the charge for the session, so/posconfirms it even when a later read fails or no longer returns it; any other charge the read finds becomes the till's answer with the error (a pending one shows on/pos; one the api returns aspaidopens the confirmation like any api-paid charge, and closing it clears the error); the charge before is open again, with the payments kept meanwhile, unless that read shows a newer charge (created after it), open or paid, or ends the charge before, and the error shows. While a wallet-paid charge waits to be shown on/pos, the amount page shows no keypad. For a payment that names the charge, the till then showsPosPaidOverlayover the whole window, without asking the api first. The confirmation shows the currency figure stored with that charge (the till sends the typed currency and digits with the create, and the api stores and returns them); beside a charge with neither a typed figure nor a stored snapshot in the viewer's currency stands the current spot in the viewer's currency, which is not written onto the charge (docs/fiat-amounts.md). A charge the api itself returns aspaidopens the same confirmation; the newest paid charge whose confirmation is not closed yet is shown, and once it is closed the next one, so two charges paid at once both confirm; a newer open charge hides an older paid one, whose confirmation is then over. Only a charge the current session read becomes its open charge. Done closes it for that charge and clears an earlier error; it leaves the till already on screen and does not open/pos/amount; closing reads the till once, and a failure of that read shows no error once the till has had an answer; the charge stays paid on this till (no countdown, no Cancel) even while the api still returns it open, and Set an amount comes back. The till reads the api only on open, right before each create, on Try again after a failed load, when the session or the language changes, once when the open charge runs out, when the tab becomes visible again (visibilitychange), after every read of this tab's wallet (useWalletStore.syncCount: a payment it receives, each wallet sync, and the five-minute wallet refresh; quiet once the till has an answer, the same signal the/walletpayment list reloads on), after Cancel, once after a create or cancel whose answer was lost, once after a create the api refuses because a payment is already open (another tab's charge then shows), once after a payment that names a charge no read listed (quiet once the till has an answer; it shows whether another tab or device opened the charge the payment names, which then takes the payment), everyPAY_POLL_MSafter the ask before settled while a Lightning payment that names no charge could be the open charge's (quiet), and when the confirmation is closed (Done). A slower refresh cannot replace a newer create or cancel, and an older till read that answers late cannot replace a newer one. A failed read shows its error until a later read answers; one that fails after a newer read answered shows none. The read after a cancel that went through belongs to the session that cancelled and does not replace a later session's error. A till is shown only for the session that read it: a load asked for while a create or cancel is on its way runs once that ends, and another session's charge never shows. A payment of the api's Spark invoice of a charge names that charge (memopos:<id>, which the wallet reads asinfo.chargeId): with that charge's amount it pays that charge and no other, at once, also in the minute after its end and without a read; with another amount it pays none. One that names a charge the latest till answer lists other than the one on screen (an older charge, or one that ran out) pays that charge at once, unless that answer shows it paid or cancelled; the charge on screen takes it only as the open charge, so not while Cancel is on its way. A payment pays one charge only, and a wallet report that comes after its charge is paid or cancelled changes nothing. When the read right before a create already shows a charge open (made in another tab, not one this tab's wallet already paid), the till shows that charge, arms it for the wallet, and creates none. A charge this tab's wallet paid takes no further payment, even while the api still shows it open. An error belongs to the session whose read, create or cancel set it; another session never sees it. A confirmation that a newer open charge hid does not come back once that charge ends. Under the?visual=pos-receivedpin, honoured only in a Playwright build (visualPin), a payment of the open charge's Spark invoice (its amount, naming the charge) is reported throughannounceReceivedForE2eto the same wallet listener the moment the charge shows, as if the wallet had received it; under?visual=pos-received-unnamed, also only in a Playwright build, a Lightning payment of the open charge's amount that names no charge is reported the same way, which pays nothing and makes the till ask the api. No keypad on this card. The wallet does not mount this card. Without a username it shows Set a username first. linking to the address row of/settings(/settings#address). With a username but no verified in-app wallet (sparkWalletVerifiednot true), it shows thepos.needWalletlink to/wallet; if background wallet setup has exhausted its retries,WalletSetupNotereplaces that link. While setup is due or has failed, the address and QR stay hidden because the address is not registered yet, and Set an amount stays hidden; charging needs both a username and a verified wallet. - Inputs: None. Reads the auth store, till state,
onPaymentReceived,useWalletStore(syncCount), anduseWalletSetup(due,failed). - Returns / side effects: React element. Calls
fetchPosStateandcancelPosCharge. Once the till has loaded, rendersPosHistoryunder the card's other content with thehistoryand thereceivedpayments of the latest till answer, a charge this wallet saw paid already shown as paid (with the time the wallet made the payment), so the list changes with every answer the till applies and the moment the wallet sees the payment. A failed setup renders the alert and secondary Try again button fromWalletSetupNote; setup due or failed suppresses the address and QR. - Interaction log: A paid charge shown on this card is recorded as
pos_charge_paid_seenwith its id and amount, once per charge in the tab (the amount page, which never shows it, records nothing), under the session whose till read or create produced it, or, before any read, the signed-in session the wallet memory is for (dropped when that session is no longer the current one). - Used by:
PosScreen.
Function: PosPaidOverlay
- Purpose: Full-screen confirmation that a till charge was paid, so nobody at the counter can miss it. The whole window turns
app-successgreen (fixed inset-0,role="alertdialog",aria-modal, named Paid). In the middle a disc in the page colour (app-bg: white, dark in the dark theme) draws a green check inside two rings that pulse outwards, then Paid very large, the amount in bitcoin and, at the same size, the currency figure stored with that charge, or without one the current spot (fiat), and The amount has arrived in your wallet. Below, Done (focused on open). On a short window the disc, the title and both amounts are smaller, the two amounts stay the same size, and Done stays inside the window. The screen does not scroll. It closes the confirmation and leaves the till already on screen (/pos); it does not open/pos/amount. The window grows in, the check draws itself, and the rings pulse; with reduced motion the same screen shows without that movement. A phone vibrates once on open (navigator.vibratewithPOS_PAID_VIBRATION); a browser without vibration shows it silently. - Inputs:
amount(bitcoin, already formatted),fiat(the charge's stored currency figure, or without one the current spot, formatted;nullwhile there is neither),onClose(called by Done). - Returns / side effects: The dialog element. Vibrates once on mount where supported. No I/O.
- Used by:
PosTill.
Function: PosHistory
- Purpose: Past till charges under the
/posQR and charge, newest first, in the api's order; a lost create the api already showed paid stays in this list after Done even when a later read no longer returns it;PosTillmay already show a row the api still has open as paid, withpaidAtthe time the wallet made the payment (its own payment time, also for a payment kept until the charge was read). Heading History. Each row: the status (Paid ✓ with the local time it was paid, in green; Paid ✓ alone when the api sent no validpaidAt; Expired; or Cancelled), the amount in bitcoin with the currency figure stored with that charge (committedFiatFigurewith the visitor's fiat as preferred: the typed figure, else the stored snapshot in that currency; without one the current spot in the viewer's currency, not stored), and the date and time the charge was created. Payments the wallet received without a charge (received) stand in the same list by time, newest first (with no received payment the charges keep the orderPosTillgives; with one, every row is placed by its time, a charge by its creation and a payment by its arrival, a charge first on the same instant, and a charge with an unreadable time last): a greenArrowDownLeftwith Received (wallet.received), the amount in bitcoin with the current spot beside it (no figure is stored with such a payment; the spot is not written onto it), and the date and time it arrived with Instant payment (kindlightning,wallet.payment.method.lightning) or Wallet transfer (kindspark,wallet.payment.method.spark). A payment that was not in the list when it first showed eases in withanimate-fade-in, the animation of a new forum reply. The open charge is shown above the list and is left out of it. Any otherpendingrow is shown as Expired, because the api has at most one open charge and returns it ascharge. With no past charge and no received payment: No payments yet. The api returns at most its newest 20 charges; the list shows what it returns and has no paging. - Inputs:
history(PosCharge[]fromGET /pos/charge),received(PosReceived[]from the same answer, newest first), andopenChargeId(the charge shown as open above, ornull). Each charge row callscommittedFiatFigurewith the visitor's fiat as preferred; a charge row without a stored figure takes the current spot fromuseSpotRate(rateDay) throughpreferredFiatSuffix, and that figure is not written onto the charge. A received row has no stored figure and calls onlypreferredFiatSuffixwith that spot, which is not written onto it either. - Returns / side effects: A section named History. Its only I/O is the spot read of
useSpotRate(GET /fx/spot). - Used by:
PosTill.
Function: resetPosTillWriteForTests
- Purpose: Drop the module-level till write so a later test does not wait on a request the previous test left hanging.
- Inputs: None.
- Returns / side effects: Sets the in-flight write to null, empties the set of paid charges already recorded as seen in the tab, and drops what the wallet settled (open charge, wallet-paid charges, closed confirmations); it also calls the saved unsubscribe of the wallet listener and forgets it, so the next test subscribes afresh. Production clears that write when the request settles.
- Used by:
PosScreentests.
Function: fetchPosState
- Purpose:
GET /pos/chargefor the signed-in till. - Inputs: Bearer
sessionToken. - Returns / side effects:
{ charge, history, received }. A charge ispending,paid,cancelled, orexpired, withpaidAt(ISO string, ornull;nullalso when the api does not send it).chargeis the pending charge, or one paid within the last minute.receivedlists the payments the wallet received without a till charge,{ id, amountSats, receivedAt, kind }(kindlightningorspark), newest first; it is empty when the api does not send the field or sends no list, and an entry that is not a usable payment (no id, not a whole positive amount, a time that is not an ISO-8601 instant with its offset, another kind) or repeats an id is left out while the rest stay. Throws when the response is not OK orcharge/historyare not the expected JSON. - Used by:
PosTill,PosAmount.
Function: createPosCharge
- Purpose:
POST /pos/charge. When a typed pair is passed, the body is{ amountSats, amountCurrency, amount }. When it is not, the body is{ amountSats }.amountis that typed draft, so12.00stays12.00. - Inputs: Bearer
sessionToken, a whole sat amount, and an optional typed pair{ amountCurrency, amount }(amountCurrencyis USD, CHF, EUR, or PHP). - Returns / side effects: The created charge. Throws
WalletRequiredErrororCannotReceiveErroron a 400 whosecodeiswallet_requiredorcannot_receive(viathrowIfWalletAnswer), recognised by the body'scodeonly; otherwise throws with the API error string or a status fallback. Recordspos_charge_createdwith the charge id and amount. Does not recompute the stored decimal from sats or from the spot. - Used by:
PosAmount.
Function: committedFiatFigure
- Purpose: The figure a stored amount shows. When
amountCurrencyis USD, CHF, EUR, or PHP andamountis a string, that pair is the figure and the viewer's currency does not replace it. Without that pair,preferredis used only when the stored snapshot for that code is a string (an empty string counts;nulland a missing field do not).preferredomitted ornullreturnsnulleven when snapshots exist. Anullreturn means no stored figure: the caller shows the current spot beside bitcoin and does not write it back. Bitcoin stands alone only when that spot is not loaded. It never callssatsToFiatAmountand never takes a rate. - Inputs:
stored(amountCurrency,amount,amountUsd,amountChf,amountEur,amountPhp) and optionalpreferred(FiatCodeornull). - Returns / side effects:
{ code, amount }with the exact stored decimal, ornull. No I/O. - Used by:
useShopChargeFigure(the visitor's fiat),useWalletSend(a shop charge, the visitor's fiat),usePosTillState(the open and paid till charge, the visitor's fiat),PosHistory(the visitor's fiat),PayLinkScreen(ChargeFiat, the visitor's fiat),PaySheet(the viewer's fiat as preferred),preferredFiatSuffix(snapshots only, with the viewer's fiat),LoanRepayScreen(goal snapshots, with the viewer's fiat).
Function: storedTypedFiat
- Purpose: A typed
{ code, amount }as the stored pair.amountCurrencyandamountare that pair. The four snapshots stay null, so the viewer's currency is not added beside it. No figure returns undefined, and the caller then shows the current spot beside bitcoin. - Inputs:
figure({ code, amount }withcodeUSD, CHF, EUR, or PHP) orundefined. - Returns / side effects: A
StoredFiat, orundefined. No I/O. It does not read a rate and does not recompute the decimal. - Used by:
ForumPaySheet,ForumReplyPayPage,InboxScreen,PayLinkScreen.
Function: cancelPosCharge
- Purpose:
DELETE /pos/charge. - Inputs: Bearer
sessionToken. - Returns / side effects: Resolves when the open charge is cancelled. Throws otherwise.
- Used by:
PosTill.
Function: proxyPosGet
- Purpose: Same-origin proxy of api
GET /pos. - Inputs: Incoming
Request. - Returns / side effects: Upstream response.
- Used by:
GET /pos/charge.
Function: proxyPosPost
- Purpose: Same-origin proxy of api
POST /pos. - Inputs: Incoming
Request. - Returns / side effects: Upstream response.
- Used by:
POST /pos/charge.
Function: proxyPosDelete
- Purpose: Same-origin proxy of api
DELETE /pos. - Inputs: Incoming
Request. - Returns / side effects: Upstream response.
- Used by:
DELETE /pos/charge.
Function: GET
- Purpose: Shared export name for App Router GET handlers. Healthz and
/maps/keyuseexport function GET(/maps/keyis always 200{ key: string | null }); same-origin api proxies re-export unique functions asGET(including/forum/messages,/forum/messages/placeswhich re-exportsproxyMessagesPlacesGet,/forum/messages/hiddenwhich re-exportsproxyMessagesHiddenGet,/forum/notificationswhich re-exportsproxyNotificationsGet,/messages/[id]/photo,/messages/[id]/photo/[file]({1-9}.jpg),/conversations/[id]/messages/[messageId]/photo,/conversations/[id]/messages/[messageId]/photo/[file]({1-9}.{jpg|jpeg|png|webp}, proxy always requests{n}.jpgfrom the api),/messages/[id]/[file],/messages/[id]/repaymentwhich re-exportsproxyMessagesRepaymentGet,/me/loanswhich re-exportsproxyMeLoansGet,/me/previous-walletswhich re-exportsproxyMePreviousWalletsGet,/me/held-shareswhich re-exportsproxyMeHeldSharesGet,/view-key/[viewKey],/push/vapid-public,/trust/graph,/trust/proposalswhich re-exportsproxyTrustProposalsGet,/funding/applicationswhich re-exportsproxyFundingApplicationsGet,/funding/daily-rosterwhich re-exportsproxyFundingDailyRosterGet, and/funding/applications/[accountId]which callsproxyFundingApplicationGet)./translatere-exportsproxyTranslateAvailableGet(api GET/translate). HTML/messagesis the inbox page, not a GET proxy. HTML/notificationsis the notifications page, not a GET proxy. HTML/moderateis the moderation hub, not a GET proxy. HTML/moderate/hiddenis the hidden-notes page, not a GET proxy. HTML/moderate/proposalsis the confirm/reject queue, not a GET proxy. HTML/moderate/applicationsis the grant-application queue, not a GET proxy. HTML/grants/payments/commentand/grants/payments/amountsare the daily payment pages, not GET proxies. HTML/moderate/applications/[accountId]is the grant-application review, not a GET proxy. HTML/moderate/groupis the closed staff-room page, not a GET proxy./wallets/usagere-exportsproxyWalletUsageGet. The signed-in HTML page/trust-chainisTrustChainPage, not this GET.GET /l/[code]redirects an 8-hex short code or callsnotFound().GET /links/[code]re-exportsproxyShortLinkGet. HTML/posis the till page, not a GET proxy;GET /pos/chargere-exportsproxyPosGet./forum/messages/[id]/editsre-exportsproxyMessagesEditsGet. - Inputs: Incoming
Requeston proxy routes (plus asyncparamson dynamic photo,/messages/[id]/photo/[file](id+filematching{1-9}.jpg),/conversations/[id]/messages/[messageId]/photo(id+messageId),/conversations/[id]/messages/[messageId]/photo/[file](id+messageId+filematching{1-9}.{jpg|jpeg|png|webp}; proxy always requests{n}.jpgfrom the api), file, and view-key); none on healthz or/maps/key;/translatetakes the incomingRequest. - Returns / side effects:
Response. Healthz is{ status: 'ok' }200;/maps/keyis always 200{ key: string | null };/translateis 200{ available: boolean }or 502; proxies return the upstream api response (JSON or raw photo/video bytes). - Used by: Container probes, browser/wallet same-origin calls,
getMyLoansviaGET /me/loans,fetchPreviousWalletsviaGET /me/previous-wallets,fetchHeldShareBoxesviaGET /me/held-shares, andfetchTranslateAvailableviaGET /translate.GET /.well-known/nostr.jsonproxies NIP-05.GET /.well-known/lnurlp/[username]proxies LUD-16.GET /lnurlpay/[pubkey]/metadata(asyncpubkey) callsproxyLnurlpayMetadataGetfor the in-app wallet;GET /lnurlp/[username]/invoice(asyncusername, query unchanged) andGET /verify/[paymentHash](asyncpaymentHash) callproxyLnurlpInvoiceGetandproxyVerifyGetfor payers' wallets and answer withAccess-Control-Allow-Origin: *.
Function: OPTIONS
- Purpose: CORS preflight for
/.well-known/nostr.jsonand/.well-known/lnurlp/[username]. - Inputs: none.
- Returns / side effects: 204 with
Access-Control-Allow-Origin: *. - Used by: Damus NIP-05 fetch and LUD-16 payRequest preflight.
Function: isForumVideoFile
- Purpose: True when a picker file is MP4, WebM, QuickTime, or MPEG-4 video (type
video/mp4/video/webm/video/quicktime/video/x-m4v, or.mp4/.webm/.mov/.m4vname). - Inputs:
File. - Returns / side effects: boolean.
- Used by:
ForumLoaderattach control.
Function: prepareForumVideo
- Purpose: Size-check (32 MiB) and capture a first-frame JPEG poster when the browser can decode the clip. If capture fails (iPhone HEVC / Dolby Vision), still return ok with a fallback JPEG poster.
- Inputs:
File. - Returns / side effects:
{ ok: true, video }withfile, JPEGposter, andpreviewUrl; or{ ok: false, error: 'unsupported' | 'tooLarge' }. Errors are only type/name (unsupported) and oversize (tooLarge) — a failed poster capture is not an error. - Used by:
ForumLoader.
Function: postMessageVideo
- Purpose: Multipart
POST /forum/messageswithvideo+ optionalposter, optionalgoalCurrencyandgoalAmount(trimmed draft, comma stays; omitted from the form when either is missing, and on replies), optionalplaceLat/placeLng/placeLabelplusplaceStreet/placeHouseNumber/placePostalCode/placeCity/placeCountrywhen the pin has an address (place fields are top-level only; replies must not send them), and optionalshopUsername(leading@stripped; omitted when blank). NotgoalSats. - Inputs: session token,
{ text, video, poster?, goalCurrency?, goalAmount?, place?, shopUsername? }. - Returns / side effects:
ForumMessage. On 400, 404, or 429 uses the api error string when present; otherwise throwsCould not post your message. On 403 (the post needs a Bitcoin payment) throwsPostFeeRequiredErrorwithCould not post your message. - Interaction log: A created note is recorded as
post_createdwith its id,video: true, and whether it is an Ask. The text is never recorded. - Used by:
ForumLoadersubmit.
Function: forumVideoSrc
- Purpose: Build the same-origin forum video path for a message from its MIME type so playback uses
.mp4,.webm, or.movcorrectly. - Inputs:
messageIdstring and optionalcontentType(video/mp4|video/webm|video/quicktime| null | undefined). - Returns / side effects:
/messages/{id}/video.mp4|.webm|.mov(defaults to.mp4when type is missing or unknown). No I/O. - Used by:
ForumBoardplaybacksrcwhen no local preview URL is set.
Function: forumPhotoSrc
- Purpose: Build the same-origin path for a public forum still so the browser and the edge can cache it for a day. Always
.jpg; the api serves the real bytes on that name. - Inputs:
messageIdstring, optionalindex(0 or omitted or negative isphoto.jpg; 1–9 arephoto/{n}.jpg), optionalversion(a non-empty string appends?v=). - Returns / side effects: The path string. No I/O.
- Used by:
ForumBoard,QuotedForumNote,PublicMessageLoader.
Function: HandbookCopyLink
- Purpose: Client button beside a handbook heading, chapter, screen heading, or figure-card permalink. Copies
origin + pathname + #idto the clipboard, setslocation.hash, and flashes a check icon for 1.2s (textareaexecCommandfallback). - Inputs:
targetId(DOM id without#) andlabel(interpolated intohandbook.copyLinkviauseTranslationsas{ label }). Optionaltone('app' | 'dark', default'dark'). Copied Check usestext-accentwhen dark andtext-app-fgwhenapp. - Visible UI: Idle
Link2icon; copiedCheckicon. No visible "Copy link" or "Copied" text (titleandaria-labelkeep the accessible name). - Returns / side effects: A
<button type="button">. Clipboard write; hash update. No network. - Used by:
HandbookPage(page title),HandbookMarkdown(every heading),HandbookFigure,HandbookSectionHeading, andModerateHandbookScreen.
Function: HandbookMarkdown
- Purpose: Render parsed handbook markdown as Tailwind-styled headings, paragraphs, lists, links, and images. A link to an in-app path (
/…, not//…) is a client-sidenext/link; a hash or another site stays a plain anchor. Every heading has a siblingHandbookCopyLink. A paragraph whose only inline is an image becomes aHandbookFigure(thumbnail, lightbox, deep link) instead of<p><img>. - Inputs:
markdownstring andidPrefixfor heading ids. - Returns / side effects: React fragment. No network.
- Used by:
HandbookFunctionsPageandHandbookEndpointsPage.
Function: HandbookIntro
- Purpose: Server-presentational chrome for the
/handbooktitle, intro sentence, and section-navaria-label(already-translated copy). - Inputs:
title,introBefore,introAfter,navAria(already-translated strings),headingAction(node beside the h1, e.g. copy-link), andchildren(the section links). - Returns / side effects: Heading, intro with the api-handbook GitHub link, and a nav whose accessible name comes from
navAria. No network. - Used by:
HandbookPage,HandbookScreensPage,HandbookFunctionsPage,HandbookEndpointsPage.
Function: HandbookPage
- Purpose: Async Next.js hub for
/handbook. Resolves locale viagetRequestLocaleand links to/handbook/screens,/handbook/functions, and/handbook/endpointswithout dumping those markdown files. Title copy-link useshandbook.title; intro chrome via already-translated props onHandbookIntro. - Inputs: None (calls
getRequestLocale()). - Returns / side effects: The handbook hub inside
MarketingLayout. - Used by: Route
/handbook.
Function: StatsLoader
- Purpose: Client loader for
/stats. Fetches gift totals, posts, and self-reported wallet totals in onePromise.allon mount and retry, ignores stale responses after unmount, and rendersStatsDashboard. The posts and wallet fetches are tolerant: a failure hides only that section and still shows the gift stats. - Inputs: None.
- Returns / side effects: React element. Calls
fetchGiftStats,fetchPostStats, andfetchWalletStats; a gift-stats failure keeps the existing error and retry state. - Used by:
StatsPage.
Function: StatsDashboard
- Purpose: Renders gift KPIs (
formatBitcoin(totalSats)plusformatFiatDisplayof the preferred fiat fromuseFiatPreference; a null fiat total is—, notCHF 0) and SVG diagrams (cumulative spend over time and by month), plus loading/error/empty states. FiatPicker (CHF | EUR | USD | PHP) above the KPI cards only when unsigned (useHydrateSession().ready && session === null). Signed-in visitors still display and scale with the preferred code and cannot change it here. Total spend over time links each non-zero UTC day on the chart (not as a wrapping text list) to/stats/{day}with a client-sidenext/link(no prefetch). Each of Total spend over time and By month usesSegmentedControl tone="gift" shell="dark"for ₿ | {preferred FiatCode} via BarScale'btc' | 'fiat'(default ₿). Over time shows one cumulative series. Month bars rescale with the selected unit, and each label shows only that unit. A missing fiat amount on a month label is an em dash when fiat is selected. Footnote is the USD daily-close sentence, or{code} is USD at each donation's UTC-day close, converted with that day's ECB rate.for CHF/EUR/PHP. The optional Wallets section sits directly after Posts and before the gift tiles: two tiles (In wallets =formatBitcoin(totalSats)overformatFiatDisplay(satsToFiatAmount(totalSats, rateDay, fiat)), Wallets with balance =formatCount(fundedWalletCount)), the self-reported UTC-day-end caption, and a line/area chart ofbalanceOverTime[].totalSatswith ₿ ticks. The wallet fiat is the current spot fromuseSpotRate(GET /fx/spot) in the visitor's currency, not a day's price, and is omitted only while no spot is available. Each chart point's<title>is the day, ₿, and that spot fiat. The wallet chart uses the same sharedOverTimeChartdrawing as the gift chart but has no/stats/{day}links; one day draws a horizontal line and an empty series omits the Wallets section, like a failed fetch. When the section is shown, the link See how the wallet is used goes to/stats/wallet. - Inputs:
stats,error,loading,onRetry, optionalposts(null or omitted hides the Posts section), optionalwallets(null or omitted hides the Wallets section). - Returns / side effects: React element. With
posts, a Posts section shows the total and a daily bar of notes and replies by UTC day; hidden notes are not counted. Withwallets, a Wallets section shows the self-reported wallet totals, the daily chart, and the link See how the wallet is used to/stats/wallet. ReadsuseFiatPreferenceand, only when wallets are present,useSpotRate(the spot read ofGET /fx/spot). - Used by:
StatsLoader.
Function: formatCount
- Purpose: Groups a whole count for the public statistics pages (payments, wallets, forum pace) with the visitor's number-format style. It is not a bitcoin amount and has no ₿ prefix.
- Inputs:
n(whole count) andstyle(NumberFormatStyle). - Returns / side effects: Grouped decimal string from
formatGroupedNumberwith zero fraction digits. No network. - Used by:
StatsDashboard(wallets with a balance) andWalletUsageDashboard(payments, sending wallets, chart labels, and the all-flows table).
Function: OverTimeChart
- Purpose: Shared SVG line and area chart over UTC days. Gift days pass a link marker; the wallet series passes a plain marker. Empty points render a titled
role="img"with no series. A non-empty series isrole="group". The caller suppliesformatTickandrenderPoint. - Inputs:
points(OverTimePoint[]),formatTick(axis tick label),ariaLabel, andrenderPoint(required marker for oneOverTimePointLayout). - Returns / side effects: An SVG figure. Width 800, height 280, left pad 96, right 16, top 16, bottom 36. No network and no
/stats/{day}links of its own. - Used by:
StatsDashboardfor gift spend over time and the/statswallet balance, andWalletUsageDashboardfor wallets with a balance per day.
Function: StatsPage
- Purpose: Next.js page for
/stats. RendersStatsLoader. - Inputs: None.
- Returns / side effects: The statistics screen inside
MarketingLayout. RendersStatsLoader. - Used by: Route
/stats.
Function: WalletUsagePage
- Purpose: Next.js page for
/stats/wallet. Sets metadata throughmarketingMetadataand renders the marketing main frame with the heading Wallet usage andWalletUsageLoader. The server page has no second subtitle. - Inputs: None.
- Returns / side effects: The wallet-usage screen inside
MarketingLayout. No fetch of its own. - Used by: Route
/stats/wallet.
Function: WalletUsageLoader
- Purpose: Client loader for
/stats/wallet. FetchesGET /wallets/usageandGET /wallets/statstogether, ignores a late answer after unmount, and rendersWalletUsageDashboard. A failed usage fetch is one quiet error line with no retry. A failed wallet-stats fetch only hides the wallets-per-day chart. - Inputs: None.
- Returns / side effects: React element. Calls
fetchWalletUsageandfetchWalletStats. The wallet-stats rejection becomesnulland does not replace a loaded usage payload. - Used by:
WalletUsagePage.
Function: WalletUsageDashboard
- Purpose: Public body of
/stats/wallet. English copy, like/stats. Shows the release instant and as-of line, one takeaway, six KPI tiles, payments per day by purpose, forum payments before and after the release, shop till charges created and paid, payment sizes, Manila time of day (all 24 hours, UTC+8), wallets per day when wallet stats loaded, two flow diagrams with a shared DayFilterMenuand Amount/Count switch, All flows, and a closed details block How these numbers are made. Payments per day by purpose stacks payment counts: a purpose appears when its count is above 0 on any day, that count sets the scale and each segment height, and a purpose with payments of 0 sats still appears. The per-day tooltip keeps the count and the sats with the spot fiat. Below 520 px of container width each flow diagram is the stacked lists (Where from, the account with the shared-scale total, Where to); at 520 px and wider, and until that width is known, it is the SVG Sankey. All flows uses the same aggregated rows in both layouts, sorted by sats descending. From thesmbreakpoint up it is the six-column table (From, To, Purpose, Payments, Sats, Fee;hiddenbelowsm,w-full table-fixed text-xs sm:table). Belowsmit is one stacked entry per flow (sm:hidden): the same party and purpose labels as From → To · Purpose, then{count} payments · {sats} · fee {fee}. The volume tile, the Tondo fund tile, the purpose, forum and payment-size tooltips, the all-flows sats and fee figures (table cells and the stacked line), and every ribbon tooltip show ₿ with the preferred fiat fromuseSpotRatebeside it when a spot exists (₿… · fiat), or ₿ alone when it does not. A negative amount keeps that leading minus on the fiat figure of its absolute value when a spot exists. Repeated UTC days keep the first row, then run oldest first, for the balances, the DayFilterMenu, the diagrams, and the active-wallet bars. All days draws only flows whose day is in that list. Never renders a person, account, or payment id. - Inputs:
usage(WalletUsage | null),wallets(WalletStats | null),error(string | null), andloading(boolean). - Returns / side effects: React element. Reads
useNumberFormat,useFiatPreference, anduseSpotRate(the spot read runs only when usage is loaded). Day and metric stay in component state. - Used by:
WalletUsageLoader.
Function: WalletFlowDiagram
- Purpose: One account's inflows and outflows in two layouts, chosen from the container width (
ResizeObserveron the host). At 520 px and wider, and on any render before that width is known (including a measured width of 0), a three-column SVG Sankey: Where from, the account, and Where to. Below 520 px the same nodes are a compact list: Where from rows, the account node with the shared-scale total, and Where to rows. Each compact row is body text (text-sm) with the label, the selected figure, and a bar whose width is that node's share of the shared scale. Incoming groups sit on the left, or in Where from, and outgoing groups on the right, or in Where to. Each group is one party and one purpose, and the label names that party. On member wallets, Shop sales to members is only a shop purchase from members; a shop purchase from outside, the Tondo fund, or 21.gifts is its own node (Shop sales to outside, Shop sales to the Tondo fund, Shop sales to 21.gifts). Both sides share one scale, so the same payment has the same ribbon width in the SVG and the same bar width in the compact list. In count mode the scale is the larger column total and the shorter side stays shorter; fees and balances are omitted, and each row shows the payment count. In amount mode a start balance above zero is pinned to the bottom of the left side (Balance at start of day) and an end balance above zero is pinned to the bottom of the right side (Balance at end of day). A start balance below zero is pinned to the bottom of the right side (Balance below zero at start of day) with its absolute value, and an end balance below zero is pinned to the bottom of the left side (Balance below zero at end of day) with its absolute value. A start balance of exactly 0 and an end balance of exactly 0 add no row, in the SVG and in the compact list. Balance rows stay muted and last, after the payment rows on that side (fees, in amount mode only, stay in the outgoing size sort). The compact account node shows that shared total: the count in count mode, or ₿ with the preferred fiat beside it whenspotcan price it, otherwise ₿ alone. An amount-mode row shows the same bitcoin figure, with fiat beside it whenspotcan price it. An empty selection says No payments on this day and draws neither layout. Hover or focus on a ribbon or a compact row fills the same status line under the diagram, not a title attribute. Whenspotcan price the amount, that line shows the same fiat beside the bitcoin figure, including a leading minus on a negative balance; otherwise it shows bitcoin alone. - Inputs:
account(fundormembers),accountLabel,flows,startSats,endSats,metric(amountorcount),numberFormat, and optionalspot(rateDayplus the preferred fiat). - Returns / side effects: React element. The SVG and the compact list each have
role="img"witharia-labelequal toaccountLabel. The line under either layout isrole="status". No network. - Used by:
WalletUsageDashboardfor the Tondo fund and for member wallets together.
Function: accountBalances
- Purpose: Running balance of the Tondo fund or of all member wallets from the release day. The release day starts at 0. Inflow is sats arriving from another party. Outflow is sats plus fees leaving to another party. A payment from the account to itself does not move the balance. The next day starts where this day ends. Negative balances are kept.
- Inputs:
account(fundormembers),days(UTC days in order), andflows(rows for other days are ignored). - Returns / side effects: One
AccountBalanceDayper day (startSats,inflowSats,outflowSats,endSats). Empty whendaysis empty. No network. - Used by:
WalletUsageDashboardfor the fund KPI over all days and for both flow diagrams on the selected day or all days.
Function: GiftDayPage
- Purpose: Next.js page for
/stats/[day]. Invalid UTC days callnotFound(). Valid days renderDayLoader. - Inputs:
paramsPromise{ day }. - Returns / side effects: The day screen inside
MarketingLayout. - Used by: Route
/stats/[day].
Function: DayLoader
- Purpose: Client loader for
/stats/[day]. FetchesGET /gifts?day=, date input navigates, retry on error. FiatPicker on the loaded table only when unsigned (useHydrateSession().ready && session === null). The summary line is{n} donation(s) · ₿ · formatFiatDisplay(total, selected fiat, numberFormat). - Inputs:
dayUTCYYYY-MM-DD. - Returns / side effects: React element. Calls
fetchGiftDay. ReadsuseFiatPreferenceanduseNumberFormatand passes both intoGiftDayTable. - Used by:
GiftDayPage.
Function: GiftDayTable
- Purpose: Table of individual gifts on one UTC day (Time, Recipient, ₿, {FiatCode}), or empty copy No donations recorded on this day.
- Inputs:
day: GiftDay,fiat: FiatCode, and requirednumberFormat(ch/us/de) for ₿ and fiat cells. - Returns / side effects: React element. Fourth column header is the selected code; cells use
formatBitcoinandformatFiatDisplaywithnumberFormat. No network. - Used by:
DayLoader.
Function: FiatPicker
- Purpose: Four-way CHF | EUR | USD | PHP control, no ₿. Optional
shelldefault'dark'AND optionaltonedefault'gift'(unsigned stats and day). The/settingsDisplay row (FiatPreferenceSwitcher) passestone="neutral"andshell="app". RequiredariaLabel(Settings passes catalogprofile.fiatCurrency; unsigned stats and day passFiat currency). Chart scale stays a separate ₿ | selected fiat control. Unsigned stats / day mounts meanuseHydrateSession().ready && session === null, not merely a null session. Profile charts do not mount it. Forum, the public thread (PublicMessageLoader), and the pay sheet do not mount it. - Inputs:
value(FiatCode) andonChange; optionalshell('app' | 'dark', default'dark'); optionaltone('gift' | 'neutral', default'gift'); requiredariaLabel. - Returns / side effects: React element. No network.
- Used by:
FiatPreferenceSwitcher(always, signed-in/settings);StatsDashboardandDayLoaderwhen unsigned.
Function: fetchGiftDay
- Purpose: GET
/gifts?day=and parse the per-day gift list payload. - Inputs: UTC
daystring. - Returns / side effects:
GiftDay. Throws visitor copy on non-OK or invalid JSON. - Used by:
DayLoader.
Function: isUtcDay
- Purpose: Validate a UTC calendar day string
YYYY-MM-DD. - Inputs: Candidate
day. - Returns / side effects:
trueonly for a real calendar date. No I/O. - Used by:
GiftDayPage,DayLoader.
Function: proxyGiftsGet
- Purpose: Same-origin proxy helper for api
GET /gifts(forwardsday). - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: Route GET
/gifts.
Function: Home
- Purpose: Next.js page for
/. Marketing landing: pitch, how it works, why, project donate (#project, only when the build names the platform account:projectDonateAddressgives<platform username>@<request host>, the platform account's own in-app wallet address, shown as a genericlightning:link fromlightningHref, for running 21.gifts itself — distinct from/donateforum gifts; without a platform username the section is left out), FAQ, CTAs to/login(Ask for help) and/donate(Send help), plusPwaInstall(tone="dark"placement="hero") after Send help, all viatranslatefor the negotiated locale.HomeShopssits under the hero, andHappylandSectionis the place portrait. The same page is/,/en,/de,/es, and/fil. - Inputs: None. Calls
getRequestLocale()and reads the request host (x-forwarded-hostfirst, thenhost, without a port); only21.giftsand its subdomains are taken from the request, any other or missing host yields21.gifts, so a forged header cannot change the donation address. - Returns / side effects: The home screen element. Step 2 of how it works shows the example address
you@21.gifts. - Used by: Routes
/,/en,/de,/es, and/fil.
Function: writeLocaleCookie
- Purpose: Write the visitor's language into the
localecookie for one year. Shared by the language controls, account sync, and route sync so each caller stores the same attributes. - Inputs:
locale, one supported locale (en,de,es, orfil). - Returns / side effects: Sets
document.cookietolocale=<code>; Path=/; Max-Age=31536000; SameSite=Lax, and appends; Securewhen the page is HTTPS. Returns void. Does not navigate or refresh. - Used by:
LanguageSwitcher,LanguagePreferenceSwitcher,AccountPreferenceSync, andLocaleRouteSync.
Function: readLocaleCookie
- Purpose: Read the supported language stored in the
localecookie. - Inputs: None. Reads
document.cookie. - Returns / side effects: That locale when the value is exactly
en,de,es, orfil; otherwisenull(missing or unsupported). Does not write. - Used by:
LocaleRouteSyncandAccountPreferenceSync.
Function: LocaleRouteSync
- Purpose: Keep the root layout on the language of the path that is showing. Mounted once under the root provider. Renders nothing. A client navigation does not re-render the root layout, so a mismatch refreshes it. The language switcher does not do this.
- Inputs: None. Reads the pathname, the provider locale, the auth account's saved language, and the locale cookie via
readLocaleCookie. - Returns / side effects: Returns
null. On a pathname change, when the provider locale changes, and onpageshowwhenpersistedis true, a language URL whose cookie differs is stored withwriteLocaleCookiewhen the account has no saved language. On a path without a language prefix, the saved account language is stored withwriteLocaleCookiewhen the cookie differs, before refresh. The language the server should render is the URL language, otherwise the saved account language, otherwise the cookie. When that differs from the provider locale,router.refresh()runs once for that path and language; the guard is cleared as soon as the provider shows the expected language, including on the same path, so a later mismatch there refreshes again, as does a later return to the same language URL. A provider change onto the expected language does not refresh. Apageshowthat is not persisted, a plain event, a cookie that already matches, a language URL when the account has a saved language, and unmounting do not write. - Used by:
RootLayout.
Function: LanguageSwitcher
- Purpose: Custom language listbox (not a native
<select>) that persists the visitor's override in alocalecookie, stores it on the account when signed in, and either opens the localized public URL or refreshes the App Router tree. Public / unsigned chrome only (Globe pill + absolute popover). Signed-in language lives on/settings. - Inputs:
tone(darkfor marketing chrome,lightfor login, donate, unsigned/rules, unsigned/messages/[id], and/view/[viewKey]). Reads current locale viauseTranslationsand an optional session token from storage. Noembeddedprop. - Returns / side effects: Combobox + absolute popover listbox with endonym labels (English/Deutsch/Español/Filipino). With a session token, a new locale first calls
bumpLocaleGeneration(), thensetAccountLocale(token, next, false); failure, a stale generation, or a response for a different account writes no cookie and does not navigate, while success merges onlylocaleonto the current same-id account. After that successful save, the path and the target are read again from the URL as it is then. A signed-out choice keeps the path read before the click. It then callswriteLocaleCookie. Public Home, About, Donate, and Rules choices fully load the corresponding/{locale}URL, so the page, shared navigation, and footer all use the new language; other unsigned app routes callrouter.refresh(). Choosing the current language on an already localized URL is a no-op; choosing it on a legacy URL opens its stable URL. The switcher never sets the cookie on a first visit; a public language URL sets it inmiddlewarewhen the browser opens that URL as a page. The switcher does not watch the path and does not listen forpageshow.LocaleRouteSyncaligns the cookie and the rendered language for an in-app navigation and for a page restored from the back/forward cache. While a stored session is held back until its wallet is open (lockedSession), or a login is still opening its wallet, the account is not written and only the cookie changes. - Used by:
MarketingHeader(always visible),/login,/donate, unsigned/rules, unsigned/messages/[id],/view/[viewKey].
Function: LanguagePreferenceSwitcher
- Purpose: Settings Display row: uppercase
language.labelkicker andSegmentedControl tone="neutral"(default one-rowrounded-fulltrack, same as ThemeSwitcher) for English / Deutsch / Español / Filipino. Always visible on the signed-in/settingspage. Not page chrome, not a Menu disclosure. - Inputs: None. Reads current locale via
useTranslationsand an optional session token from storage. Catalog keyslanguage.label,aria.language. Option labels are native endonyms (not catalogized). - Returns / side effects: Settings row matching
PushTogglechrome. A same-locale click is a no-op. With a session token, a new locale first callsbumpLocaleGeneration(), thensetAccountLocale(token, next, false); failure, a stale generation, or a response for a different account writes no cookie and does not refresh, while success merges onlylocaleonto the current same-id account before writing the cookie and refreshing. Without a token it does not bump or POST and writes the locale cookie, includingSecureon HTTPS, then refreshes as before, while success merges onlylocaleonto the current same-id account beforewriteLocaleCookieand refreshing. Without a token it does not bump or POST and callswriteLocaleCookie. - Used by:
SettingsScreen.
Function: NumberFormatSwitcher
- Purpose: Settings Display row: uppercase
numberFormat.labelkicker andSegmentedControl tone="neutral"for the three sample labels (10'000.23/10,000.23/23.000,33), then the muted line Saved on this device (settings.deviceOnly). Always visible on the signed-in/settingspage. Not page chrome, not a Menu disclosure. - Inputs: None. Reads
numberFormat/setNumberFormatfromuseNumberFormat. Catalog keysnumberFormat.label,aria.numberFormat. Option labels are samples fromformatGroupedNumber. - Returns / side effects: Settings row matching
PushTogglechrome. Pressing an option callssetNumberFormat(cookie write viaNumberFormatProvider); the choice stays on this device. - Used by:
SettingsScreen.
Function: NameForm
- Purpose: Logged-in form to set or edit a display name. Onboarding (
variant="onboarding"): field at the top, Continue and labeled Skip at the bottom. Profile / overlay: the saved name is centered, with the pencil beside it (no Skip). OptionalbesideNameandbelowNameplace the public role and funding marks on that resting row. OptionalonSavedafter a successful save. - Inputs: Reads
useAuthStore. User input: name string. Visitor-facing copy viauseTranslations. Empty, length, control, and request failures are typed keys (name.errorEmpty,name.errorLength,name.errorControls,name.errorRequest) so they re-render after a locale change. After an empty, too-long, or control-character name, Continue/Save stays disabled while the draft still breaks that rule. A request failure leaves Continue/Save enabled. Skip stays available. - Returns / side effects: React element or
nullwhen logged out. POST/me/nameon save; POST/me/setup/skipon Skip. Mergesname,setup, andmissing. - Used by:
NameSetupon/setup/name,MemberProfileScreenon/profile,/members/:id, and/view/:viewKeywhen the signed-in account id matches, andRequirementsOverlay.
Function: LocationForm
- Purpose: Logged-in profile row to set, edit, or clear a free-text location. The resting value is centered, in the same color when it is unset, with the pencil and trash beside it.
- Inputs: Reads
useAuthStore. OptionalstartEditingopens the field on mount. User input: location string. Visitor-facing copy viauseTranslations(location.*). After a too-long value or a control character, Save stays disabled while that draft still breaks the rule. A request failure leaves Save enabled and useslocation.errorRequest. Blank after trim is a valid clear. - Returns / side effects: React element or
nullwhen logged out. POST/me/locationon save or clear. Merges onlylocationso a concurrent name write is not overwritten. - Used by:
MemberProfileScreenon/profile,/members/:id,/view/:viewKeywhen the signed-in account id matches.FundingApplyScreenrenders it in the apply walk, which every verified account with statusnoneorrejectedsees (applications are open).
Function: LocaleProvider
- Purpose: Client context provider that exposes the negotiated locale and a bound
thelper to visitor-facing components. - Inputs:
locale,messagesfor that locale, andchildren. - Returns / side effects: React provider element. No network; does not write cookies.
- Used by:
RootLayoutwraps every page; consumed viauseTranslations(see that function).
Function: NumberFormatProvider
- Purpose: Client context provider that exposes the negotiated number-format style and a setter that writes the
numberFormatcookie. Nest isLocaleProvider→NumberFormatProvider initial={numberFormat}→FiatPreferenceProvider initial={fiat}→ThemeProvider. - Inputs:
initial(NumberFormatStylefromgetRequestNumberFormat) andchildren. - Returns / side effects: React provider element.
setNumberFormatwritesnumberFormat=<id>; Path=/; Max-Age=31536000; SameSite=Laxand; Secureon HTTPS. Same-id is a no-op when the cookie is alreadych/us/de; selectingchwhile the cookie is absent still writes so the choice persists. - Used by:
RootLayoutwraps every page; consumed viauseNumberFormat(see that function).
Function: FiatPreferenceProvider
- Purpose: Client context provider that exposes the preferred fiat and a setter that writes the
fiatcookie. Nest isLocaleProvider→NumberFormatProvider→FiatPreferenceProvider initial={fiat}→ThemeProvider. - Inputs:
initial(FiatCodefromgetRequestFiat) andchildren. - Returns / side effects: React provider element. Syncs in-memory code to
initialwhen that prop changes and no valid cookie is set (locale default afterrouter.refresh()with no cookie). A validfiatcookie wins over a staleinitial.setFiatdoes not rewrite the cookie when it already equalsnext; in-memory state still syncs tonextif it is stale. Otherwise writesfiat=<code>; Path=/; Max-Age=31536000; SameSite=Laxand; Secureon HTTPS. - Used by:
RootLayoutwraps every page; consumed viauseFiatPreference.
Function: useFiatPreference
- Purpose: Reads preferred
FiatCodeandsetFiatfrom {@link FiatPreferenceProvider}. - Inputs: None (context).
- Returns / side effects:
{ fiat, setFiat }. Throws outside the provider. - Used by:
FiatPreferenceSwitcher,AccountActivityChart,ForumBoard,PublicMessageLoader,StatsDashboard,DayLoader,WalletBalance,WalletPay,WalletSend,LoansCard,LoanRepayScreen,MenuAccountHeader.
Function: FiatPreferenceSwitcher
- Purpose: Settings Display row: uppercase
profile.fiatCurrencykicker plusFiatPickershell="app"tone="neutral"(same chrome as ThemeSwitcher / NumberFormatSwitcher / LanguagePreferenceSwitcher; selected isbg-app-btn, not orange). The only signed-in control that writes thefiatcookie. Unsigned stats and day FiatPickers still write that cookie and keep defaulttone="gift". Profile charts do not mount one. - Inputs: None. Uses
useFiatPreference,useTranslations, and an optional session token from storage. - Returns / side effects: A same-fiat choice is a no-op. With a session token, a new choice first calls
bumpFiatGeneration(), thensetAccountFiat(token, next, false); failure, a stale generation, or a response for a different account does not callsetAccountorsetFiat, while success merges onlyfiatonto the current same-id account beforesetFiat. Without a token it does not bump or POST and only callssetFiat. UnsignedFiatPickerinstances remain cookie-only. - Used by:
SettingsScreen.
Function: AccountPreferenceSync
- Purpose: Reconciles nullable signed-in account locale and fiat preferences with the screen and supported preference cookies once per account id.
- Inputs: Hydrated auth
sessionandaccount, screen locale, fiat context, preference generations, and the router. - Returns / side effects: Returns
null; fills explicitnullvalues withonlyIfUnset=trueonly when the generation captured before hydration still matches, mirrors a stored fiat into its cookie even when the visible code already matches, merges only that one field onto the current account, stops when the session is gone, ignores missing keys, discards a stale response without replacing the other preference. A session whose wallet is not open in this tab yet (useWalletOpen) counts as signed out: nothing is read or written for it until the login opens the wallet, writes a differing locale throughwriteLocaleCookieand refreshes whenreadLocaleCookie()is not that language, discards a stale response without replacing the other preference. - Used by:
RootLayoutinsideFiatPreferenceProvider.
Function: bumpLocaleGeneration
- Purpose: Marks a newer explicit locale choice so older asynchronous locale work cannot overwrite it.
- Inputs: None.
- Returns / side effects: Increments and returns the module-local locale generation counter.
- Used by: Language controls before an authenticated locale POST.
Function: localeGeneration
- Purpose: Reads the current locale generation for stale-response guards.
- Inputs: None.
- Returns / side effects: Returns the module-local counter without changing it.
- Used by: Language controls and
AccountPreferenceSync.
Function: bumpFiatGeneration
- Purpose: Marks a newer explicit fiat choice so older asynchronous fiat work cannot overwrite it.
- Inputs: None.
- Returns / side effects: Increments and returns the module-local fiat generation counter.
- Used by:
FiatPreferenceSwitcherbefore an authenticated fiat POST.
Function: fiatGeneration
- Purpose: Reads the current fiat generation for stale-response guards.
- Inputs: None.
- Returns / side effects: Returns the module-local counter without changing it.
- Used by:
FiatPreferenceSwitcherandAccountPreferenceSync.
Function: parseFiatCode
- Purpose: Accept a raw cookie/option string if it is exactly one of
CHF|EUR|USD|PHP; otherwise returnfallback. - Inputs:
value(optional string) andfallback(FiatCode). - Returns / side effects: A
FiatCode. No side effects. - Used by:
getRequestFiat,FiatPreferenceProvider.
Function: getRequestFiat
- Purpose: Cookie
fiatif valid; otherwisedefaultFiatForLocale(locale). Never writes. - Inputs: Request
locale. - Returns / side effects:
FiatCodefor this request. - Used by:
RootLayout.
Function: InAppBrowserView
- Purpose: Shared escape UI when a passkey ceremony cannot run inside Telegram or another in-app browser: heading Open this page in your browser, body copy, optional iOS hint, Open in browser, and Copy link.
- Inputs: None. Uses
useTranslations,openInSystemBrowser, andorigin + pathnameas the URL to open or copy (so on/view/<key>the invite URL is used). - Returns / side effects: Fragment with the escape controls. No WebAuthn. Clipboard via
execCommand('copy')fallback thennavigator.clipboard. - Used by:
LoginCard(in-app / unsupported branch) andViewProfileClaim(same branch under the public view card).
Function: LoginCard
- Purpose: Login UI used both on
/loginand in place of a signed-in screen throughWalletLoginCard: an idle card with the single primary Log in (authenticate-first), an account-choice card after browserNotAllowedError(Log in with existing account / Open a new account), an unknown-passkey card after authenticate finishUnknown credential(headinglogin.unknownHeading, mutedlogin.unknownBody, Try again as the first control, callingpasskey.login, secondary Open a new account, and the Recover account via Social Recovery link under the buttons; dismissing the Try again login prompt stays on this card and does not open the account-choice card), preparing, error, or an in-app browser escape card viaInAppBrowserView(Open in browser + Copy link, no passkey ceremony). After success,OnboardingGateleaves/login; inWalletLoginCard, the same successful prompt refreshes the session and begins deriving the wallet phrase before the held-back screen appears. While a session is held back (lockedSession), the idle card adds the muted greetinglogin.heldGreeting(Welcome back, {name}, fromlockedName) above the heading, the muted linelogin.heldConfirm(Confirm to open your wallet) directly above Log in, and, below Log in, the muted linelogin.newHere(New to 21.gifts?) with secondary Open a new account (opens the name form without a passkey prompt); its Log in callspasskey.authenticateHeld(one prompt for the account's wallet passkey, never the account-choice card). When that prompt ends without an answer (walletPasskeyMissed) the card showslogin.heldPasskeyMissedabove Log in and the next Log in offers every passkey, and whichever passkey answers that prompt decides the account. An unknown passkey or another failure stays on this card withlogin.errorabove Log in (a refused account showslogin.wrongAccountand keeps the held session, and the next Log in clears that hint);heldProblemfromWalletLoginCardshowswallet.prfUnsupported(noPrf) orlogin.error(failed) there until the next Log in. Open a new account leaves that state for the ordinary name form and sign-up errors. Open a new account opens the name form. Passkey and account exist only after a valid name is submitted and the create ceremony is finished. Error useslogin.errorplus Try again, except a wrong-account 403 (wrongAccountor passkey error equal to that api string) which useslogin.wrongAccountwith the same layout. Try again on that hint callsclearWrongAccountthenpasskey.login(neverretry, so it cannot create another account). Generic errors still callpasskey.retry. When a new account's passkey gives no PRF output (passkey.erroriswallet.prfUnsupported), the alert iswallet.prfUnsupported(This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.) instead oflogin.error; Try again still callspasskey.retry. A dismissed prompt, a network error, or any other failure keeps its own copy. When the mounted user agent is iOS below 18, Start, Choice, and Unknown show a mutedlogin.iosVersionline (installed version and minimum iOS 18). When the mounted user agent is Android below 9, Start, Choice, and Unknown show a mutedlogin.androidVersionline (installed version and minimum Android 9). iOS is chosen when both would match. The alert is that same sentence whenpasskey.errorislogin.iosVersionorlogin.androidVersion, and the muted line is then hidden. Other errors keep their own copy and still show the muted line. The line is absent until after mount. Desktop pictures omit it. Phone pictures include it, because those baselines use an iPhone user agent below iOS 18. - Inputs: Uses
usePasskeyLogin,useAuthStore(account,lockedSession,lockedName,wrongAccount),isInAppBrowser,iosPasskeyBlock,androidPasskeyBlock, andInAppBrowserView. OptionalheldProblem(noPrf/failed/null) fromWalletLoginCard. OptionalshowRecover(defaulttrue;WalletLoginCardpassesfalse). - Returns / side effects: React element covering idle (with the held greeting, alert, and confirm line while a session is held back)/choice/unknown/name/starting/error/wrong-account/in-app. While
showRecoveris true (WalletLoginCardpasses false, because it stands in for a member session), the idle card and the held start view show Recover account via Social Recovery (recover.entry) under Log in as a quiet text link (a held session reaches this card throughWalletLoginCardtoday, so its members do not see the link) to/recover(next/link,min-h-11 text-sm text-app-muted underline), the account-choice card adds it as a secondaryButtonLinkas its third control, and the unknown-passkey card adds the same control under its buttons. Whenpasskey.recoveryPendingis set (authenticate finish answered 409recovery_pending), the error view showslogin.recoveryPendingwith Try again (passkey.retry) and the same Recover account via Social Recovery link under it, whatevershowRecoveris, because the alert names that entry and the same passkey stays refused until the recovery is finished; on the held start view (a held-back session whose Log in answered with such a passkey) the alert islogin.recoveryPendinginstead oflogin.error, with the link under Log in, because that passkey belongs to the recovery, not to the held member. A signed-in account shows the preparing spinner until redirect. Detects in-app browsers after mount; never starts WebAuthn from the in-app card. Statusclosed(apilogins_closed) oroutdated(apiapp_outdated) showsLoginBlockedNoticeinstead of every other view, also over a held-back session, which stays held. - Used by: Screen
/loginandWalletLoginCard.
Function: WalletLoginCard
- Purpose: Shows the ordinary
LoginCardin place of a signed-in screen, on that screen's existing path, while its valid stored session is held back or a fresh login is still opening the wallet in this tab. It also stands in after Log in instead on the public profile (ViewProfileClaim). - Inputs: Auth-store
sessionandlockedSession,visualPin, andfinishWalletOpen. - Returns / side effects: A
LoginCard, given the last wallet-open problem asheldProblemandshowRecover={false}(a member session stands behind it, so its account-choice and unknown-passkey views offer no Social Recovery entry, and its start view shows no quiet link, which only the/logincard has; a passkey of an unfinished social recovery still showslogin.recoveryPendingwith the entry, as on/login). After login it waits for the phrase derivation from that passkey prompt; only when another passkey signed in does wallet opening ask for the seed passkey. Success letsOnboardingGatereveal the screen and background setup proceeds independently. Failure callslockSession:noPrfshowswallet.prfUnsupported, another failure or a cancelled wallet-opening prompt showslogin.error, inside the held card above Log in. Playwright-only balance gate pins can force either alert. There is no Log out under the card: its first Log in asks only for the wallet passkey, a miss showslogin.heldPasskeyMissed, the next Log in offers every passkey and whichever passkey answers it decides the account, and a different account replaces the held session. The outcome of the last wallet open is kept per held-back session in the tab, so a card that mounts later for that session (the visitor moved to another screen) still shows its alert. - Used by:
OnboardingGate(signed-in screens and/loginwhile the wallet is not open) andViewProfileClaim(after Log in instead on the public profile).
Function: LoginPage
- Purpose: Next.js page for
/login. The visible heading lives inLoginCard(login.heading). - Inputs: None.
- Returns / side effects:
AppShellwithProfileChromeLeft(wordmarkHomeWordmark:/unsigned,/welcomewhen a session is hydrated) andLanguageSwitchertop-right, wrappingOnboardingGatearoundLoginCard. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. Signed-in visitors are sent to/setup/name,/setup/username,/setup/rules, or/welcome; with a finished setup, a safe in-app path in?next=(loginReturnPath) opens instead of/welcome. The recovery phrase is not part of that path. - Used by: Route
/login.
Function: DonatePage
- Purpose: Next.js page for
/donate,/en/donate,/de/donate,/es/donate, and/fil/donate. Guest-visible donation explainer: read a forum post, write a reaction under it with an amount, then pay from your wallet; CTA to/welcome. No address/amount form and no QR. - Inputs: None. Calls
getRequestLocale()for localized copy. - Returns / side effects:
AppShellwithProfileChromeLeft(wordmarkHomeWordmark:localizedPublicPath(locale, '/')when unsigned,/welcomewhen a session is hydrated) andLanguageSwitchertop-right; heading, lead, Open the forumButtonLink. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. No OnboardingGate. - Used by:
- **Route /donate, /en/donate, /de/donate, /es/donate, and /fil/donate - Home CTA home.ctaSend - LanguageSwitcher on /donate**
Function: RulesSetup
- Purpose: Third post-login screen: one living-room rules chapter at a time. Intermediate Continue clicks only advance the chapter. The last I agree to these rules POSTs and merges
rulesAgreedAt,setup, andmissinginto the auth-store account. - Inputs:
chapters— ordered server-renderedRulesDocumentelements (one perRULES_CHAPTER_IDSid). - Returns / side effects: Heading, prompt, progress, current chapter, error alert, full-width Continue until the last chapter, then I agree to these rules with the line By continuing you accept the Terms of Use. above it (
setup.termsBefore, anext/linkto/termslabellednav.terms,setup.termsAfter; no checkbox). Clicking that link keeps the chapter index in module memory of this tab, and the next mount reopens it once (clamped to the chapters given), so the arrow back from/termslands on the same chapter. Wordmark is a non-link span. Chapter 0 shows one arrow that returns to the previous in-app view in this tab, or/welcomewhen this tab has none, throughgoToPreviousViewwith the client-side router (no document load). Later chapters replace that arrow with the previous-chapter arrow. One arrow. Continue and Back also reset the fill inner scroller to the top. POSTs/me/rules-agreementviaagreeToRulesonly on the last chapter. Rendersnullwithout a session or whenchaptersis empty. - Used by: Screen
/setup/rules.
Function: RulesSetupPage
- Purpose: Next.js page for
/setup/rules. - Inputs: None. Calls
getRequestLocale()/getCatalogfor the rules body. - Returns / side effects: Fill
AppShell(align="start") withSignedInChrometop-right, a fallbackProfileChromeLefttop-left (shown only whileOnboardingGateshows the login card in place ofRulesSetup, whoseAppShellTopLeftarrow replaces it otherwise), andOnboardingGatearoundRulesSetup(RULES_CHAPTER_IDSmapped toRulesDocumentchapters,showNav={false},chapter={id}).RulesSetupportals the one top-left arrow: chapter 0 returns to the previous in-app view, or/welcomewhen this tab has none; later chapters reuse that slot for the previous chapter. - Used by: Route
/setup/rules.
Function: LogoutButton
- Purpose: Matching icon+text log-out inside the signed-in Menu dropdown and in the Account section of
/settings(not a free top-right action); clears the session and returns the visitor to/login. - Inputs: Active
session,useAuthStore.clearAuth,usePasskeyLogin.cancel,useRouter,disablePush, andlogLogout. - Returns / side effects: Full-width Menu-row icon+text button (same row chrome as Home / Profile / Contact). A signed-in session first switches push off (
disablePush, unsubscribe) and, at the same time, recordslogoutand sends the interaction log with that session (logLogout); each waits at most 5 s, and a failure does not block log out; a second click while this runs does nothing. Then it clears auth plus the tab phrase and callsreturnToView('/login', router). Without an active session it only clears auth and redirects. The login card of a held-back session has no log-out control. - Used by:
SignedInChromeMenu dropdown,SettingsScreen.
Function: NameSetup
- Purpose: Display-name form when
account.setup === 'name'. - Inputs: None besides
NameFormstore reads. - Returns / side effects: Heading Your name at the top and
NameForm(variant="onboarding") with Continue at the bottom of the screen. NoLogoutButton. - Used by: Screen
/setup/name.
Function: UsernameForm
- Purpose: Username field and Continue. Posts
POST /me/username. Cannot skip. Once the account's wallet is verified (sparkWalletVerified), the field shows the current username, field and Continue are disabled, and one line says the username can no longer be changed because the wallet address uses it. - Inputs: Auth store session; optional
onSaved. After an empty, invalid, or taken username, Continue stays disabled until the draft changes. A request failure leaves Continue enabled. - Returns / side effects: Taken/invalid/request stay on the form. Success updates the store and calls
onSaved. - Used by:
UsernameSetup,RequirementsOverlay,SettingsScreen(address row while no username is set).
Function: UsernameSetup
- Purpose: Post-login screen to choose the unique
@21.giftsusername. Cannot skip. The address hint is left out once the account's in-app wallet is verified (sparkWalletVerified). - Inputs: Auth store session;
UsernameForm. - Returns / side effects: Heading Your 21.gifts name, hint (left out once the wallet is verified), field, Continue. Posts
POST /me/username. Taken/invalid stay on the form. - Used by: Screen
/setup/username.
Function: UsernameSetupPage
- Purpose: Next.js page for
/setup/username. - Inputs: None.
- Returns / side effects:
AppShellwithProfileChromeLefttop-left (non-linkWordmarkspan) andSignedInChrometop-right, andOnboardingGatearoundUsernameSetup. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. - Used by: Route
/setup/username.
Function: NameSetupPage
- Purpose: Next.js page for
/setup/name. - Inputs: None.
- Returns / side effects:
AppShellwithProfileChromeLefttop-left (non-linkWordmarkspan) andSignedInChrometop-right, andOnboardingGatearoundNameSetup. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. - Used by: Route
/setup/name.
Function: openInSystemBrowser
- Purpose: Best-effort handoff from an in-app WebView to the system browser so the visitor can complete a passkey login or invite claim in Safari or Chrome.
- Inputs: Absolute
httpsloginurl, and optionalSystemBrowserHost(win; defaults toglobalThis.window). Missing window is a no-op. - Returns / side effects: On Android, sets
location.hrefto a Chrome Intent URL with an encoded fallback. Else ifTelegram.WebApp.openLinkis a function, calls it. Else on iOS Telegram (JS bridges or UATelegram), setslocation.hreftox-safari-+url. Otherwise callshost.open(url, '_blank', 'noopener,noreferrer'). No network of its own. - Used by:
InAppBrowserViewOpen in browser (viaLoginCardandViewProfileClaim), the/loginand/view/[viewKey]in-app e2e flows, and handbook coverage for those in-app variants.
Function: OnboardingGate
- Purpose: The central gate for post-login routing and wallet-open state. Signed in means the account's recovery phrase is in this tab, unless that account cannot hold a wallet; a held-back session therefore sees the login card in place of the requested signed-in screen, on the same path.
- Inputs:
screen(login/wallet/name/username/rules/welcome/profile),children, and optionalallowGuest. Members usescreen="profile"./walletand/loans/repayusescreen="wallet"./welcome,/statistics, and/habit-trackerpassallowGuest. - Returns / side effects: After hydration, returns
WalletLoginCardinstead of children whileuseWalletOpenis false for an account orlockedSessionexists; it does not redirect until the wallet is open. Then it returns children on the correct onboarding screen, otherwise a spinner whilereturnToViewfollowsnextOnboardingPath(a step back when that path is the view below, otherwise a replace). The recovery phrase and one-time wallet setup are not onboarding steps; setup may continue in the background and never holds back a new member's onboarding./walletitself stays on screen whensetupis'wallet'or the next step is/welcome. Guest-allowed screens (/welcome,/statistics,/habit-tracker) render the guest view only without any stored session; a held-back session is a member there too and getsWalletLoginCard. Profile and members stay only when the next step is/welcome. Name, username, and rules still redirect when that is the next step. Accounts that cannot hold a wallet are never held back. A signed-out visitor on a gated screen goes tologinHrefof that screen (/login?next=…, plain/loginfor the forum home). Other redirect targets are/setup/name,/setup/username,/setup/rules, or/welcome. On/logina fresh login is sent on only once its wallet is open; until then, and while a session is held back,/loginshowsWalletLoginCardin place of its own card, so a wallet that could not be opened keeps its alert there instead of landing on a guest screen. Once open, a finished setup (nextOnboardingPathis/welcome) opensloginReturnPathof the login page's query (thenextview) instead of/welcomewhen that is a safe in-app path; a missing or unsafenextkeeps/welcome, and an unfinished setup still opens its next setup step. - Used by: Screens
/login,/wallet,/loans/repay,/setup/name,/setup/username,/setup/rules,/welcome,/profile,/pos,/members/[accountId],/contact,/messages,/notifications,/moderate,/moderate/hidden,/moderate/proposals,/grants,/grants/apply,/grants/applications,/grants/applications/[accountId],/trust-chain,/shops,/statistics,/habit-tracker.
Function: WelcomeLayout
- Purpose: Segment layout for
/welcome. Publishes noindex metadata so the signed-in living room is not public search content. - Inputs:
children, the nested page. - Returns / side effects: Renders
childrenunchanged.metadata.robotsis{ index: false, follow: false }. - Used by: Route
/welcome.
Function: SignedInChrome
- Purpose: Top-right signed-in chrome: the header balance (
HeaderBalance, left of Menu: the balance, or its skeleton while the balance is on its way), the received-payment banner (ReceivedNotice), the move-funds flow (MoveFundsSheet, closed until asked for), and one icon-only Menu control (lucideMenu24px intext-app-fg, accessible namearia.menu, no visible word). While the move-funds sheet is open the Menu closes and its trigger and panel host areinert, so neither a click nor the keyboard reaches the Menu behind the sheet; the top-left arrow stays the sheet's step back. Open, the panel starts withMenuAccountHeader(photo, name, @username, balance) and a divider, then icon+label dropdown rows (Home/welcomelucideHomenav.homefirst — an unmodified primary click first clears this tab's in-app view stack withresetViewHistory, then the link opens/welcomeclient-side (no document load, so the open wallet stays); when the path is already/welcome, HomepreventDefaults, records the current/welcomepath as the only view withrecordCurrentView, and dispatchesFORUM_HOME_EVENTinstead of a no-op navigation; a modified click (Cmd, Ctrl, Shift, Alt, or another button) leaves the stack alone. The browser's own history is not touched; then Balance (/wallet, lucideWallet,wallet.balanceHeading); Shops (/shops, lucideStore,nav.shops); Point of sale (/pos, lucideBanknote,pos.nav); User Profile (/profile, lucideUser,profile.title) with no given or received amounts; Grants (/grants, lucideHandCoins,nav.grants) for every signed-in member; Account security (/security, lucideShieldCheck,nav.security); Settings (/settings, lucideSettings,nav.settings); ScrollText Living room rules/rules; Habit-Tracker (/habit-tracker, lucideListChecks,nav.habitTracker); Trust Chain; Statistics (/statistics, lucideBarChart3,nav.statistics) for every signed-in account, immediately after Trust Chain, with no unread count; Moderation (/moderate, lucideShield,nav.moderate) only whenroleAtLeast(account?.role, 'moderator')—aria-labelnav.moderateUnreadwith{ count }whenmoderationUnreadCount> 0 (staff-room unread plus open-proposal count) elsenav.moderate; visiblenav.moderateplusml-autotabular-nums count when > 0; Notifications (/notifications, lucideBell,nav.notifications, unread countml-autoonly whenunreadCount> 0,aria-labelnav.notificationsUnreadthen); Messages/messages(nav.inbox, unread countml-autoonly when inbox unread > 0,aria-labelnav.inboxUnreadthen); MessageCircle Contact/contact; optional Download Install app viaPwaInstallplacement="menu"when install is offered; LogOut log out; then a quiet Version line (app.version,getAppVersion())). On mount with a session, callsresyncPushSubscription. Clicking Notifications asks for OS permission viaenablePushwhen it is not already granted and Service Worker plusPushManagerexist (otherwise resync, which no-ops without those APIs). On the forum home (/welcome) only, whenaccount.setupis null andaccount.hasPostedis false, also mountsIntroduceYourselfOverlay; it never covers/wallet,/wallet/*,/pos*,/profile*,/messages*, the setup flow, or any other screen (Close dismisses this mount only; Write an introduction callsrequestForumCompose, so the next mount starts with the dialog dismissed). On the same screen, and only there, it mountsSocialRecoveryPromptOverlayfor a grant member (account.funding.statusadmittedortrial) whosesocialRecoverySetUpisfalse(missing on an older api shows nothing) whileaccount.setupis null and the introduce dialog is not shown: Introduce yourself comes first, and once it is closed (its Close, or Write an introduction, which also opens the writer) the prompt shows in the same visit. The prompt's own Close dismisses this mount only; it shows again on the next visit. - Inputs: Session
accountandsessionfromuseAuthStore,lockedSession, wallet-open state fromuseWalletOpen, and the path fromusePathname. The introduce overlay and the social-recovery prompt mount only on/welcome. Home clears the view stack throughresetViewHistoryandrecordCurrentView. Push resync usesresyncPushSubscription. ComposesuseUnreadCount(open)(writes the home-screen badge),PwaInstall(placement="menu", closes the Menu viaonMenuAction), andLogoutButtoninside the Menu dropdown. Renders nothing, and starts none of those reads, whilelockedSessionis set or the wallet is not open. - Returns / side effects: A
flex items-centerrow with the relative Menu button (44×44, round,hover:bg-app-hover, the same background whilearia-expandedis true;aria-expanded,aria-controls) in the AppShell page-frame header ([data-app-chrome]). The panel stays mounted. Wide (frame content box at least 576px; untilframeWidthis measured,matchMedia('(max-width: 36rem)'), and a missingmatchMediacounts as wide): it portals to the trigger parent asabsolute right-0 z-50 mt-2 w-72(18rem, not a percentage, because a percentage would resolve against the trigger). When that wide panel's bottom would pass the window, the same panel usesmt-0,px-2 py-0, and the version line usespy-0. Rows staymin-h-11. If that compact panel still passes the window and a non-negative lift keeps the bottom inside, it is afixedoverlay. Itsstylesets the measuredtop,left, andwidthso the bottom sits on the window and the top is never less than 0. Thatleftis the trigger parent's right edge minus the panel width, so a horizontal move of the frame does not keep the last inline left. It does not scroll, and it does not shorten a row. When that lift would still leave the bottom outside, the wide menu uses the same sheet as a narrow frame (w-full,html[data-menu-sheet='1'], scrolling only inside its own border) and does not use a negative top. The Menu button isrelative z-[60]only while that fixed overlay is up, so a click on Menu still closes it when the panel covers the button, and a dialog in the same header still covers Menu. A window resize or a later change in the panel's own size measures again. The panel returns tomt-2andp-2only when the compact box still has 48px of room under the window, so the two layouts do not alternate. The scrim#signed-in-menu-scrimportals to[data-menu-scrim-host]inside[data-app-frame]asabsolute inset-0 z-40 rounded-3xl(the radius is set on the scrim; the host isdisplay: contents, soinheritwould be 0). Narrow (content box under 576px): it portals to[data-menu-sheet-host](px-5, the same horizontal inset as[data-scroll-page]) inside the one scrollport asw-fulland stays in that host while closed (hidden), reads the scrollportscrollTopbefore it setshtml[data-menu-sheet='1'](which hides[data-scroll-page]), sets that scroll position to 0, and writes the saved position back after the page is shown again. Whilehtml[data-menu-sheet='1']is set, the host isheight: 100%withpadding-bottom: 1.25remand the panelmax-height: 100%, so the open sheet ends above the shell footer (Receive / Send or a page CTA) instead of running under it. While open as a sheet (narrow, or that tall wide fallback) the panel carriesdata-scrollportand is bound withbindScrollportin a layout effect, so it is the active scrollport and its last row (the Version line) scrolls into view while the page port is locked; closing releases it withreleaseScrollportand clears itsdata-scroll-active/data-scroll-lockedmarks, and the page port is active again. The panel is not wrapped inScrollport, which would bind for as long as the panel is mounted. Not a body portal.PwaInstallstays mounted via thehiddenclass when closed. When open:MenuAccountHeader(mounted with the panel, also while closed, so its data loads when the chrome mounts;tightfollows the compact wide layout; following its balance link closes the Menu) and anaria-hiddenborder-tdivider when the account is loaded or a stored session is still being checked (loadSession; signed out, neither shows), so the header holds its place in a Menu opened right after a page load, then icon+label rows: Home (/welcome, lucideHome,nav.home) first, Balance (/wallet, lucideWallet,wallet.balanceHeading), Shops (/shops, lucideStore,nav.shops), Point of sale (/pos, lucideBanknote,pos.nav), Profile link (/profile, lucideUser,profile.title) with no given or received amounts, Grants (/grants, lucideHandCoins,nav.grants) for every signed-in member, Account security (/security, lucideShieldCheck,nav.security), Settings (/settings, lucideSettings,nav.settings), Living room rules (/rules), Habit-Tracker (/habit-tracker, lucideListChecks,nav.habitTracker), Trust Chain (/trust-chain), Statistics (/statistics, lucideBarChart3,nav.statistics) for every signed-in account, immediately after Trust Chain, with no unread count, Moderation (/moderate, lucideShield,nav.moderate) only whenroleAtLeast(account?.role, 'moderator')—aria-labelnav.moderateUnreadwith{ count }whenmoderationUnreadCount> 0 (staff-room unread plus open-proposal count) elsenav.moderate; visiblenav.moderateplusml-autotabular-nums count when > 0, Notifications (/notifications, lucideBell,nav.notifications, unread count on the right when greater than zero), Messages (/messages,nav.inbox, inbox unread count on the right when greater than zero), Contact (/contact), optional Install app, and log out, then a quiet Version line (app.version,getAppVersion()). Escape always closes Menu and restores focus to Menu. LocaluseStatedismissed flags forIntroduceYourselfOverlay(initialized fromconsumeSkipIntroduceOverlay) andSocialRecoveryPromptOverlay(set by its Close); does not writeforumLawsDismissedor any account field. It renders nothing and starts none of the Menu's reads whilelockedSessionis present oruseWalletOpenis false for a wallet-backed account. - Used by:
NameSetupPage,UsernameSetupPage,RulesSetupPage,WelcomePage,ShopsPage,PosPage,ProfilePage,GrantsPage,FundingApplyPage,WalletPage,LoanRepayPage,SecurityPage,SettingsPage,MemberProfilePage,ContactPage,MessagesPage,NotificationsPage,ModeratePage,HiddenNotesPage,ProposalsPage,FundingApplicationsPage,FundingApplicationDetailPage,TrustChainPage,StatisticsPage,HabitTrackerPage,RulesPageChrome,PublicMessageChrome.
Function: HeaderBalance
- Purpose: The in-app wallet balance in the signed-in header, left of Menu, so a member sees what they hold on every signed-in screen without opening the Menu. A small right-aligned two-line text block: the ₿ figure (
formatBitcoin,text-sm font-semibold tabular-nums lining-nums) over the default fiat (satsToFiatAmount+formatFiatDisplay,text-[10px] text-app-muted; the line is left out only without a usable rate). Plain text, not a pill. - Inputs: None. Reads
useWallet(status, balance, andretrying),useSpotRate(asked only while the balance is known),useFiatPreference,useNumberFormat, anduseIncomingPayment(2400). - Returns / side effects: One
next/linkto/wallet(data-wallet-tour="balance",min-h-9,rounded-lg px-2,hover:bg-app-hover,whitespace-nowrap, ansr-onlyBalance (wallet.balanceHeading) before the figures). While the balance is on its way (the wallet isconnecting, isreadywithout a balance yet, or is aterrorwithretryingbecause it is opened again in the background), a skeleton stands in its place: adivwith the link's box (mr-1 min-h-9 px-2, right-aligned column) and two bars in the Menu's skeleton look (SKELETON_CLASSfromMenuAccountHeader:bg-app-border,animate-pulse, still with reduced motion), one in a17.5pxrow and one in a12.5pxrow, the heights of the two text lines, so the header does not move when the amount replaces it. The skeleton isaria-hidden(the screens that need the wallet announce its state themselves, so the header does not announce it a second time), carriesdata-balance-skeleton, is not a link, and does not carrydata-wallet-tour.nullwithout a wallet (disabled) and after a failure that is not retried (the setup note's case). For 2.4 s after a received payment completes while the app is open, the block istext-app-successand anaria-hiddentext-[10px]line under it shows+plusformatBitcoin(+₿500) plus the current spot beside it, and bitcoin alone on that line only when the spot is not loaded. No network of its own. - Used by:
SignedInChrome.
Function: MenuAccountHeader
- Purpose: The card at the top of the signed-in Menu. First row: the profile photo (
h-10 w-10round) or, without one, the first letter of the name (else of the username) in a roundbg-app-borderbadge; the display name (text-smsemibold) and@username(text-xsmuted), both truncated. The photo or initial and the name block are together onenext/linkto/profile(the same target as the Menu's Profile row) that closes the Menu: its accessible name starts withnav.openProfile(Open your profile) from asr-onlyspan, followed by the name and@username; the photo inside it has an emptyaltand the initial isaria-hidden. The link is at least 44px tall (min-h-11), and negative margins keep the row at the photo's 40px, so the card does not grow; focus uses the shared:focus-visiblering and hoverbg-app-hover. It is not nested with the balance link. And in the right corner the wallet balance small: theformatBitcoinamount (text-basesemibold) over the default-fiat amount (text-xsmuted, empty only without a usable rate), right-aligned and never wrapping, as anext/linkto/walletthat closes the Menu. While the wallet connects (or is ready without a balance) the corner holds two skeleton bars of the same size (role="status", accessible namewallet.connecting); error or no wallet show nothing there. A wallet that is not open in this tab never reaches the Menu: the central gate shows the login card instead. There is no row of Received, Given, or post totals. WhensummarizeLoansreports a payable amount, arounded-lg bg-app-cardrow under the first row (gap-3) says Loan repayment due today or the danger-colour You're behind on your loan, shows the storeddefinedDueLabel(..., 'payable')figures followed by the payable bitcoin when every payable loan was defined in fiat, with each currency summed and joined in first-seen order (for example ₱30.00 + $3.00 · ₿1'000), otherwise bitcoin and the current spot (formatBitcoinpluspreferredFiatSuffix, bitcoin alone only when the spot is not loaded), and has Send to/loans/repay;onNavigatecloses the Menu before navigation. The row is absent when nothing is payable. Compact (tight) addsmt-2, because the compact wide panel has no top padding. - Inputs:
onNavigate(closes the Menu after the profile, balance, or loan Send link is followed),tight, andopen(whether the Menu is open). ReadssessionandaccountfromuseAuthStore, the stored session (loadSession),useWallet,useMyLoans,useSpotRate,useNumberFormat, anduseFiatPreference. - Returns / side effects: The card while the Menu is open, or
nullwhile the Menu is closed or when signed out (no session in the store and none stored,loadSession); it still starts loading while closed. Each transition from closed to open explicitly reloadsuseMyLoansonce, keeping the current shared loan body and row visible until a successful answer replaces it. Until the account is loaded (right after a page load, while the stored session is still being checked), the open card already has its final size: a roundh-10 w-10skeleton for the photo, skeleton bars in theh-5name line and theh-4@usernameline (the same heights the name and username lines keep once loaded), so the Menu rows under it do not move when the account arrives. That placeholder is not a link; the profile link appears with the account. On mount with a session it loads onlyGET /pictures/me(fetchProfilePhoto; a non-image answer counts as no photo, shown through an object URL). The photo is kept for the session in module memory (a later mount on the next screen shows it at once and asks nothing); two mounts at once share one load; when the read failed, the next mount asks again. A newer session's load revokes the previous photo URL. A load that settles after unmount is dropped. Nothing waits for these reads.useMyLoanssupplies the shared conditional repayment row. - Used by:
SignedInChrome; its loan Send link opens/loans/repay.
Function: ProfilePage
- Purpose: Next.js page for
/profile. - Inputs: None.
- Returns / side effects:
AppShellwithProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGatearoundProfileScreen. - Used by: Route
/profile.
Function: ProfileChromeLeft
- Purpose: Shared top-left chrome: one icon-only arrow (44px, ArrowLeft) plus a wordmark. The arrow returns to the previous in-app view in this tab, or
/welcomewhen this tab has none. One arrow. The wordmark is not that control. An ask-wizard or shop-wizard override replaces the history link with a button. The arrow is anext/link: it opens that view with the client-side router, never with a document load, so tab memory such as the open wallet stays. OptionalonBackClickruns on an unmodified click and returnstruewhen it took an in-page step (wallet hides the words, closes a send step, or returns from Send or Receive to the wallet home);falselets the arrow leave. Optionalwordmarkreplaces the default wordmark. OptionalwordmarkHrefdefaults to/welcomeand is ignored whenwordmarkis set.tone="dark"is the ink marketing header.hideHistoryArrowomits the history arrow whatever this tab's view stack holds (/welcome); a wizard override still shows, unlesshideOverrideis set as well, which leaves no arrow at all (the root info page/). - Inputs: Optional
onBackClick(() => boolean),wordmark,wordmarkHref,tone,hideHistoryArrow, andhideOverride; catalog viauseTranslations; previous path viapreviousViewPath. - Returns / side effects: A link (
profile.backwhen this tab has no earlier view, otherwisenav.back), the override button, or no arrow whenhideHistoryArrowis set and no override is armed orhideOverridehides it, plus the wordmark. The first client render matches SSR (/welcome,profile.back) unlesshideHistoryArrowhides that arrow. An unmodified primary click callsonBackClickfirst; when it returnstruethe link does not follow its href. Otherwise, when this document pushed the current entry on top of that view (takeStepBack) andViewHistoryRootprovides its back step, the click takes that step (router.back()), so the arrow and the browser's back agree; else it marks the href withmarkBackNavigationand the link opens it client-side. The second click of a double click does nothing. Modified clicks follow the href. No network. - Used by:
ProfilePage,WelcomePage,MarketingHeader,LoginPage,DonatePage,PayLinkScreen,ViewProfilePage,NameSetupPage,UsernameSetupPage,WalletChromeLeft,WalletScreenView(the visible/walletBack, viaAppShellTopLeft),ShopsPage,GrantsPage,FundingApplyPage,MemberProfilePage(/members/[accountId]),ContactPage,MessagesPage(viaMessagesChromeLeft),MessagesChromeLeft,NotificationsPage,ModeratePage,HiddenNotesPage,ProposalsPage,FundingApplicationsPage,FundingApplicationDetailPage,ModeratorGroupPage,TrustChainPage,RulesPageChrome,PublicMessageChrome.WalletPagemountsWalletChromeLeftas pagetopLeft; the card's registration wins while Wallet is shown.
Function: resetWalletReturn
- Purpose: Clear the stored
/walletreturn path. The top-left arrow does not read this slot. It returns to the previous in-app view in this tab, or/welcomewhen this tab has none. - Inputs: None.
- Returns / side effects:
void. Drops the shared tab slot andsessionStoragekey21gifts.walletReturn. Does not touchlocalStorage. - Used by: Wallet return tests,
RememberWalletReturntests,WalletChromeLefttests (afterEach).
Function: rememberWalletReturn
- Purpose: Remember a safe in-app path (not Wallet itself) as the
/walletback target. Rejects protocol-relative URLs,.., whitespace,#, overlong paths, and/walletitself without clobbering a previous good path. - Inputs:
pathstring (pathname, optionally with a query string). - Returns / side effects:
void. Writes aglobalThisslot andsessionStorage(21gifts.walletReturn) so every copy of the module in this tab sees the same path. NolocalStorage. No-op during SSR. - Used by:
RememberWalletReturn.
Function: walletBackHref
- Purpose: Read the path
rememberWalletReturnstored, or/welcomewhen this tab has not stored one. The visible top-left arrow does not use this value. That arrow uses the in-app view stack. - Inputs: None (reads the shared tab slot, which loads
sessionStoragethe first time). - Returns / side effects: The stored path string, or
WALLET_BACK_FALLBACK(/welcome). No network. The chrome arrow does not read this value. - Used by: Unit tests of the wallet-return slot. Not the chrome arrow.
Function: MoveFundsLink
- Purpose: Root listener for move-funds links, so a message or an email can start the move of a member's Bitcoin from another wallet: any page opened with
?move=1(for example/wallet?move=1) asks for the move-funds flow withrequestMoveFunds, for every member. The request waits in this tab (sessionStorage) until a signed-in screen opens the flow, so a visitor who still has to sign in, also through onboarding, gets it afterwards.MoveFundsSheetremoves the parameter once the flow opened. - Inputs: None. Reads
movefromuseSearchParams(mounted in the root layout insideSuspense). - Returns / side effects:
null. CallsrequestMoveFundswhenmoveis1. No network. - Used by: Root layout.
Function: RememberWalletReturn
- Purpose: Client recorder mounted in the root layout. On each pathname/search change, calls
rememberWalletReturnwith the current in-app path. The top-left arrow does not read this slot. - Inputs:
usePathnameanduseSearchParams. Non-empty query is appended as?…. - Returns / side effects:
null. CallsrememberWalletReturnduring render and again from an effect. No network. - Used by:
RootLayout(insideThemeProvider, wrapped inSuspense).
Function: PushOpenListener
- Purpose: Listens for
21gifts-push-openfrom the service worker and callsrouter.pushonly for a same-origin path, so an already open installed phone page can follow the notification URL. On mount, when the page becomes visible, and when it returns from the back-forward cache, it also opens a path the worker stored in the21gifts-push-opencache (at most 60 seconds old) in case a frozen page missed the message. A query may contain://. The page answers the worker; if that answer does not arrive and the window cannot navigate, the worker opens the href. Each click has its own id, and only that id is dropped after the page follows it. - Inputs:
MessageEventonnavigator.serviceWorker, plus a JSON{ url, at, id }cache record at/push-open/{id}. Accepts onlydata.type === '21gifts-push-open'with a stringdata.urlthat starts with/, contains no\, and parses as this origin. A query or hash may contain://. Drops a missing, stale, future, or unsafe cache record. A click id that is no longer the stored id is left in place. - Returns / side effects:
null. Navigates withrouter.pushwhen the path is a same-origin in-app URL; ignores anything else. No network. - Used by:
RootLayout(insideThemeProvider, afterAccountPreferenceSync).
Function: WalletChromeLeft
- Purpose: Page
/walletand/loans/repaychrome. RendersProfileChromeLeftonly. The arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none. One arrow. The wordmark is not that control. - Inputs: None. The previous path comes from the view stack inside
ProfileChromeLeft. - Returns / side effects:
ProfileChromeLeft. The card's Back replaces this one while Wallet is shown. No network. - Used by:
WalletPage,LoanRepayPage.
Function: MessagesChromeLeft
- Purpose: Client
/messageschrome. Always rendersProfileChromeLeft. It does not read?c=and it does not send every open thread to/messages. The view stack does: a thread opened from the list returns to the list; a thread opened from somewhere else returns there. - Inputs: None.
- Returns / side effects:
ProfileChromeLeft. The arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none. One arrow. The wordmark is not that control. No network. - Used by:
MessagesPage.
Function: previousViewPath
- Purpose: Read the in-app path this tab showed immediately before the current view. The top-left arrow uses it. The wordmark is not that control.
- Inputs: None. Reads the tab slot. When the slot is missing, reads
21gifts.viewHistoryand restores it. An empty store stays missing. - Returns / side effects: The previous path, or
nullon the server and when this tab has no earlier in-app view. No network. - Used by:
ProfileChromeLeft,RulesSetup.
Function: goToPreviousView
- Purpose: Leave for the previous in-app view in this tab, or open
/welcomewhen this tab has none. Does not jump to a fixed parent, does not leave the site, and does not load a new document, so tab memory such as the open wallet stays. - Inputs: The client-side router (
useRouter(), itspushandback). ReadspreviousViewPathandtakeStepBack. - Returns / side effects: When this document pushed the current entry on top of the target,
router.back(), the same step as the browser's back. Otherwise marks the target withmarkBackNavigation, thenpushof the previous path, orpush('/welcome')when this tab has none; it does not step back then, because that step could leave the site or load a document. It does not pop the stack before the router arrives, so a second click pushes the same path. The record that arrives there steps the cursor back. No network. - Used by:
RulesSetup(the chapter 0 arrow).
Function: markBackNavigation
- Purpose: Mark the path the top-left arrow is opening, so the view stack steps back instead of growing when that view records.
- Inputs: The in-app path the arrow opens: the previous view, or
/welcome. - Returns / side effects: Keeps the mark in module memory for a client-side navigation and in
sessionStorage(21gifts.viewHistoryBack) for a router that falls back to a document load. A record of the view being left (a re-render before the router arrives) keeps the mark. The record that arrives at the marked path steps the cursor back to it, or makes it the only view when there was no earlier one. A record of any other path drops the mark and pushes.resetViewHistorydrops it. No network. - Used by:
ProfileChromeLeft,goToPreviousView.
Function: recordCurrentView
- Purpose: Record the current in-app path on this tab's view stack, or restore a stamped index on browser back and forward. A router
pushStateis a push, even whenhistory.lengthdoes not grow. A URL-changingreplaceStatereplaces the current entry once this document is anchored, so a replaced screen is not a previous view; when that replace lands on the view before it, the cursor steps back onto that view, so the stack never holds the same view twice in a row after a replace. The first path of a new document, and any path after a client-side navigation, is a push, unless it is the arrow's one-shot target (markBackNavigation), which steps the cursor back. Unsafe paths are ignored. A real return to an earlier path is a new entry, not a collapse. The stack caps at 50 once a push is committed. A push that is not yet committed does not drop the oldest view; a later replace collapses that push first. A dropped entry keeps its absolute stamp, so browser back still finds it. - Inputs: A pathname, optionally with a query string. Optional
stampHistorydefaults to true. False updates the stack and does not writegiftsView, so the history entry being left keeps its stamp. - Returns / side effects: Updates the module slot and
sessionStorage(stackandcursor, plusbaseafter a capped drop). WhenstampHistoryis true, stampsgiftsViewwithhistory.replaceStatewithout pushing a history entry. A stored stack that contains an unsafe path is ignored. Each stamp also writesgiftsBelow(this document's id) when the entry was pushed in this document on top of the view before it; a browser step reads it back. A same-URLreplaceStatewithout its owngiftsView(Next's refresh) keeps the entry'sgiftsViewandgiftsBelow. A thrown storage write leaves the slot intact. No network. - Used by:
ViewHistoryRoot;SignedInChrome(Menu Home pressed on/welcome, plain click, records that path as the only view).
Function: returnToView
- Purpose: Leave a step for the view it was opened from (the till amount for
/pos, a grant application for/grants, a decided application for the queue) without leaving that step, or a second copy of the view, in this tab's history. The top-left arrow and the browser back on the returned-to view then both continue from the view before it, or/welcome. - Inputs: The in-app path the step was opened from, and the client-side router (
useRouter(), itsbackandreplace). - Returns / side effects: When the current entry was pushed in this document on top of that path, calls
router.back()once (a client-side step back, no document load). A second call for the same view before the browser has left this one (an effect that runs again) does nothing, so it neither steps back twice nor replaces under the step. Otherwise (a direct link, the first view after a document load, an arrival by the arrow or a browser step) callsrouter.replace(path);recordCurrentViewthen steps back onto the view before when it is the same path. No network. - Used by:
PosAmount,FundingApplyScreen,FundingApplicationDetailScreen,ContactLoader(back to the thread it opens),SocialRecoveryScreen(Done back to/security),RecoverScreen(Log in back to/loginafter a recovery done before),useRemainingBalance(Done and the removal back to/security), and every in-app redirect that usedrouter.replace:OnboardingGate(/logincarrying the gated screen, thenextview after login, and the next onboarding step),LogoutButton(/login),ViewProfileClaim(the next onboarding step),ForumLoader(/logincarrying the current view,/setup/rules), andProfileScreen,MemberProfileScreen,MemberProfileLoader,FundingApplyScreen,ShopTable(/setup/rules).
Function: loginHref
- Purpose: Build the
/loginhref for a signed-out visitor so that, once signed in, they return to the view they came from instead of the forum home. It is the one place that encodes the return path; no caller writes?next=itself. - Inputs: The current in-app path (pathname, optionally with a query string).
- Returns / side effects:
/login?next=<encoded path>(encodeURIComponent). A plain/loginfor/and/welcome(where a finished login lands anyway), for/loginitself, and for any path that is not a safe in-app path (the same rule asloginReturnPath). No storage, no network. - Used by:
PublicMessageLoader(the Log in link under a public note),OnboardingGate(a signed-out visitor on a gated screen),ForumLoader(signed-out 401 and feed-mode redirects),HabitTrackerTopRight, and the/statisticsLog in link.LogoutButtonandRecoverScreenopen a plain/loginon purpose.
Function: loginReturnPath
- Purpose: Read the view
/loginwas asked to return to (next) and accept it only when it is a same-origin in-app path, so a crafted login link cannot send a member to another site. - Inputs: The login page's query string (
location.search), with or without the leading?. - Returns / side effects: The decoded
nextpath, ornull. Accepted: a path that may enter this tab's view stack (one leading/, not//, no backslash, no scheme, no.., hash, or whitespace, at most 512 characters, and only the view stack's URL-safe characters), has no.path segment, and is not/loginitself (with or without a query or subpath).//evil.com, a backslash path,https://…,javascript:…,/login?next=…,/./login, and an empty value arenull. No storage, no network. - Used by:
OnboardingGate(theloginscreen, once the wallet is open and setup is finished;nullkeeps/welcome).
Function: canStepBack
- Purpose: Preview whether a plain click toward a path will step back with
router.back(). Same conditions astakeStepBack, without clearing the claim, so the arrow can still claim the step on the same click.ShopsScreenuses it when the top-left arrow's href is the view-stack path and has no hash: the view then follows the restored entry (popstate) instead of that href. - Inputs: An in-app path.
- Returns / side effects: A boolean. True when
takeStepBackwould tell the caller to callrouter.back(). Does not clearpushed. No network. - Used by:
ShopsScreen.
Function: takeStepBack
- Purpose: Claim a browser back step to a given view: true only when this document pushed the current history entry on top of that view, which is the previous view in this tab. The claim holds until the browser arrives, so a second call before that (a second click) returns false and cannot step back twice. The arrow and the step returns use it, so they step back instead of adding an entry when the browser's back would do the same.
- Inputs: An in-app path.
- Returns / side effects: A boolean; true clears the tab stack's
pushedflag, and the caller then callsrouter.back(). The current entry must also carry this document's stamp for the current view (giftsViewandgiftsBelow), so an entry the router pushed without a record (a hash link on/shops) never steps back onto the same view. Reads that flag, which each stamp also writes on the entry asgiftsBelow(this document's id), so a browser step back or forward reads it again; an entry of an earlier document, an arrival by the arrow's link, and a replace that collapsed onto the view before never count. No network. - Used by:
ProfileChromeLeft,goToPreviousView,returnToView.
Function: resetViewHistory
- Purpose: Clear this tab's in-app view stack so the top-left arrow opens
/welcomeuntil another view is recorded. The signed-in Menu's Home calls it, so the first screen opened from the forum home returns to/welcome, as on a fresh tab. - Inputs: None.
- Returns / side effects: Deletes the module slot, drops a pending arrow target (module copy and
21gifts.viewHistoryBack), and removes21gifts.viewHistoryfromsessionStorage. No network. - Used by:
SignedInChrome(Menu Home, plain click); unit tests that isolate the view stack.
Function: ViewHistoryRoot
- Purpose: Record the current pathname and search on the in-app view stack and provide the chrome back override. The top-left arrow returns to the previous in-app view in this tab, or
/welcomewhen this tab has none. One arrow. The wordmark is not that control. - Inputs:
children— the page tree. - Returns / side effects:
ChromeBackProvideraroundchildren, withrouter.back()as itsstepBack. A location recorder writes the stack during render without stamping history, and stampsgiftsViewfrom a layout effect after the router commits the history entry. A pathname the location has not reached yet is not recorded, so a query is not stored as its own hop. A replace committed after that render collapses the provisional push, so a replaced screen is not a previous view. Search comes fromwindow.location.searchwhen it matches the pathname, so a full navigation is stored before the load event. A suspended search recorder re-renders on a query-only change, including a cleared query, and records the live location — the same string as the location recorder, and only once that location has reached the pathname. Each committed view also removes the marker of a running client-side navigation (clearAppNavigation), so only a navigation that never committed leaves it for the next page load. No network. - Used by:
RootLayout, insideThemeProvider, besideRememberWalletReturn.
Function: useChromeBack
- Purpose: Read and set the top-left arrow override for an in-page step such as the ask wizard, the shop wizard, or a wallet Receive or Send view over
/welcome(labelnav.back). Without a provider, the override is null and the setter is a no-op, so a wizard render does not throw. - Inputs: None. Reads
ChromeBackProvidercontext when it is present. - Returns / side effects:
{ override, setOverride, stepBack };stepBackis the root'srouter.back(), ornullwithoutViewHistoryRoot. Does not navigate by itself. No network. - Used by:
ProfileChromeLeft,ForumAskWizard,ShopAddWizard,WelcomeScreen, the welcome top-left chrome.
Function: ChromeBackProvider
- Purpose: Hold the top-left back overrides, one slot per caller. The chrome arrow runs the latest in-page step instead of the view history; an override marked
over(a wallet view laid over/welcome) beats every page step, even one that registers again after it. Pay-sheet dismiss stays Close (X), not this control. - Inputs:
children; optionalstepBack, the client-side back step the arrow takes (defaultnull). - Returns / side effects: Context provider. Each caller has its own slot.
useChromeBackhands outstepBack. The arrow shows the last set override. Clearing or unmounting a caller restores the previous. No network. - Used by:
ViewHistoryRoot.
Function: ProfileScreen
- Purpose: Signed-in profile: single
max-w-smidentity card showing the public profile a visitor sees on/members/:id, plus edit controls, with a resting header (round profile photo fromGET /pictures/meand wide image fromGET /banners/mewhen that slot is stored; a missing one is an icon-only camera then the button Add a profile photo or Add a wide image (CameraPhotoButton: Take a profile photo with the front camera, Take a wide photo with the back camera); choosing a wide image opens a 5:2 cropper in place of Add a wide image (Add a profile photo stays; Use this crop stores the framed JPEG; the X (Cancel crop) stores nothing; saving the profile photo, including from About me, reloads the header and leaves that open crop in place; a failed or empty reload clears that header picture, and the Add button stays hidden until the reload settles); neither is the About me photo), a compact Given/Received activity chart, thenLoanBalanceChartdirectly under it (samefailedflag; missing loan fields → nothing drawn / saldo 0), About me (AboutMeSectionowner: empty prompt + Write your About me, or filled text and/or photo + edit; Languages Translate on the filled read-only text whenaboutMessageIdis set; the editor is not translatable; copy-profile-link on the card — never a forum post), the centered name with one role pill from the api role (a software developer shows one Software Developer pill because the api sendsrole: 'software_developer') and the funding-program icon, then location, then the same public facts a visitor sees on/members/:idand on/view/:viewKey(username@21.gifts, pay QR, Shop sticker, Posts/Reactions counts, and the activity feed). Owner edits appear because the account id matches. Identity only: notifications, language, theme, fiat currency, and number format live on/settings(SettingsScreen). Never showsforum.loadingon the card. The signed-in menu Profile row shows no amounts. Back + wordmark live inProfileChromeLeft. - Inputs: Session and account from
useAuthStore. OneMemberProfileScreen(nofactsOnly, noomitPills). The first paint is the account (name, location, role, About me).fetchMember(session, account.id)replaces that card.fetchMemberActivity(session, account.id)fills the gift and loan charts, the same series a visitor loads. Catalog viauseTranslations. Preferences stay on/settings. The owner About me editor insideMemberProfileScreenpassesomitEmptySlotAddsandimageEpoch, so empty portrait and wide-image adds are not repeated beside the header buttons, a header save refreshes those slots while the editor stays open. The screen passes the accountviewKeyasshareViewKey, so the copy button writes/view/<viewKey>. - Returns / side effects: When a profile photo or wide image is stored, that header is above the heading (wide image
aspect-[5/2], round photo overlapping its lower edge when both exist). Heading Profile, compact gift chart then loan chart (gift empty or in-flight:profile.chartEmptywith no chart FiatPicker, no SVG / no ₿|fiat scale; loan empty or in-flight renders nothing; a thrown activity load showsprofile.chartError/profile.loanChartError(role="alert"); never Loading…; populated: legend + ₿ | selected fiat + SVG). The card has no FiatPicker. About me, then the centered name with the pencil and, in that same row, the role pill (a software developer shows one Software Developer pill) and the funding-program icon (pressing it reveals that one sentence; on this screen the pressed result isfunding-program-press), then the location form, then the public member facts (username@21.gifts, QR, Shop sticker, post/reaction counts, and the on-demand feed) — all inside one identity card (no second panel), with no settings rows. A failedfetchMembershowsforum.errorand Try again and leaves the editors up.MissingRequirementsErrorgoes to/setup/ruleswithreturnToView. No Message button and no staff actions. Back + wordmark live inProfileChromeLeft. Without a receiving address (lightningAddress: null), the public facts show Can't receive yet (CannotReceiveLabel) instead of the address, the QR, and the Shop sticker. - Used by:
ProfilePage.
Function: AboutMeSection
- Purpose: Profile-card About me block: heading plus filled text and/or photo (the note photo shows the whole picture (
object-contain,max-h-80) and is not cropped, not the profile photo or the wide image), or the owner empty prompt (profile.about.emptyTell others who you are. and labeled Write your About me). Filled means trimmedaboutMeis a real bio (not the display name) orhasPhotois true. Owner mode can edit (write / pencil, save, cancel) viaonSave. The editor can show three separate attaches, each its own icon-only camera (CameraPhotoButton, same handler; the profile photo uses the front camera) followed by its ImagePlus and remove: the About me photo (JPEG/PNG/WebP viaprepareForumPhoto, no video), the round profile photo, and the wide image. WhenomitEmptySlotAddsis set, the profile-photo attach (camera and ImagePlus) is omitted while no portrait is stored and the wide-image attach is omitted while no wide image is stored; a stored slot keeps its replace icon and remove control. The About me photo attach is unchanged. Each previews on its own. Choosing a wide image opens a 5:2 cropper above its preview; Use this crop stores that JPEG and the X (Cancel crop) stores nothing. Closing the editor, or a successful save, drops an unsaved crop. A whole portrait is not stored as the wide image. Optional icon-only copy-profile-link (profile.copyLinkCopy link to this profile) whenprofileUrlis set; the URL is never shown as visible text. Public mode with no filled text, no photo, and no copy URL rendersnull. A filled read-only body usesTranslatableNoteBodywhenmessageIdis a non-empty string; otherwiseLinkedText. The editor is not translatable. - Inputs:
aboutMe(string | null),mode(owner|public), optionalname(string | null) for the filled comparison ((name ?? '').trim(); blank name applies only the trimmed-non-empty check), optionalhasPhoto, optionalloadPhoto(() => Promise<Blob>), optionalprofileUrl, optionalmessageId(stored About me note id; omitted or blank keepsLinkedText), optionalonSave(text, photo?)(photoomitted keeps,nullclears, object sets), optionalloadPicture/onSavePicturefor the round profile photo and optionalloadBanner/onSaveBannerfor the wide image (neither is the About me note photo; a non-image blob stays empty), optionalstartEditingto open the owner editor on mount, optionalomitEmptySlotAdds(boolean, default false) to hide empty portrait and wide-image adds, optionalimageEpoch(number, default 0) to reload the stored portrait and wide image while the editor stays open. After more than 8000 characters (profile.about.errorLength) or a control character other than a line break (profile.about.errorControls), Save About me stays disabled until the draft changes. - Returns / side effects: React element or
null. Clipboard write for copy. CallsonSaveon owner save,onSavePicturewhen the profile photo changes, andonSaveBannerwhen the wide image changes. Loads a blob URL whenhasPhotoandloadPhotoare set and revokes it on unmount. Loads and revokes the profile-photo and wide-image blob URLs the same way whenloadPictureorloadBanneris set.imageEpochreloads those stored slots while the editor stays open. - Used by:
MemberProfileScreen(owner passesomitEmptySlotAddsandimageEpochwhen the account id matches; public otherwise),ViewProfileScreen(public,name={profile.name}),FundingApplyScreenrenders it in the apply walk, which every verified account with statusnoneorrejectedsees (applications are open),ProfileScreen(owner,name={account.name},omitEmptySlotAdds).
Function: PushToggle
- Purpose: Settings Notifications sections (the section heading is
profile.push.headingonSettingsScreen): uppercase headingprofile.notify.heading, a Hearts On / OffSegmentedControl(profile.push.on/off, groupprofile.heartNotify.label,fullWidthfalse), and one compact PostsSegmentedControl(fullWidthfalse, groupprofile.notify.room) on the same line as its label. The Posts options are always All (all), Only to me (mentions), Only with a gift (active), and Off (none), on that same line and right-aligned. The label does not shrink; the pill wraps under it only when the row is too narrow. Choosing another option posts that level. Pressing the selected option does not POST. No level hint and no heart hint. A second bordered section, headingprofile.device.heading, shows Notifications On / Off (profile.device.label, notaria.push) only whenserviceWorker/PushManagerare ready. No Bell / IconButton / trailing slot. Changing the level POSTs/me/notification-levelviapostNotificationLeveland mergesnotificationLevelinto the current store account when the session still matches; a second change while the POST is in flight is ignored; failure keeps the previous value and showsprofile.push.level.error. Hearts displayaccount.notifyHearts ?? true; changing them POSTs/me/heart-notificationsviapostHeartNotificationswith{ enabled }and mergesnotifyHearts; a second change while that POST is in flight is ignored; failure keeps the previous value and showsprofile.heartNotify.error. The device pill callsenablePush/disablePush; same-value or busy is a no-op. Renders nothing without a session. On iPhone Safari outside standalone, showsprofile.push.installHintunder the device row. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations;postNotificationLevel,postHeartNotifications,accountNotificationLevel, andsetAccount;enablePush,disablePush,pushRenewalPending,pushTurnedOff,isIosSafari, andisStandaloneDisplay. - Returns / side effects: Heading
profile.notify.heading, Hearts On/Off, a compact Posts pill (All / Only to me / Only with a gift / Off), and, when Push APIs are ready, a second sectionprofile.device.headingwith Notifications On/Off. Level change callspostNotificationLevelthen mergesnotificationLevel; Hearts change callspostHeartNotificationsthen mergesnotifyHearts; On callsenablePushwhen not subscribed, Off callsdisablePushwhen subscribed; may showprofile.push.unavailableon push failure,profile.push.level.erroron level failure, orprofile.heartNotify.erroron the heart setting failure. - Used by:
SettingsScreen.
Function: useUnreadCount
- Purpose: Load signed-in unread notification, inbox, staff-room, and open-proposal counts in parallel (
GET /forum/notifications+GET /conversations, plusGET /conversations/moderator-groupandGET /trust/proposalswhenroleAtLeast(account?.role, 'moderator')).refreshKeyretriggers the fetches (Menu open). Does not mark notifications or conversations read. - Inputs:
refreshKeyboolean; optionaloptions?: { writeBadge?: boolean }(omit the object to default). Default writes the home-screen badge.writeBadge: falsefetches and returns the four counts but does not callsetUnreadAppBadge(including the logout / session-null0write). - Returns / side effects:
{ unreadCount, inboxUnreadCount, moderationUnreadCount, proposalCount }.unreadCountis the notifications unread count.inboxUnreadCountis the number of conversation rows withunread: true.proposalCountis the open-proposal list length.moderationUnreadCountis staff-room unread (0or1) plusproposalCount, for the Menu Moderation row. Hub Open proposals usesproposalCountalone. When badge writes are enabled (the default), the home-screen badge is notification unread + inbox unread + staff-room unread (0or1) — open-proposal count is not added (proposal rows already sit in notification unread) — written once all started fetches settle. A role below moderator skips the staff-room and proposals fetches and contributes0. A thrown staff-room or proposals fetch contributes0without failing the other sides. Either of the other sides failing contributes0to the sum; the other sides still write. Epoch skip applies to that sum write. No session → all four counts0; badge0only when writes are enabled andloadSession() === null(real logout). A hydrating store (sessionnull, token still in storage) does not clear the badge. A cancelled fetch updates neither React state nor the badge. - Used by:
SignedInChrome(default write),ModerateScreen(writeBadge: false).
Function: setUnreadAppBadge
- Purpose: Set or clear the installed PWA home-screen unread badge via the Badging API (
navigator.setAppBadge/navigator.clearAppBadge). Whencount > 0andsetAppBadgeexists, sets that number; otherwise clears whenclearAppBadgeexists. Missing APIs are a no-op. Rejections are swallowed so unsupported or denied badge writes never throw into the UI. - Inputs:
count(number) — notification unread plus inbox unread plus staff-room unread (0or1). Positive values request a badge;0(and any non-positive) request a clear. - Returns / side effects:
void. Fire-and-forget promises; does not await. No network. - Used by:
useUnreadCount,NotificationsLoader,refreshUnreadAppBadge,useAuthStore.clearAuth.
Function: bumpUnreadAppBadgeEpoch
- Purpose: Increment the home-screen badge epoch so in-flight unread fetches do not overwrite a mark-all-read clear, and after inbox mark-read so they do not overwrite the remaining sum.
- Inputs: None.
- Returns / side effects: The new epoch number.
- Used by:
NotificationsLoader,InboxLoader,ModeratorGroupScreen,useAuthStore.clearAuth.
Function: unreadAppBadgeEpoch
- Purpose: Read the current home-screen badge epoch. Capture before an async unread fetch; skip
setUnreadAppBadgeif it changed. - Inputs: None.
- Returns / side effects: Current epoch number. No network.
- Used by:
useUnreadCount,NotificationsLoader,refreshUnreadAppBadge.
Function: refreshUnreadAppBadge
- Purpose: Refresh the installed PWA home-screen badge to notification unread plus inbox unread plus staff-room unread (
0or1). SignaturerefreshUnreadAppBadge(sessionToken, inboxUnreadOverride?, moderationUnreadOverride?). FetchesGET /forum/notificationsand, unless an inbox override is passed,GET /conversations. When the moderation override is omitted, fetchGET /conversations/moderator-grouponly whenroleAtLeast(account?.role, 'moderator')(unreadtrue →1, else0; throw/404 →0); a role below moderator contributes0without starting the request. When the moderation override is set, skip that fetch. Any side failing contributes 0. Captures the badge epoch at start; skips the write if the epoch changed orloadSession()is not stillsessionToken. Never rejects. - Inputs:
sessionToken(string). OptionalinboxUnreadOverride(number) — when set, skip the conversations fetch and use that inbox unread count (e.g. the local list after mark-read). OptionalmoderationUnreadOverride(number) — when set, skip the staff-room fetch and use that count (0or1). When the moderation override is omitted, skip the staff-room fetch unless the signed-in auth-store account is at least moderator. - Returns / side effects:
Promise<void>. CallssetUnreadAppBadgewith the sum only when the epoch is unchanged andloadSession() === sessionToken. Fire-and-forget safe. - Used by:
InboxLoaderafter a successful thread load and mark-read (inbox override only; fetches staff-room only when the account is at least moderator).ModeratorGroupScreenafter opening the room (moderation override0).
Function: pushTagForNotification
- Purpose: Collapse tag for one in-app notification, matching the api:
forum_post:<parentId>,forum_reply:<replyId>,forum_mention:<replyId>,zap:<replyId>,heart:<replyId>,moderator_appointed:<parentId>. Any other type, includingmoderator_proposal, is null. - Inputs:
type,parentId, andreplyId. - Returns / side effects: Tag string or
null. No network. - Used by:
NotificationsLoaderbefore it closes the local banner for a row that is not a proposal, andForumLoaderafter the welcome appointment pill'smarkNotificationReadsucceeds.
Function: currentPushEndpoint
- Purpose: Read this browser's Web Push subscription endpoint so a mark-read request can ask the api to skip this device. Calls
getRegistration()and does not wait onready. - Inputs: None. Uses
navigator.serviceWorkerwhen it exists. - Returns / side effects: The endpoint string, or
undefinedwhen Push APIs are missing, the lookup rejects, or the endpoint is empty. Never throws. - Used by:
markNotificationRead,markAllNotificationsRead,markNotificationsReadForMessage, andmarkVisibleForumNoteRead.
Function: closeLocalPushNotifications
- Purpose: Close shown Web Push notifications whose tag is in the list, so a note already read on this device does not stay on screen. Calls
getRegistration()and does not wait onready. - Inputs: Tag strings. An empty list is a no-op.
- Returns / side effects: Nothing. Missing
serviceWorkerorgetNotificationsis a no-op. Never throws. - Used by:
markAllNotificationsRead,markNotificationsReadForMessage,markVisibleForumNoteRead,NotificationsLoaderwhen a row is opened, andForumLoaderafter the welcome appointment pill'smarkNotificationReadsucceeds.
Function: vapidPublicKeyToBytes
- Purpose: Decode a VAPID application server public key (url-safe base64) to bytes for
pushManager.subscribe. - Inputs: Url-safe base64 public key string.
- Returns / side effects:
Uint8Array. No network. - Used by:
enablePush,resyncPushSubscription.
Function: registerPushWorker
- Purpose: Register the push-only service worker at
/sw.js(scope/) and wait until ready. - Inputs: None (uses
navigator.serviceWorker). - Returns / side effects:
ServiceWorkerRegistration. - Used by:
enablePushonly.disablePushandresyncPushSubscriptionlook up an existing registration withgetRegistration()and never register the worker.
Function: push service worker
- Purpose: Push-only service worker at
/sw.js. A payload whosetypeisdismisscloses the named tags, shows and closes a silentdismiss-ack, sets the badge tomax(0, floor(unreadCount))including 0, and returns before the Sunday check. On the device's local Sunday, a push whosetypeis not exactlyconversationdoes not stay on screen and does not change the badge: it callsshowNotificationwith tagsunday-quietand closes that note in the samewaitUntil, so the browser does not invent its own banner. Every other push, including a private message, shows a notification (registration.showNotification) and, whennavigator.setAppBadge(orregistration.setAppBadgeas fallback) exists, sets the home-screen badge: floorpayload.unreadCountfirst, use it when that integer is greater than 0, otherwise1.setAppBadgerejections are swallowed sowaitUntilstill followsshowNotification. MissingsetAppBadgestill shows the notification. A thrown weekday lookup does not pause notifications. No asset or offline cache. A notification click stores a short-lived21gifts-push-openentry so a reloaded page can still open the path whenpostMessagewas missed. Onpushsubscriptionchangethe worker subscribes again with the lost subscription's application server key (skipped when the browser already suppliesnewSubscriptionor the old key is unknown), then posts{ type: '21gifts-push-subscription-change' }to every window. The api accepts a subscription only with a member session, which the worker does not hold, so an openSignedInChromerunsresyncPushSubscription(session, true)on that message (which also subscribes with the current key when the worker could not) and otherwise the next app start posts a subscription the worker restored (one it could not restore with no window open has to be turned on again in the profile); the api drops the old endpoint once the push service reports it gone. - Inputs: Push
eventwith optional JSON payload (type,title,body,url,tag,tags,unreadCount). - Returns / side effects: When
typeisdismiss, closes the named tags, shows and closes a silentdismiss-ack, sets the badge tomax(0, floor(unreadCount))whenunreadCountis finite, and returns before the Sunday check. On a non-conversation Sunday push,event.waitUntilshows and closessunday-quiet. Otherwiseevent.waitUntilofshowNotificationplus optionalsetAppBadgeviaPromise.all. Install skips waiting; activate claims clients. Notification click closes the note, stores the in-app path in the21gifts-push-opencache, then the focused same-origin window (or the first one, if none is focused) is focused and, after that, receives{ type: '21gifts-push-open', url }(pathname + search + hash). A page that answers within 500 ms opened the path with its client-side router and is not navigated again, so its document and the open wallet in tab memory stay. A page that does not answer is navigated withnavigatewhen that function exists and the URL differs (rejection or null still focuses), otherwiseclients.openWindowopens the href. No window:clients.openWindowon the same-origin href. Empty, invalid, or foreigndata.urlbecomes/welcome. - Used by: Browser Web Push runtime (registered by
registerPushWorker).
Function: isStandaloneDisplay
- Purpose: Detect installed / standalone display mode (
display-mode: standaloneor iOSnavigator.standalone). - Inputs: None (reads
window/navigator). - Returns / side effects:
boolean. No network. - Used by:
PushToggle,shouldOfferIosInstall,PwaInstall.
Function: isIosSafari
- Purpose: Detect iPhone/iPod stock Safari (Safari in UA, not CriOS/FxiOS).
- Inputs: None (reads
navigator.userAgent). - Returns / side effects:
boolean. No network. - Used by:
PushToggleonly.
Function: iosPasskeyBlock
- Purpose: Read an iPhone, iPad, or iPod user agent and decide whether a new account can finish. iOS 18 is the first version with the extra key this sign-in needs. Older iOS returns the installed version and the minimum. Other browsers, iOS 18 or newer, and an iOS user agent with no version token return null.
- Inputs:
userAgentstring (navigator.userAgent). - Returns / side effects:
{ installed, required }whererequiredis18andinstalledismajor.minorormajor.minor.patch, or null. No network and no DOM writes. - Used by:
LoginCard(muted line after mount) andusePasskeyLogin(a new account that cannot finish fails withlogin.iosVersionand is not stored).
Function: iosInstalledVersion
- Purpose: Read the installed iOS version from an iPhone, iPad, or iPod user agent, including iOS 18 and newer.
iosPasskeyBlockstill returns null on those newer versions. - Inputs:
userAgentstring. - Returns / side effects: Installed string (
major.minorormajor.minor.patch), or null when the token is missing or the browser is not iOS. No network. - Used by:
usePasskeyLogin, which puts that version at the front of a failed login or register diagnostic.
Function: androidPasskeyBlock
- Purpose: Android below 9 cannot finish a new-account passkey. Android 9 is the first version whose passkeys can carry the extra key. Older Android returns the installed version and the minimum. Android 9 and newer, other browsers, and an Android user agent with no version token return null.
- Inputs:
userAgentstring. - Returns / side effects:
{ installed, required }whererequiredis9andinstalledis major, major.minor, or major.minor.patch, or null. No network. - Used by:
LoginCard(muted line after mount) andusePasskeyLogin(a new account that cannot finish fails withlogin.androidVersionand is not stored).
Function: androidInstalledVersion
- Purpose: Read the installed Android version, including Android 9 and newer.
androidPasskeyBlockstill returns null on those newer versions. - Inputs:
userAgentstring. - Returns / side effects: Installed string, or null when the token is missing. No network.
- Used by:
usePasskeyLogin, which puts that version at the front of a failed login or register diagnostic.
Function: shouldOfferIosInstall
- Purpose: True when an iPhone/iPod browser whose UA contains Safari (stock Safari, Chrome CriOS, Firefox FxiOS, Edge EdgiOS) is not standalone and not an in-app browser — the condition for the iOS Home Screen install sheet.
- Inputs: None. Reads
navigator.userAgentplusisStandaloneDisplayandisInAppBrowser. Does not callisIosSafari. - Returns / side effects:
boolean. No network. - Used by:
PwaInstall.
Function: PwaInstall
- Purpose: Client install control for the PWA. First paint is
null(no layout slot). After mount, hidden when standalone or in-app. On iPhone Home Screen browsers (Safari, Chrome, Firefox, Edge) (shouldOfferIosInstall) shows a labeled control that opens a three-steprole="dialog"sheet (Share → Add to Home Screen → if Open as Web App is shown, leave it on). On Chromium, listens forbeforeinstallprompt(preventDefault, store event), shows the control, and on click callsevent.prompt()then drops the event (hides) regardless of accepted/dismissed;appinstalledalso hides. Placements:header(compact secondary),hero(secondary md),menu(SignedInChrome Download + label row). - Inputs:
placement(header|hero|menu); optionaltone(app|dark, defaultapp); optionalonMenuAction(menu row closes the Menu after click). Catalog viauseTranslations. - Returns / side effects: Install button and optional iOS sheet, or
null. No new dependencies; Tailwind only. - Used by:
MarketingHeader(tone="dark"placement="header"),Homehero (tone="dark"placement="hero"),SignedInChromeMenu (placement="menu").
Function: enablePush
- Purpose: Register the worker, fetch the VAPID key, request notification permission, subscribe, and POST the subscription to the api. Once permission is granted it removes the
21gifts-push-offflag a previous Off stored. Shares a serial queue withresyncPushSubscriptionanddisablePush; a later disable no-ops a queued enable. - Inputs:
sessionToken. - Returns / side effects:
void. ThrowsNotification permission deniedorPush is not configured(and other api errors). - Used by:
PushToggle,SignedInChrome.
Function: resyncPushSubscription
- Purpose: When
Notification.permissionis alreadygranted, a service worker is already registered (getRegistration(); never registers one), and a localpushManagersubscription exists, fetch the current VAPID key and POST that endpoint to the api. When the subscription'soptions.applicationServerKeydiffers byte for byte from the current key,unsubscribe(),subscribe()again with the current key, POST the new subscription, and DELETE the old endpoint (a DELETE failure is ignored). A browser that does not expose the stored key keeps the plain re-POST. Before dropping the old subscription it stores21gifts-push-renewinlocalStorageand removes it after a successful POST, so whensubscribe()fails (or returns no keys) after the old subscription was dropped, the next call subscribes with the current key even though no local subscription is left. When only the POST fails, the new subscription stays and the next call re-POSTs it. When storage cannot hold the marker, it keeps the old subscription and re-POSTs it instead of dropping it. When permission is notgranted, it removes a pending marker, so granting permission later does not subscribe on its own. WithsubscriptionChangedtrue (the worker's21gifts-push-subscription-changemessage), a missing local subscription is not an opt-out either: the worker could not subscribe again, so the resync stores the21gifts-push-renewmarker before it fetches the key and subscribes with the current key. WhiledisablePush's21gifts-push-offflag is set (Off or log out in this or another tab, untilenablePush), any resync subscribes nothing and finishes the Off for a subscription still present (one that survived a cut-off log out, or one the worker made meanwhile): DELETE its endpoint (failure ignored),unsubscribe(), and drop a pending renewal. The flag is shared by every tab while the queue generation is per tab, so the resync reads it again after the key fetch, aftersubscribe(), and after each POST, and finishes the Off for whichever subscription it holds then. Never callsrequestPermission. Opt-out (no local subscription, no pending renewal, and no reported change) is a no-op. POST failure leaves the local subscription in place. Shares a serial queue withenablePushanddisablePush; a later disable no-ops a queued resync so it cannot POST after DELETE. - Inputs:
sessionToken; optionalsubscriptionChanged(defaultfalse). - Returns / side effects:
void. Without granted permission, only removes a pending21gifts-push-renewmarker. While21gifts-push-offis set, only DELETEs and unsubscribes a subscription still present. No-op when Push APIs are missing, no worker is registered, orgetSubscription()is null with no pending renewal and no reported change. Throws api errors fromfetchVapidPublicKey/postPushSubscriptionwithout unsubscribing, the browser'sPushManager.subscriberejection, andInvalid subscriptionwhen a new subscription omits endpoint or keys. - Used by:
SignedInChrome(mount, Notifications click when permission is already granted, and the worker's21gifts-push-subscription-changemessage).
Function: pushRenewalPending
- Purpose: Whether this browser owes a resubscription after a VAPID key change or a browser-reported subscription change, with no new subscription stored yet (
21gifts-push-renewinlocalStorage). The next resync finishes it unless push is turned off, so the device counts as subscribed until then. Counts only whileNotification.permissionisgranted, because without it the resync cannot finish the renewal. - Inputs: None (reads
Notification.permissionandlocalStorage). - Returns / side effects:
boolean. False when permission is not granted, the marker is missing, or storage throws. No network. - Used by:
resyncPushSubscription,PushToggle.
Function: pushTurnedOff
- Purpose: Whether the last choice on this browser was Off or log out (
21gifts-push-offinlocalStorage, stored bydisablePushand removed byenablePush). Shared by every tab, so a resync in another tab respects it too. - Inputs: None (reads
localStorage). - Returns / side effects:
boolean. False when the flag is missing or storage throws. No network. - Used by:
resyncPushSubscription,PushToggle.
Function: disablePush
- Purpose: When a service worker is already registered (
getRegistration(); never registers one) and it holds a local push subscription, DELETE its endpoint on the api thenunsubscribe()locally. Bumps a generation so in-flight enable/resync cannot POST after this opt-out, and waits for the shared serial queue so DELETE is the last server mutation. - Inputs:
sessionToken. - Returns / side effects:
void. Clears a pending21gifts-push-renewkey renewal and stores21gifts-push-offat once (log out waits only briefly for the queue), and clears the renewal again inside the queue. No-op whenserviceWorkeris missing, no worker is registered, or there is no subscription, so log out never installs a worker. Localunsubscribe()still runs if the api DELETE fails. - Used by:
PushToggleandLogoutButton.
Function: fetchVapidPublicKey
- Purpose: GET
/push/vapid-publicwith the bearer session and return the VAPID public key string. - Inputs:
sessionToken. - Returns / side effects:
string. ThrowsPush is not configuredon 503; other non-2xx throw with status. - Used by:
enablePush,resyncPushSubscription.
Function: postPushSubscription
- Purpose: POST
/me/push-subscriptionswith bearer +{ endpoint, keys }and validate the response. - Inputs:
sessionToken, subscription endpoint + p256dh/auth keys. - Returns / side effects:
void. ThrowsPush is not configuredon 503; 400 uses api error when present. - Used by:
enablePush,resyncPushSubscription.
Function: deletePushSubscription
- Purpose: DELETE
/me/push-subscriptionswith bearer +{ endpoint }. - Inputs:
sessionToken,endpoint. - Returns / side effects:
void. 404 is success (already gone). ThrowsPush is not configuredon 503. - Used by:
disablePush,resyncPushSubscription(old endpoint after a VAPID key change).
Function: proxyPushVapidPublicGet
- Purpose: Bearer proxy GET
/push/vapid-publicto the 21.gifts api. - Inputs: Incoming
Requestwith Bearer session. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/push/vapid-public.
Function: proxyMePushSubscriptionsPost
- Purpose: Bearer proxy POST
/me/push-subscriptionsto the 21.gifts api. - Inputs: Incoming
Requestwith Bearer session and JSON body. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/push-subscriptions.
Function: proxyMePushSubscriptionsDelete
- Purpose: Bearer proxy DELETE
/me/push-subscriptionsto the 21.gifts api. - Inputs: Incoming
Requestwith Bearer session and JSON body. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route DELETE
/me/push-subscriptions.
Function: manifest
- Purpose: Next.js
MetadataRoute.Manifestfor installable 21.gifts (/manifest.webmanifest). - Inputs: None.
- Returns / side effects: Manifest with name/short_name
21.gifts, start_url/welcome, displaystandalone, theme/background colors, apple-touch-icon at 180×180, plusicon-192.pngandicon-512.png. - Used by: App Router manifest route.
Function: AccountActivityChart
- Purpose: Compact dual-line cumulative SVG of Given and Received. Does not mount FiatPicker on the signed-in profile, a member profile, or public
/view. The preferred code comes fromuseFiatPreference(the Settings Display row when signed in, otherwise the cookie or the locale default). Empty/all-zero sats isprofile.chartEmptyrole="status"(no SVG, no ₿|{fiat} scale). Empty/all-zero sats andfailedshowprofile.chartError(role="alert",text-app-danger) instead ofprofile.chartEmpty. In-flight and successful empty stayprofile.chartEmpty, never Loading…. Nullusd/cumulativeUsdwith positive cumulative sats still draws the satoshi chart (legend + scale + SVG). Populated: legend +SegmentedControl tone="gift"options ₿ | selected FiatCode (profile.chartScale), then SVG. Scale state isActivityScale'sat' | 'fiat'. Ticks: satformatBitcoin; fiatformatFiatTick(USD may useformatUsdTick); em dash whenfiatUnsummableholds for both series (USD: any rawcumulativeUsdisnull; other codes: every source cumulative isnull). Wrapperrole="group"usesprofile.chartTitleasaria-label. No title heading; page heading is Profile. Given isdonatedOverTimefrom account activity (no longer a hardcoded zero series). - Inputs:
received(AccountActivity.receivedOverTime); optionaldonated(default[]) fromAccountActivity.donatedOverTime; optionalfailed(default false). - Returns / side effects: When the series is empty or all zeros:
profile.chartEmpty(role="status") — no legend, ₿|{fiat} scale, FiatPicker, or SVG — orprofile.chartError(role="alert",text-app-danger) whenfailed. In-flight and successful empty stayprofile.chartEmpty, never Loading…. Nullusd/cumulativeUsdwith positive cumulative sats still draws the satoshi chart. Otherwise one chrome row (legend left, ₿ | selected FiatCode right) and SVG. Client state for scale. This component does not write thefiatcookie. No network. - Used by:
MemberProfileScreenandViewProfileScreen(no route rendersViewProfileScreen).
Function: LoanBalanceChart
- Purpose: Compact dual-line open-balance SVG of Debt (
owedOverTime) and Credit (creditOverTime), mounted directly underAccountActivityCharton the same three profile surfaces. Does not mount FiatPicker. Fiat code comes fromuseFiatPreference(written by the Settings Display row when signed in, otherwise the cookie or the locale default). Chrome matches the gift chart geometry (same WIDTH/HEIGHT/pads) and uses a localSegmentedControl tone="gift"(profile.chartScale/profile.scaleSat/ selected fiat). Empty or all-zero cumulative sats renders nothing for both signed-in and unsigned, with no picker and no status. Empty/all-zero andfailedshowprofile.loanChartError(role="alert",text-app-danger). In-flight renders nothing, never Loading…. Populated: legend Debt/Credit (profile.legendDebt/profile.legendCredit) plus ₿ | fiat scale, then SVG. Y-axis always includes 0 vialoanAxisand may extend below zero. Fiat ticks are an em dash whenfiatUnsummableholds for both series; loan days from the api carrynullin every fiat field, so the fiat scale shows an em dash like an unsummed gift chart. Circles mark every value change (rise or fall), not only increases. Wrapperrole="group"usesprofile.loanChartTitle. No title heading. - Inputs: optional
owed(default[]) fromAccountActivity.owedOverTime; optionalcredit(default[]) fromAccountActivity.creditOverTime; optionalfailed(default false) — same flag as the gift chart. - Returns / side effects: Empty/all-zero sats and not failed →
null(no status, no FiatPicker). Failed empty → alert copy, no FiatPicker. Otherwise legend + scale + SVG. Client scale state only. This component does not write thefiatcookie. No network. Missing API loan fields are already normalized to[]by callers. - Used by:
MemberProfileScreen(not infactsOnly) andViewProfileScreen(no route rendersViewProfileScreen).
Function: Button
- Purpose: Labeled app button with primary (filled), secondary (bordered), accent fill, or
overlay(a dark translucent pill,bg-black/55 text-white backdrop-blur-md, for controls over a camera picture; the same on both tones). Optionaltoneapp(default) ordarkfor marketing-ink shells (same class split asButtonLink). Sizesm/md/lg(lgis full width). All sizesmin-h-11. - Inputs: Native button props plus optional
variant(defaultprimary), optionalsize(defaultmd), optionaltone(defaultapp), optional leadingicon, optionalref(the rendered<button>, to move focus to it), andchildrenlabel. Defaulttype="button". - Returns / side effects: A
<button>element. No network. Used across login, forum retry, public note retry, PWA install on dark shells, and forms. - Used by:
PublicMessageLoader,ForumBoard,PwaInstall,WalletBalance,WalletPay,WalletSend,LoanRepayScreen, setup and contact screens.
Function: ButtonLink
- Purpose: Labeled pill link matching
Buttonanatomy (primary/secondary/accent,sm/md/lg,toneappordark).size="chrome"is the compact page-chrome pill (min-h-11 gap-1 px-1.5 py-1 text-xs, fromsmgap-1.5 px-3 text-sm); the other sizes keepgap-2 text-sm. - Inputs:
href, optionalvariant/size(chrome/sm/md/lg) /tone/icon/className/aria-label, optionalonClick, and the visiblechildrenlabel. - Returns / side effects: A Next.js
<Link>for internal paths, or a native<a>for protocol hrefs (https:). When supplied,onClickruns before navigation; the Menu loan row uses it to close the Menu before/loans/repayopens. No network of its own. - Used by:
Home,MarketingHeader,DonatePage,RulesDocument,LoansCard, andMenuAccountHeader.
Function: SegmentedControl
- Purpose: Mutually exclusive option group with
tonegift(compact ₿|USD cells, optionalshellapp/dark) orneutral(pills for staff inbox and Settings notifications). OptionalfullWidthdefaults to true and is ignored forgift; false makes the neutral trackinline-flex w-auto shrink-0so the pill hugs its labels and can sit beside a row label. Gift hit target ismin-h-11 min-w-11on mobile and desktop.shellis ignored forneutral. Neutralrole="group"is the pill; the forum composer Post/Ask!grid grid-cols-2 !rounded-2xlstill lays out those option buttons viaclassNameon the group. The four forum view filters areForumModeSelect, not this control. Notrailingslot. - Inputs:
value,options(value+label, optionalbadge/badgeAriaLabel; chip omitted whenbadgeis missing or ≤ 0; optionaldisabled),onChange,ariaLabel,tone, optionalfullWidth(default true, ignored forgift), optionalshell(defaultapp, gift only), optionalclassName(on the group). - Returns / side effects: A
role="group"track oftype="button"options witharia-pressed. A disabled option renders a nativedisabledbutton, dimmed withdisabled:opacity-50in both tones, and pressing it does nothing. Neutral is that group as the pill (classNamelands there, including the composer Post/Ask!grid grid-cols-2 !rounded-2xl). No network. - Used by:
ForumBoard(tone="neutral"),PushToggle(tone="neutral", three times, each withfullWidthfalse: Hearts, Posts, and Notifications under On this device),AccountActivityChart(tone="gift"),StatsDashboard(tone="gift" shell="dark"),AmountEntry(tone="gift", the fiat option disabled without an exchange rate),FondDeposit(tone="neutral",fullWidthfalse: Instant payment / On-chain deposit, shown only with a checked on-chain address).
Function: ForumModeSelect
- Purpose: Combobox for the living-room forum view (Active, No gifts yet, All, Most popular) and the shops country filter. The field trigger shows the selected label and a chevron. The chip trigger is a compact
rounded-fullpill with a 44px minimum hit target and a truncating label; belowsmthe trigger shows a globe icon instead of the label and badge. A positive unpaid badge is also shown as a count chip on the closed trigger. Opening the trigger shows a listbox of option rows; the selected row has a check. Choosing a row calls onChange and closes the list. Post/Ask stays a SegmentedControl. - Inputs:
value;options(value,label, optionalbadge, optionalbadgeAriaLabel);onChange(value);ariaLabel(the caller's catalog label:forum.modeLabelinForumBoard,shops.countryLabelinShopsCountryFilter); optionalvariant('field'by default, or'chip'). - Returns: A relative wrapper with the combobox button and, only while open, the listbox. The field listbox is absolutely anchored. Once the chip and frame are measured, the chip listbox is a fixed DOM portal placed inside the frame via
fitBoxInFrame; its wrapper usesoverflow-clipand does not create another scroller. Until placement is available it uses the absolute fallback.
Function: IconButton
- Purpose: Icon-only control with a required
aria-label, variant (primary/secondary/ghost), size (sm/md/lg/xl), and optionaltoneapp(default) ordarkfor marketing-ink shells (ghost+dark is paper hover andfocus-visible:outline-paper).smis 24px paint with a 44px::beforehit slop;mdis 44px;lgis 48px;xlis 56px (the floating + on the forum home). - Inputs: Native button props;
aria-labelis required for accessible naming. Defaultvariant="secondary",size="md",tone="app",type="button". - Returns / side effects: A
<button>wrapping the icon child. No network. Used for attach/post/pay/copy/dismiss controls on the forum board and the handbook copy-link on marketing ink. - Used by:
ForumBoard,WelcomeScreen(the +),InboxScreen,HandbookImageViewer,HandbookLightbox,ContactScreen,NameForm,RulesSetup,HandbookCopyLink,WalletSend,WalletOwnAddress,FondDeposit(on-chain Copy).
Function: Card
- Purpose: Primary app content panel using semantic card tokens (
bg-app-card, border, shadow) with optional max-width (sm/md/xl).surfacedefaulttruedraws that nested visual panel.surface={false}is a width + flex + gap column for page body inside the AppShell frame (no radius, border, bg, shadow, orp-8). Card never hosts page chrome. - Inputs:
children, optionalclassName, optionalmaxWidth(defaultsm), optionalsurface(defaulttrue;falseomits panel classes). - Returns / side effects: A
<section>wrapper. No network. Nested panel for public notes and overlays; page-body columns (LoginCard, profile, welcome, inbox) usesurface={false}. - Used by:
PublicMessageLoader,LoginCard, profile and setup screens.
Function: AmountEntry
- Purpose: Every typed amount. Gift
SegmentedControl(₿ and the member's fiat code) plus the other unit under the field.fixedUnitis the explicit Pay-more exception: the input stays in the loan unit, omits the switch, and keeps the other unit as its live counter.keypad(the/pos/amountpage only) replaces the input with a non-focusable amount and an always-visible 3-column keypad. The page heading is already Amount, so the keypad does not repeat it; the amount keeps that name for assistive tech. Bitcoin offers no decimal key and ignores a typed decimal. Fiat shows the number-format decimal and keeps two fraction digits. A key scales down and darkens while it is held. When the amount changes and the device can vibrate, and reduced motion is off, it vibrates for 10 ms. Other screens keep the input. Switching the keypad to fiat rewrites the draft with the number-format decimal. Bitcoin shows the preferred fiat. Fiat showsformatBitcoin. The input box, its placeholder, and where the digits start do not change when the unit changes. A numeric placeholder is not rewritten. The switch and the counter do change. A signed-in toggle savesaccount.amountUnitthroughsaveAmountUnit(POST/me/amount-unit), the same save as the Settings Default amount row. No session keeps the choice on the control and starts at ₿.rateDayis the current spot rate (useSpotRate). While the preferred fiat has no usable rate, that fiat is a disabled option on the switch (₿ stays), the field shows ₿ even whenaccount.amountUnitisfiat, and the line under the field reads No exchange rate yet (amount.noRate) where the fiat would be, typed or not, so typing does not move the layout. A fixed fiat field instead stays in fiat and shows the same no-rate line. When the rate arrives the field followsaccount.amountUnitagain. Once a price is loaded the hook keeps it, so a fiat draft does not lose its rate. Only a later answer that prices other currencies but not this one can take it away; then the draft is kept in fiat and the line under it reads No exchange rate yet, and the point of sale answers This amount cannot be converted to bitcoin. Enter it in ₿. instead of a whole-number error. Pressing ₿ on a fiat draft that cannot be converted switches to an empty ₿ field. A locked invoice shows the sat amount and disables the switch.layout="composer"(inbox) puts the switch beside the input.layout="inline"(forum reply) puts the amount before the switch on one line. Both keep the label for assistive tech only and put the counter under the input. - Inputs:
label,value,onValueChange,rateDay(current spot rate ornull), optionalid,disabled,fixedUnit(btcorfiat; suppresses the switch),placeholder,className,lockedSats,counterSats,onUnitChange,layout(fielddefault,composer, orinline), optionalkeypad(default false; the/pos/amountpage only), and optionalfiatCode. WithoutfiatCodethe switch and counter use the member's preferred fiat; a fixed-fiat loan passes its loan currency so its typed decimal stays the api amount. WhencounterSatsis notnull, it is the authoritative bitcoin counter: it takes precedence over spot conversion and over the no-rate copy.LoanPayMoreuses it to keep the API-paired bitcoin amount beside a fixed-fiat Max selection even without a usable current rate. - Returns / side effects: A labeled input, or with
keypada non-focusable amount plus the keypad and no input. The keypad does not show the label again. The switch unlessfixedUnitis set, and a counter line when an amount is defined; the counter line folds in and out (Collapse) instead of pushing the controls under it at once. Signed-in toggle callssaveAmountUnit; when the latest save fails, its rollback restores a convertible draft in the unit the server kept and keeps a draft that cannot be converted in the unit the member chose. No other network. The session comes fromuseActiveSession: while a login is still opening its wallet, the chosen unit stays local and is not saved on the account. - Used by:
ForumAskWizard,ForumBoardpay sheet and reply,InboxScreen,PayLinkScreen,PosAmount,WalletSend, andLoanPayMore.
Function: Field
- Purpose: Labeled text input or textarea using shared app field tokens; id is generated from the label when omitted. The label is a sibling linked by
htmlFor, so typed input does not become part of the accessible name. Optional hint and error copy is rendered directly under the control. - Inputs:
label, optionalid/className/hint/error, optionalerrorAnnounce(addsrole="alert"for errors that arrive after an action, not live typing errors),multiline(textarea when true), plus native input or textarea attributes. - Returns / side effects: A sibling
<label htmlFor>and<input>or<textarea>. Hint and error spans receive stable ids; an error setsaria-invalidand extendsaria-describedbywith the message id. The error span getsrole="alert"only whenerrorAnnounceis true. No network. - Used by: Shared labeled text primitive, including shop name, address, and account fields. Amount fields use
AmountEntryinstead.
Function: APP_HEIGHT_BOOTSTRAP_SCRIPT
- Purpose: Blocking bootstrap IIFE string injected as a raw head script before paint. Sets
--app-heightto the visible viewport (visualViewport.height, elseinnerHeight) and writesvisualViewport.offsetTopto--app-offset-top. The offset is never added into the height and the script does not takemaxwithinnerHeight. A taller frame would be a second scroll. Scale guard: skips both writes whenvisualViewport.scaleis present and not ≈ 1. - Inputs: None (constant string).
- Returns / side effects: Non-empty IIFE source mentioning
visualViewport,--app-height, and--app-offset-top. It does not mentionMath.maxand it does not add the offset into the height. - Used by:
RootLayout<head>script.
Function: AppHeightViewport
- Purpose: Minimal visual-viewport fields (
height, optionaloffsetTop, optionalscale) used to resolve--app-heightand--app-offset-topwithout depending on the DOMVisualViewporttype in tests.offsetToppositions the body and is not part of the height. - Inputs:
heightin CSS pixels; optionaloffsetTop; optionalscale(omit when unknown — do not passundefined). - Returns / side effects: A structural type only — no runtime value. Callers pass
{ height }or{ height, offsetTop, scale }intoresolveAppHeightandresolveAppOffsetTop. - Used by:
resolveAppHeight,resolveAppOffsetTop;useAppHeight(livewindow.visualViewport).
Function: resolveAppHeight
- Purpose: Chooses the pixel value for
--app-height. The result isvisualViewport.height(elseinnerHeight).offsetTopis not added. A frame taller than the visible viewport would scroll the document under the one scrollport. Pinch-zoom skip: returnsnull(caller must not write) whenscaleis present and not ≈ 1 (|scale - 1| > 0.01). Null/undefined visualViewport falls back toinnerHeight. - Inputs:
innerHeight(window.innerHeight);visualViewport(window.visualViewportor a stub; null/undefined allowed;offsetTopoptional and not added into the result). - Returns / side effects: Rounded CSS-pixel height, or
nullto skip the write. No DOM writes of its own. - Used by:
useAppHeight(AppHeightSync); bootstrap IIFE inlines the same visible-height path.
Function: resolveAppOffsetTop
- Purpose: Chooses the pixel value for
--app-offset-top, which positions the fixedbodyon the visual viewport. The value is roundedvisualViewport.offsetTop, or 0 when the viewport or the offset is missing. It is never added into--app-height. Pinch-zoom returnsnullso the caller skips both writes. - Inputs:
visualViewport(AppHeightViewportor null/undefined).scalepresent and not ≈ 1 (|scale - 1| > 0.01) skips the write. - Returns / side effects: Rounded CSS-pixel offset, 0 when there is no viewport, or
nullwhile pinch-zoomed. No DOM writes of its own. - Used by:
useAppHeight(AppHeightSync); the bootstrap IIFE writes the same offset before paint.
Function: useAppHeight
- Purpose: After hydration, keeps
--app-heightequal tovisualViewport.height(elseinnerHeight) and--app-offset-topequal to the visual-viewport offset so the fixed body sits in the visible area. The offset is never added into the height. Pinch-zoom skips both writes. Viewport resize and scroll reveal the focused field; focus does the same on the next animation frame. - Inputs: None (reads
window.visualViewport/innerHeightinside auseEffect). - Returns / side effects:
void. Sets--app-heightand--app-offset-topondocument.documentElement. Registers window resize/orientationchange, document focusin/focusout, and visualViewport resize/scroll listeners; cleans them up on unmount. Reveals the focused input, textarea, or select inside the active scrollport. One exception is scoped to the forum home writer ([data-writing-composer], the writer layerForumBoardrenders withwriter): iOS reports the taller viewport only after the keyboard has slid away. Closing the writer first takes the focus out of it (WelcomeScreen), so the keyboard closes as a focus change. When the focus leaves that writer and no other text field takes it, the hook writes at once the height it measured when the focus came into the writer from no text field (a re-entry while a hold is still on keeps the held height) and offset 0, and holds them until the viewport reports that height, another text field takes the focus (a focused button keeps the hold), the width or orientation changes, or one second has passed. Entering the writer from another text field measures nothing, so leaving it afterwards holds nothing. Leaving any other field (a reply, the inbox, a wizard, a form, wallet Send) writes the visible viewport as before. - Used by:
- **AppHeightSync (same file; root layout mount) - Every hydrated app page (via that mount) - Fill/flow AppShell layouts** that consume --app-height
Function: AppHeightSync
- Purpose: Client-only root mount that calls
useAppHeightso--app-heightstays the visible viewport height and--app-offset-topkeeps the fixed body on that viewport after the blocking bootstrap script runs in<head>. The offset is never added into the height. - Inputs: None.
- Returns / side effects: Renders
null; side effect is the hook. Mounted as the first child of<body>inRootLayout. - Used by:
- **RootLayout** (src/app/layout.tsx) - All app and marketing routes under that layout - **useAppHeight consumers** that rely on a single shared mount
Function: AppShell
- Purpose: App page shell driven by
--app-height. Always draws one page frame,rounded-3xl.fillandflowshare that geometry: locked height, framegrow shrink basis-0 self-stretch(notflex-1), frame-header chrome row, then one positioned frame body ([data-app-body], a Tailwindgroup/body,relative flex min-h-0 flex-1 flex-col) holding the notices, the header host, one[data-scrollport](Scrollport), the footer host and the overlay host. The document does not scroll. Prefer this over Tailwind viewport-height utilities on app routes. Chrome (wordmark + Menu / language) is the frame’s first row ([data-app-chrome],px-5 pt-4 pb-1).<main>has nooverflow-hidden. The frame ([data-app-frame]) publishes its content-box width asframeWidth.[data-menu-scrim-host]sits on the frame.[data-menu-sheet-host](px-5, the same horizontal inset as the page) and[data-scroll-page](px-5 py-4) sit inside the one scrollport; the header slot ispx-5and the footer hostpx-5with a bottom padding ofcalc(1.25rem - 0.5rem * var(--footer-collapse, 0)):1.25rem(aspb-5) wherever the frame body carries no--footer-collapse,0.75remwhen it is 1 (WalletFooterActions), gliding (duration-320 ease-glide) only while the body carriesdata-footer-snap; 0 while the body carriesdata-footer-fold(the forum home's folded Receive / Send), gliding there and back (duration-280 ease-glide) only while it carriesdata-footer-folding. Card never hosts page chrome. Neverjustify-centeron<main>or the scrollport. The center wrapper setsjustify-content: centerand thensafe center, so content that fits stays centered, and wheresafeis supported a thread taller than the frame starts at the top and remains scrollable inside that one scrollport. - Inputs:
children, requiredmode(fill|flow; both values render the same frame), optionaltopLeft/topRight, optionalclassName, optionalalign(start|center). The<main>inset ispx-3 py-2, below 360pxpx-2, and the chrome rowpx-5, below 360pxpx-3, so the signed-in header fits at 320px. - Returns / side effects: A
<main>layout with a rounded page frame, chrome row, header/footer/overlay portals, and inner scroller.useAppShellScrollerreads that scroller from context; the context also carries the frame body (bodyEl) and the overlay host (overlayEl, adisplay: contentselement after the footer, so a layer positions itself against the frame body: from the chrome row's bottom edge to the frame's). No network. MountsPasskeyRenewNoticewhilewalletRequired === false; wallet setup has no shell-level visual surface. - Used by:
- Fill and flow app routes (LoginPage, DonatePage, setup, contact, inbox, notifications, public note, ProfilePage, WalletPage, LoanRepayPage, ShopsPage, ViewProfilePage, MemberProfilePage) - **PageChrome** (still mode="flow"; AppShell draws the unified frame — welcome and public rules) - **AppShellHeader / AppShellFooter / AppShellOverlay / AppShellTopLeft slot registrars - useAppShellScroller** (ForumBoard pull-to-refresh, ForumLoader atTop / scroll-to-top, InboxScreen open-thread pin to bottom / one-shot list reset to top)
Function: Scrollport
- Purpose: The only layout scrollport. Renders
[data-scrollport]. Overflow is theglobals.cssrule, not a Tailwind utility: clip untildata-scroll-active, then the active port scrolls vertically only (overflow-x: clipandoverflow-y: auto). The innermost bound port scrolls. Among siblings, the most recently bound one scrolls and getsdata-scroll-active. Every other port getsdata-scroll-locked.htmlandbodystayoverflow: clip. - Inputs:
children, optionalclassName, optionalscrollRef, optionalonClick. - Returns / side effects: A
div. Binds on mount and releases on unmount. No network. - Used by:
AppShell, marketing layout,NotFound,HandbookLightbox,PlaceField(the place dialog sheet body).
Function: bindScrollport
- Purpose: Push a scrollport onto the active stack and resync. Binding the same element twice does not stack it twice. The innermost bound port may scroll; among those, the most recently bound. That port gets
data-scroll-active. - Inputs: The mounted scrollport element.
- Returns / side effects: Sets
data-scroll-activeon the port that may scroll anddata-scroll-lockedon the others, and clips stray scrolling elements. No network. - Used by:
Scrollporton mount.
Function: releaseScrollport
- Purpose: Remove a scrollport from the active stack and resync. The innermost remaining port scrolls; among siblings, the most recently bound. Releasing an element that is not on the stack does nothing.
- Inputs: The unmounted scrollport element.
- Returns / side effects: Sets
data-scroll-activeon the port that may scroll anddata-scroll-lockedon the others, and clips stray scrolling elements. No network. - Used by:
Scrollporton unmount.
Function: syncScrollSurfaces
- Purpose: Leave exactly one scrollport unlocked. Every other element whose computed overflow can scroll (
auto,scroll, or legacyoverlay, on either axis) is forced to clip. Textareas grow to their text instead. Inputs and selects are left to the browser. - Inputs: None. Reads the active stack and
document.body. - Returns / side effects: Sets
data-scroll-activeon the one port that may scroll anddata-scroll-lockedon the others, and may set inline overflow or textarea height. No network. - Used by:
bindScrollport,releaseScrollport, andScrollSurfaceGuard.
Function: ScrollSurfaceGuard
- Purpose: Root watcher. On mount, and whenever class, style, or children change, it runs
syncScrollSurfacesso a scrolling overflow added later cannot become a second surface. Typing in a textarea resyncs immediately so the field grows instead of scrolling. - Inputs: None.
- Returns / side effects: Renders
null. Observesdocument.bodyand listens forinput. Disconnects on unmount. No network. - Used by:
RootLayout, mounted once for every page.
Function: useAppShellScroller
- Purpose: Returns the AppShell inner
[data-scrollport]element, ornulloutside AppShell. - Inputs: None (reads AppShell context).
- Returns / side effects:
HTMLElement | null. No network. - Used by:
ForumBoard(pull-to-refresh pageScrollTop),ForumLoader(atTop / scroll-to-top),InboxScreen(open-thread pin to bottom / one-shot list reset to top), AppShell unit tests.
Function: AppShellHeader
- Purpose: Registers flex-none header content into the nearest
AppShellpage frame (DOM portal into the shell<header>host). Without anAppShellancestor, renders children inline. - Inputs:
children(typically an onboardingh1). - Returns / side effects: Portal into the shell header host when present; otherwise the children. Layout only.
- Used by:
- **NameSetup - RulesSetup**
Function: AppShellFooter
- Purpose: Registers flex-none footer content (CTAs) into the nearest
AppShellpage frame (DOM portal into the shell<footer>host;px-5 pb-5on that host). Without anAppShellancestor, renders children inline. - Inputs:
children(typically Continue / Skip / Agree buttons). - Returns / side effects: Portal into the shell footer host when present; otherwise the children. Layout only.
- Used by:
- **NameForm (onboarding) - RulesSetup**
Function: AppShellOverlay
- Purpose: Registers a layer over the frame body of the nearest
AppShell: everything under the header row (notices, header slot, scrollport, footer) down to the frame's bottom edge. DOM portal into the shell's overlay host, the last child of[data-app-body]. The layer positions itself against that body (absolute inset-0, or a smaller box such as the +), so it starts right under the chrome row, moves with the frame when the visible viewport changes (the iOS keyboard), and needs no measured screen coordinates. Without anAppShellancestor, renders children inline; before the host mounts, renders nothing. - Inputs:
children(the layer). - Returns / side effects: Portal into the shell overlay host when present; otherwise the children. Layout only. A layer that should scroll is its own
Scrollport, which becomes the active one while it is mounted. - Used by:
- **ForumBoard (the forum home writer) - WelcomeScreen (the floating +**)
Function: AppShellTopLeft
- Purpose: Registers top-left chrome into the nearest
AppShellvia DOM portal; child registration wins over the pagetopLeftprop. The host is the frame chrome row ([data-app-chrome]), not a Card. Without anAppShellancestor, renders children inline. - Inputs:
children(back control + wordmark, etc.). - Returns / side effects: Portal into the shell top-left host when present; otherwise the children. Layout only.
- Used by:
- **RulesSetup (chapter back + wordmark) - WalletScreenView** (Wallet Back and wordmark; wins over the page topLeft) - **AppShell unit tests** (child portal wins over the page topLeft prop)
Function: AppShellTopLeftExtra
- Purpose: Registers extra chrome to the right of the top-left cluster via a DOM portal into the frame chrome row. Without an
AppShellancestor, renders children inline; before the host mounts, renders null. - Inputs:
children. - Returns / side effects: Portal into the shell top-left-extra host when present, inline children without shell context, or null while the shell host is not mounted. Layout only.
- Used by:
ShopsCountryFilter.
Function: PageChrome
- Purpose: Wrapper around
AppShell(stillmode="flow") with optional top-left (wordmark) and top-right (menu / language) slots. Chrome is the page-frame header, not page-absolute. PreferAppShelldirectly on app routes. - Inputs:
children, optionaltopLeft, optionaltopRight, optionalclassNameon the outer<main>. - Returns / side effects: Layout only (
AppShell mode="flow"; AppShell draws the unified frame). No network. - Used by: Flow app routes (
WelcomePage,RulesPage) plus unit tests and theuibarrel. Fill routes useAppShelldirectly.
Function: Wordmark
- Purpose: Text brand mark
21.gifts(header 17px/700, footer 15px/700). Link whenhrefis set; otherwise a<span>(marketing footer). - Inputs: optional
href, optionaltone(app/dark), optionalsize(header/footer, defaultheader), optionalclassName, optionalonClickforwarded to the link only. - Returns / side effects: A Next.js
<Link>or<span>. No network. - Used by:
HomeWordmark,ForumHomeWordmark,MarketingFooter,ProfileChromeLeft,RulesSetup, setup name/username pages, andRulesPageChrome.
Function: ForumHomeWordmark
- Purpose: Welcome-page wordmark: linked
21.giftsto/welcomethatpreventDefaults and dispatchesFORUM_HOME_EVENTsoForumLoadercan scroll to top and apply new notes without a full reload. - Inputs: None. Uses
WordmarkandFORUM_HOME_EVENT. - Returns / side effects: A client wordmark link. Dispatch only; no fetch of its own.
- Used by:
WelcomePage.
Function: HomeWordmark
- Purpose: Session-aware header wordmark: linked
21.giftsto/welcomewhenuseHydrateSessionis ready anduseAuthStorehas a session, otherwisepublicHref. WhenpublicHrefis omitted, the unsigned target is/. Real navigation (nopreventDefault, unlikeForumHomeWordmark). - Inputs: Optional
tone,size,className,onClickforwarded toWordmarkwhen set. OptionalpublicHref: the target without a session; with a session the link is still/welcome. UsesuseHydrateSessionanduseAuthStore. - Returns / side effects: A client
Wordmarklink. Hydrates the session; no other network of its own. - Used by:
MarketingHeader,LoginPage,DonatePage,ViewProfilePage,PayLinkScreen,RecoverPage,RecoverScreen,RulesPageChrome.
Function: PublicMessageChrome
- Purpose: Client chrome wrapper for public
/messages/[id],/messages/[id]/author,/messages/[id]/repayment-list, and/{npub}: when a session is hydrated (ready && session !== null), mounts signed-in shell (ProfileChromeLeft+SignedInChrome); otherwiseProfileChromeLeftwith wordmark href/and lightLanguageSwitcher. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. - Inputs:
children(public note/author/ledger content orShopScreen). UsesuseHydrateSessionanduseAuthStoreforsession. - Returns / side effects: Fill
AppShell(align="center") with the matching top-left / top-right slots aroundchildren. No network beyond session hydration. - Used by:
PublicMessagePage,ExternalAuthorPage,RepaymentListPage,ShopPage.
Function: ShopPage
- Purpose: Next.js page for
/{npub}. Rejects every segment except a valid npub or 64 lowercase hex; api 404 usesnotFoundand 410 renders the anonymous unlisted state. Only an exact answer renders the shop: status 200 (not any 2xx) for an npub whoseshop.npubequals the segment, or a 301 to a valid npub for a hex key. Any other status, a 200 for a hex key, a 200 for a different npub, and unusable data render the retryable state. - Inputs: Dynamic
npubroute segment. Calls public apiGET /shops/:npubwith manual redirect handling, no session, andAbortSignal.timeout(API_FETCH_TIMEOUT_MS)(2500 ms, fromsrc/lib/api-timeout.ts) — the same limit as metadata; a timeout or abort renders the retryableunavailablestate. The loader is wrapped in Reactcache, sogenerateMetadataand the page share one api call and one answer per request. - Returns / side effects:
ShopScreeninsidePublicMessageChrome, or a 308permanentRedirectfrom a known hex key to/{npub}after the api's 301. Also exports shopgenerateMetadata. Every photo URL goes throughresolveShopPhotoUrlagainstgetApiUrl(): a relative path becomes an api URL, and a photo that is not http(s) is dropped before the page andog:imageuse the list. - Used by: Route
/[npub].
Function: ShopScreen
- Purpose: Public shop identity body: name, description,
ForumPhotoGallery, text address when the shop has a pin, optional one-marker map, forum-note link, optional NIP-05, npub copy control, and an optional payment block like the profile cards: heading 21.gifts address, thegiftsLightningAddress(payUsername, host)line, then the Open CryptoPay QR withprofileQrLogo; the address line and the QR use the browser host and appear only after mount. When the shop has a pin the gallery follows the description and the payment block is last. Whenplaceis null the overline Shop sits above the name, the payment block sits under the description, the photo follows the npub, and the address heading and the map are omitted. Whenaddressis null the street lines are omitted. - Inputs: Discriminated
state:readywith a parsedShop,gone, orunavailable. Uses translations and browser hostname; asksfetchMapsKeyonly while ready andplaceis non-null. Renders only absolute http(s) photos (resolveShopPhotoUrlwithout an api base). A forum still is then loaded from the same-origin proxy (sameOriginShopPhotoSrc). Photos are numbered in order. - Returns / side effects: Ready card, anonymous unlisted heading, or
shop.error(Could not load this shop. Please try again.) plusview.retry. Retry callsrouter.refresh; a non-empty maps key mountsGoogleMapCanvasfor one point. When the canvas callsonUnavailable(script failure, missinggoogle.maps, or a rejected key), the map frame is removed and the address stays, the same page as without a key. - Used by:
ShopPage.
Function: resolveShopPhotoUrl
- Purpose: Make one public shop photo URL safe to render and to publish as
og:image. - Inputs: The photo
urlfromGET /shops/:npuband an optional api base. With the base (trailing slashes trimmed), a root-relative/pathis appended after the full base, path included (https://x/v1+/a→https://x/v1/a), so an api behind a path prefix still serves its photos; any other relative path resolves against the base plus/, and a protocol-relative//host/…stays a host, not a path. Without it, only an absolute URL is accepted. - Returns / side effects: The absolute
http:orhttps:URL, or null for every other scheme (javascript:,data:, …) and for an unparsable value. No side effects. - Used by:
ShopPage(withgetApiUrl()),ShopScreen(without a base).
Function: sameOriginShopPhotoSrc
- Purpose: Load a public shop still through the app's same-origin photo proxy so CSP
img-src 'self'allows it. The api publishes absolute forum photo URLs. - Inputs: An absolute photo URL already accepted for rendering. A forum still is
/messages/{id}/photo.jpg,.jpeg,.png, or.webp, or an extra still at/messages/{id}/photo/{1-9}.{ext}, including when that path sits under an api prefix such as/v1. - Returns / side effects:
/messages/{id}/photo.jpgor/messages/{id}/photo/{n}.jpg. The extension is.jpgbecause the api serves the stored bytes for every image extension. Any other URL, including a relative path and a broken percent-encoding, is returned unchanged. No side effects. - Used by:
ShopScreen.
Function: NpubCopyButton
- Purpose: Shared icon-only npub copy control extracted from
ExternalAuthorProfile; Copy becomes a check named Copied for 1200 ms. - Inputs:
npubstring and the existingforum.externalProfileCopy/forum.externalProfileCopiedcatalog keys. - Returns / side effects:
IconButton; writes throughnavigator.clipboard, with the hidden-textarea fallback, and clears pending work on unmount. - Used by:
ExternalAuthorProfile,ShopScreen.
Function: GoogleMapCanvas
- Purpose: Shared Google Maps JavaScript canvas used by the all-places screen and the one-shop public page. It draws the supplied markers, centers one point at zoom 14, or fits several points and caps fitted zoom at 14.
- Inputs: Browser maps key or null, marker points, anchor,
fitAll, a test id, and an optionalonUnavailablecallback. A null key leaves its frame empty and does not callonUnavailable;ShopScreenomits that frame entirely. - Returns / side effects: Bounded map frame. Loads Google's script through the shared
loadGoogleMaps, subscribes to a rejected key throughonGoogleMapsAuthFailure(unsubscribes on unmount), clears Google's authentication-failure dialog from the frame and draws nothing more after it, and leaves surrounding text usable on script failure. A script failure, a missinggoogle.mapsafter the load, or a rejected key calls the latestonUnavailable; a failure that settles after unmount does not.ShopScreenpasses it and removes the map;PlacesMapScreendoes not, so its frame stays empty above the list, as without a key. - Used by:
PlacesMapScreen,ShopScreen.
Function: PublicMessagePage
- Purpose: Next.js page for
/messages/[id]— public HTML note by UUID. Unsigned visitors see a read-only thread. Signed-in React on the root note, copy, reply, and Gift on a payable nested reply run throughPublicMessageLoader→PublicMessageThread. NoOnboardingGate, top-level composer, or envelope. Wrapped inPublicMessageChrome(signed-in or unsigned chrome depending on hydrated session). - Inputs: Dynamic route params (
id). - Returns / side effects:
PublicMessageLoaderinsidePublicMessageChrome(chrome is no longer always unsigned Wordmark + LanguageSwitcher). Also exportsgenerateMetadatafor per-note Open Graph / Twitter tags. Unsigned chrome isProfileChromeLeftwith wordmark href/, not a bare wordmark. - Used by: Route
/messages/[id].
Function: generateMetadata
- Purpose: Next.js App Router metadata for six pages. On
/messages/[id], loads the public note vialoadPublicMessageForOgand maps it throughpublicMessageOgMetadataso crawlers see the author, text, and photo without running JS. Missing or failed fetches inherit the root layout preview. On/,/about,/donate, and/rules, each implementation reads the language withgetRequestLocale()and callsmarketingMetadatawith that locale, an English title, and an English description that stay the same on every language URL. Home titleHelp people with Bitcoin | 21.gifts, descriptionRead what people share, react to a post and donate Bitcoin directly to the person's wallet. 21.gifts does not hold your donation and keeps no share.About titleWhat 21.gifts stands for | 21.gifts, descriptionIn the forum, people can ask for help and donate Bitcoin to one another. Three convictions stand behind 21.gifts.Donate titleDonate Bitcoin and help someone | 21.gifts, descriptionSign in and open a post in the forum. Write a reaction under it, add an amount and pay from your wallet. The Bitcoin goes to the person who wrote the post.Rules titleLiving room rules | 21.gifts, descriptionYou are a guest in a living room with the windows open. Everything you write here is public, and anyone walking past can read along.A shop on/{npub}loads apiGET /shops/:npubthrough the same request-cached loader asShopPage, usesAbortSignal.timeout(API_FETCH_TIMEOUT_MS)(2500 ms), inherits root metadata on missing, invalid, timed-out, or unusable responses, and builds description,og:description, andtwitter:descriptionwithogDescriptionTextand the default image altOG_IMAGE_ALT. - Inputs:
/messages/[id]takes{ params: Promise<{ id: string }> }from the dynamic route. The four public pages take no route params. Each of them callsgetRequestLocale()and passes that locale intomarketingMetadatawith path/,/about,/donate, or/rules./{npub}takes{ npub }from the dynamic route. - Returns / side effects:
Promise<Metadata>./messages/[id]returns per-note Open Graph / Twitter tags when the note is found, or{}so the site-wide layout preview is inherited, and does not render the visible page. Each public page returns the English title and description above, a canonical URL for the language of the request (/en,/de,/es,/fil, and the same prefix on/about,/donate, and/rules), reciprocalhreflanglinks foren,de,es, andtl(Filipino pages; the URL prefix stays/fil) plusx-defaultto the unprefixed path, and Open Graph / Twitter image/og.png. Those four do not render the visible page./{npub}returns the shop name,ogDescriptionText(description, name)(trimmed,{name} on 21.giftswhen blank, cut above 300 code units with…), the first photo (or/og.png), and the relative canonical/open-graph URL/{npub}resolved by rootmetadataBase, and does not render the visible page. - Used by: Route
/messages/[id](PublicMessagePage). Routes/,/en,/de,/es, and/fil(Home). Routes/about,/en/about,/de/about,/es/about, and/fil/about(AboutPage). Routes/donate,/en/donate,/de/donate,/es/donate, and/fil/donate(DonatePage). Routes/rules,/en/rules,/de/rules,/es/rules, and/fil/rules(RulesPage). Route/[npub](ShopPage).
Function: loadPublicMessageForOg
- Purpose: Server fetch of api
GET /messages/:idfor Open Graph. Invalid UUIDs skip the network. Timeouts, non-OK responses, JSON/schema failures, and thrown errors (getApiUrl, network, abort) all returnnulland never throw. - Inputs:
idstring from the route (forum message UUID). - Returns / side effects:
ForumMessageornull. Usescache: 'no-store',Accept: application/json, andAbortSignal.timeout(API_FETCH_TIMEOUT_MS)(2500 ms; the constant lives insrc/lib/api-timeout.tsand also boundsShopPageand the/l/[code]lookup). - Used by:
generateMetadataon/messages/[id].
Function: ogDescriptionText
- Purpose: Shared link-preview description for a public note and a public shop: trimmed text, or `
${name} on 21.giftswhen the text is blank — never the marketing layout copy. Text longer than 300 UTF-16 code units is cut to 299 plus…`. - Inputs:
text(note text or shop description) andname(author or shop name). - Returns / side effects: Description string of at most 300 code units. No I/O.
- Used by:
publicMessageOgMetadata, shopgenerateMetadataon/[npub].
Function: publicMessageOgMetadata
- Purpose: Maps a loaded public note (or
null) to Next.jsMetadata. Found notes use the author name as title and never the marketing layout description, even whentextis empty. Photo notes setog:imageto/messages/{id}/photo.jpg; others keep/og.png. A note with anyviavalue (written without a 21.gifts account) gets fully generic metadata instead: titleExternal author on 21.gifts, descriptionA reply from someone outside 21.gifts who sent bitcoin to a post., and always the default/og.pngimage — nothing from the note'sname,textor photo reaches a link preview. Both strings are plain English constants, not from the catalog. - Inputs: Route
idandnote(ForumMessage | null). - Returns / side effects:
{}whennoteisnull. For a note with aviavalue the generic External title, description and default image described above. Otherwise title, description (trimmed text or `${name} on 21.gifts, truncated above 300 code units with…), Open Graph (type: website,urlhttps://21.gifts/l/plus the first 8 hex of a UUID id (otherwisehttps://21.gifts/messages/{id}),siteName21.gifts), and Twittersummary_large_image`. - Used by:
generateMetadataon/messages/[id].
Function: PublicMessageLoader
- Purpose: Client loader for the public thread page: validates UUID, waits for hydrate
ready, then fetches. Staff (roleAtLeast(account.role, 'moderator')+ session) usefetchForumMessage(session, routeId)andfetchReplies(session, root.id)so a soft-hidden row can load; others usefetchPublicMessage(routeId)/fetchPublicReplies. IfparentIdis set, fetches that parent (null→ missing) then replies of the parent. Ready only with root + replies (empty replies → parent only). Replies throw → error + Try again (whole chain). Until hydrateready, onlyforum.loading(no fetch, no cards). After ready, when the loaded root or the highlighted reply hasdeletedAt/deletedBy, arole="status"forum.hiddenNoticeline sits above the thread (permalink target). Unsigned visitors (no session or no account) keep thePublicThreadCardstack (no pay/copy): vertical stack parentCardthen reply Cards withpl-4. Gift-only replies (empty text, sats > 0): sats line viaformatBitcoinplus optional preferred-fiat·formatFiatDisplayof the amount stored when the payment was made (a stored string as-is, a null or missing field on a passedstoredobject shows the current spot, and stays off the line only when that spot is not loaded), no empty<p>. When the route id is a reply, that unsigned reply card (or wrapper) hasdata-permalink-target="true"andring-1 ring-app-fg. Photo/video per unsigned card viaforumPhotoSrc(<img src>/messages/{id}/photo.jpg, extra stills/photo/{n}.jpg) andforumVideoSrc. Unsigned gallery isForumPhotoGallery(horizontal snap row,data-scroll-x, 88% peek,current/totalchip, dots);data-photo-indexkeeps the original still index when an earlier extra still fails to load. Translate (Languages icon) under unsigned note and reply bodies viaNoteTranslatewhen the language differs from the UI locale. Avia === 'nostr'reply or note shows a non-interactive External<span>badge next to the name (no hint state on this card) and renders its body as plain text (TranslatableNoteBodyplain) instead ofForumQuotedBody. Each unsigned card is ₿ plus optional preferred-fiat·formatFiatDisplayof the amount stored when the payment was made (useFiatPreference; cookie, otherwise locale default); a missing string shows the current spot, and stays off the line only when that spot is not loaded. On an unsigned reply withreceivedSatsgreater than zero, that card usesReplyDirectionAmountsinstead of the single amount: sent and received stay separate lines and are not added. A top-level card keeps one amount, the collected total.useSpotRatefeeds the pay sheet and an unpaid invoice preview. A posted goal bar uses the stored visitor snapshot when that string exists, and shows the current spot beside bitcoin when it does not, and bitcoin alone only when that spot is not loaded. A top-level unsigned note with a positivegoalSatsalso showsForumGoalBar, and the same Loan, Donation, or #Shop tag as the forum beside the name. Whenready && session && accountand the root is loaded, mountsPublicMessageThreadinstead of the unsigned cards, passingseedReplyas the highlighted hidden reply (omit the prop when none). Auth CTA once below either stack fromuseHydrateSessionis Log in when unsigned; its href isloginHrefof this note's path and query, read fromwindow.locationas the view stack records them (a query keeps%20, not+), so a login steps back to the note instead of adding a second copy of it. Signed-in visitors have no text back link under the thread. The top-left arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none. - Inputs:
idstring from the route. Also readssessionandaccountfrom the auth store and hydrateready. - Returns / side effects: States loading / missing / error (with Try again) / ready unsigned stack or signed-in
PublicMessageThread. Malformed UUID → missing without an api call. Inline<video>keeps the clip aspect ratio (max-h-80 max-w-full, no full-width black canvas). A failed<video>errorevent hides the player and falls back to the photo when present.NoteTranslateon unsigned note and reply bodies (GET/translateon mount, POST on Translate). Unsigned stack has no pay, composer, copy, or FiatPicker. Hydrate-not-ready is onlyforum.loading(no unsigned cards). A hydrate drop after a note is loaded keeps the cards and showsforum.loadingin the footer. A login whose wallet is still opening counts as signed out here (useActiveSession): the public fetch is used and no notification is marked read until the wallet is open. - Used by:
PublicMessagePage.
Function: PublicMessageThread
- Purpose: Signed-in permalink thread: one root on
ForumBoardwithcomposerHiddenandtruncate={false}so the original body stays full, auto-expand viafetchReplies, and the same React, copy, reply, overlay, photo, and poll behavior as/welcome. Public stills useforumPhotoSrc; a deleted staff row still loads viafetchMessagePhotoas a blob. React (forum.react, lucide Reply) on the root note; Heart (forum.heartAmount“Send ₿21” with a loaded account, otherwiseforum.heart“Send ₿1”) on those same cards after Translate and before React or Gift; on every nested reply Gift when payable (shown disabled withCannotReceiveLabelwhen that reply's author cannot receive yet), copy (forum.copyReplyLink, the reply's own origin/l/<8 hex>, first group of that reply id) always, and trash for staff. StaffonDeletedon the root callsonRootDeleted(loader → missing); a nested reply is dropped from the list. PassespermalinkTargetIdso only a matching nested reply is ringed. OwnspayHostand passes it to ForumBoard: a compose-fee reply invoices 1 sat to 21.gifts on the composer slot (payHost: composer,payMessageId= compose-target note); extra gifts and Gift-open stay on the card (payHost: card). - Inputs:
{ root, highlightId, seedReply?, onRootDeleted }as insrc/components/PublicMessageThread.tsx:rootisForumMessage,highlightIdisstring | null(route id when it is a reply UUID),seedReplyis the opened hidden reply when the route id is a hidden child,onRootDeletedis() => void. Session and account from the auth store. - Returns / side effects: React tree. Auto-expands the root so Write a reaction is available. After Bearer
fetchRepliesof the root, mergeseedReplyinto the list when it is missing so the signed-in board still shows the hidden permalink target. PassespermalinkTargetId={highlightId}andviewerAccountId, so on the viewer's own root the reply form has no Amount field and a reply posts unpaid (isOwnNote; an empty one setsempty). No top-level composer or feed filters. OwnspayHostand passes it to ForumBoard: a compose-fee reply invoices 1 sat to 21.gifts on the composer slot (payHost: composer,payMessageId= compose-target note); extra gifts and Gift-open stay on the card (payHost: card). AWalletRequiredError(apicodewallet_required) on a gift, a paid reply, or a posting fee opens theRequirementsOverlaywalletstep. A paid reaction keeps its text and amount in the disabled form behind the reaction pay sheet (replyPayPreviewonForumBoard); both clear once the payment is seen, and a cancel leaves them in the form. While that sheet is open, the card does not expand or collapse (and on the profile the activity feeds do not switch), as on the forum home. Pay invoices keep the api'ssparkInvoiceso the wallet pays it before the payment request. A reply to a note whose author cannot receive yet (authorCannotReceive) never invoices a gift to the author: an empty one setsempty, and one with text posts unpaid (verified or above) or pays only the 1 sat posting fee.
- Used by:
PublicMessageLoader.
Function: ViewProfilePage
- Purpose: Next.js page for
/view/[viewKey]— public read-only profile by view key. NoOnboardingGate, noSignedInChrome. - Inputs: Dynamic route params (
viewKey). - Returns / side effects: Exports
metadata.referrer = 'no-referrer'.AppShellwithProfileChromeLeft(wordmarkHomeWordmark:/unsigned,/welcomewhen a session is hydrated) and lightLanguageSwitchertop-right; body isViewProfileLoader. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. The card itself has no back control. - Used by: Route
/view/[viewKey].
Function: ViewProfileLoader
- Purpose: Client loader for
/view/[viewKey]. Validates the key, fetches the public profile, and rendersMemberProfileScreen, the same card as/profileand/members/:id. When a session exists and the payload has an id,fetchMemberreplaces the card so hearts and trust match. A failed refetch keeps the public card. Activity isfetchMemberActivityafter that refetch andfetchViewActivityotherwise. Public posts, replies, shops, and credits usefetchViewForumListonly while the card stays public. It passesshareViewKeyso Copy link to this profile writes the current/view/<key>URL, including when the signed-in account is the owner.ViewProfileClaimstays under the card. - Inputs:
viewKeystring from the route. Session fromuseAuthStore. - Returns / side effects: Loading (
forum.loading) / missing (view.missing) / error with Try again / the shared card plusViewProfileClaim(hasPasskeyfrom the public payload). A key that is not 64 lowercase hex is missing and does not call the api.createdAt(epoch ms) becomes an ISO string. Trust stays empty on the public card. Activity failure keeps the card and both charts show their error copy (profile.chartError/profile.loanChartError). A successful empty gift series staysprofile.chartEmpty. An empty loan series renders nothing. The chart is never swapped forforum.loading. - Used by:
ViewProfilePage.
Function: ViewProfileScreen
- Purpose: Presentational read-only identity card matching signed-in profile chrome: heading Profile,
AccountActivityChart, thenLoanBalanceChartdirectly under it (sameactivityFailedflag), About me inside the card (not a forum post; publicAboutMeSectionwithname={profile.name}shows filled text and/or photo, or omits the heading when neither; Languages Translate whenaboutMessageIdis set), name, location, and publicusername@21.giftsrows (labelsname.heading/location.heading/profile.giftsHeading) without edit or Message actions. Unset location showslocation.unset. Missing username showsview.noGiftsAddress. Copy-profile-link on the card (profile.copyLink). When a username is set, a centeredQrCode(labelprofile.giftsQr) under the address encodesopenCryptoPayQrValue(https://<domain>/pl/?lightning=plus the uppercase LNURL ofhttps://<domain>/.well-known/lnurlp/<local>), including on a smartphone. A missing username shows no QR. WhenlightningAddressVerifiedis false, the card shows Can't receive yet (CannotReceiveLabel) instead of the address and the QR. - Inputs:
{ profile, viewKey, received, donated, owed, credit }—receivedisAccountActivity['receivedOverTime']; optionaldonated/owed/creditdefault[]; optionalactivityFailed(default false), passed to both charts asfailed.viewKeybuilds the copy URL/view/<viewKey>.profileincludesaboutMe,aboutMeHasPhoto, andlocation. PublicAboutMeSectionhasPhotofromaboutMeHasPhotowithloadPhoto(fetchViewAboutMePhoto). - Returns / side effects: No menu, logout, back, edit forms, or Message. Copy-profile-link on the card; URL/key never shown as visible text. Language switcher lives on the page, not in this card. When
activityFailedis true and a series is empty, that chart shows its error copy. - Used by: No route. The share link renders
MemberProfileScreen. This card remains for its own tests.
Function: getBuildId
- Purpose: Typed accessor for the build id of this bundle (
NEXT_PUBLIC_BUILD_ID): the deployed commit, ordev. Passkey begin and finish send it asX-App-Build, so the api can refuse a tab that still runs an older build. - Inputs: None.
- Returns / side effects: The baked string. Throws if unset or empty.
next.config.tsbakes it atnext buildfrom Docker ARGNEXT_PUBLIC_BUILD_ID(unset or empty →dev). Not anentrypoint.shplaceholder. - Used by:
startPasskeyRegistration,finishPasskeyRegistration,startPasskeyAuthentication,finishPasskeyAuthentication,startPasskeyRecovery,finishPasskeyRecovery.
Function: LoginsClosedError
- Purpose: Typed error for the api's HTTP 503 answer with
codelogins_closed(LOGINS_CLOSED_CODE) on register begin, register finish, authenticate finish, or social recovery begin or finish: operators closed new logins for an update. Recognised by the body'scodeand that status, never by text; screens show catalog copy. - Inputs: None. The message is
logins_closed. - Returns / side effects: Error instance named
LoginsClosedError.usePasskeyLoginmaps it to statusclosed. - Used by:
startPasskeyRegistration,finishPasskeyRegistration,finishPasskeyAuthentication,startPasskeyRecovery,finishPasskeyRecovery,usePasskeyLogin.
Function: AppOutdatedError
- Purpose: Typed error for the api's HTTP 403 answer with
codeapp_outdated(APP_OUTDATED_CODE) on a passkey begin or finish: a newer app build is live and this tab must reload. Recognised by the body'scodeand that status, never by text; screens show catalog copy. - Inputs: None. The message is
app_outdated. - Returns / side effects: Error instance named
AppOutdatedError.usePasskeyLoginmaps it to statusoutdated. - Used by:
startPasskeyRegistration,finishPasskeyRegistration,startPasskeyAuthentication,finishPasskeyAuthentication,startPasskeyRecovery,finishPasskeyRecovery,usePasskeyLogin.
Function: LoginBlockedNotice
- Purpose: The card body when the api refused to create a session:
closedis the calm status line 21.gifts is updating. Please try again a little later. (login.closed) with nothing to press;outdatedis A new version is ready (login.outdated) with Reload (login.reload), or without it whenreloadis false. - Inputs:
kind:closedoroutdated; optionalreload(defaulttrue): whetheroutdatedoffers Reload. - Returns / side effects: React fragment (icon,
role="status"line, and foroutdatedwithreloada labeledButton). Reload callswindow.location.reload(): only a full page load loads the new build. Nobody is signed in on these surfaces, so the reload loses no wallet held in the tab. Nothing retries on its own. - Used by:
LoginCard,ViewProfileClaim, andRecoverScreen(theblockedstep on/recover, which adds Try again and Start over underclosed, and passesreload={false}foroutdated: only the login card and the profile claim may reload the document).
Function: ViewProfileClaim
- Purpose: Public passkey claim control under the
/view/[viewKey]card. Unclaimed invites (hasPasskeyfalse) bind a passkey to the existing profile (name already set), including when another 21.gifts session is already signed in. - Inputs:
viewKey(64 lowercase hex) andhasPasskeyfrom the public profile. UsesusePasskeyLogin,useAuthStore,useRouter,isInAppBrowser, andInAppBrowserView. - Returns / side effects: Waits for
useHydrateSessionready. Claimed (hasPasskeytrue) →null(even in Telegram, even if signed in). In-app on mount orunsupported→ same card chrome as login wrappingInAppBrowserView(no yellow Activate). Else in a real browser: yellow banner withview.activationRequiredand Activate (view.activate) even whenaccount !== null; click sets a claim-attempted flag,cancel+clearAuthwhen a session exists, thenregister(viewKey)(stays on the view page). Success →returnToView(nextOnboardingPath(account), router)only when that claim was attempted (pre-existing sessions do not redirect on mount). 409 →view.alreadyClaimedplus Fingerprint that callsauthenticate(); after that attempt the yellow Activate banner does not return (successful login hides the control; a dismissed prompt keeps the already-claimed copy). Statusunknownshowsview.claimErrorand Try again callsauthenticate(), neverregister, and never the login unknown card. Other errors / starting stay visible even with a session →view.claimError+ Try again (view.retry) or spinner. When Activate fails because the new passkey gives no PRF output (passkey.erroriswallet.prfUnsupported), the alert iswallet.prfUnsupported(This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.) instead ofview.claimError. After Log in instead, the spinner shows while that login runs, and a failed or unknown attempt shows its claim alert and retry (both also over a held-back session); then the login opens the wallet like any other:WalletLoginCardstands in place until the wallet is open, and stays while the session is held back after it could not be (with the no-PRF or error alert); once open it renders nothing, as before. A stored session held back on a passive visit is not affected. Statusclosedoroutdatedafter Activate or after Log in instead showsLoginBlockedNoticein place of the banner or the claim alert. - Used by:
ViewProfileLoader(ready state only).
Function: fetchViewProfile
- Purpose: Fetches a public read-only profile by view key via the same-origin proxy.
- Inputs:
viewKeystring. - Returns / side effects: Validated
ViewProfile, ornullon 404. Throws on other non-2xx or a body that failsviewProfileSchema. Hits/view-key/${encodeURIComponent(viewKey)}. - Used by:
ViewProfileLoader.
Function: proxyViewGet
- Purpose: Same-origin proxy of api
GET /view/:viewKey(public; no auth). - Inputs: Incoming
RequestandviewKeypath segment. - Returns / side effects: Proxied upstream
Responsefor/view/${encodeURIComponent(viewKey)}. - Used by: App Router
GETon/view-key/[viewKey].
Function: alignActivitySeries
- Purpose: Align receive and donate cumulative account-activity series onto one sorted UTC-day axis for the profile chart.
- Inputs:
received(AccountActivity.receivedOverTime) anddonated(AccountActivity.donatedOverTime). - Returns / side effects:
ActivityPoint[]. Empty+empty →[]. Empty donated → zero Given on each received day. Non-empty both → day union with step-hold carry-forward. Also aligns CHF/EUR/PHP cumulatives (nullstring →0); missing series side stays at the carried value (0 until first point). - Used by:
AccountActivityChart.
Function: activityValue
- Purpose: Read one cumulative chart value from an aligned activity point.
- Inputs:
point,series(donated|received),scale(sat|fiat); when'fiat',fiat(FiatCode) selectscumulative*Usd|*Chf|*Eur|*Php.'sat'ignoresfiat. - Returns / side effects: Number used to place the polyline.
- Used by:
AccountActivityChart,activityMaxY.
Function: activityMaxY
- Purpose: Y-axis max for the dual-line chart: max of both series at the active scale, or
1when empty/all zeros. - Inputs:
points,scale(sat|fiat), optionalfiat(FiatCode) — same asactivityValue. - Returns / side effects: Positive number for SVG scale.
- Used by:
AccountActivityChart.
Function: fiatUnsummable
- Purpose: Decide whether a chart's fiat y-ticks show an em dash instead of an amount. USD is unsummable when any raw
cumulativeUsdisnull; CHF/EUR/PHP are unsummable when every source cumulative for that code isnullor missing. - Inputs:
days(raw activity or loan days of every series the chart draws,FiatCumulativeDay[]),fiat(FiatCode). - Returns / side effects: Boolean. Pure.
- Used by:
AccountActivityChart,LoanBalanceChart.
Function: alignLoanSeries
- Purpose: Align owed and credit cumulative loan series onto one sorted UTC-day axis for
LoanBalanceChart. Step-hold matchesalignActivitySeries; negativecumulativeSatsand fiat cumulatives are kept; null USD/CHF/EUR/PHP cumulatives become0. - Inputs:
owed(AccountActivity.owedOverTime) andcredit(AccountActivity.creditOverTime); callers pass[]when a side is missing. - Returns / side effects:
LoanPoint[]. Empty+empty →[]. Only one side → the other is 0 on those days (no invented calendar days). Both non-empty → sorted day union with step-hold carry-forward. - Used by:
LoanBalanceChart,loanValue/loanAxistests.
Function: loanValue
- Purpose: Read one cumulative chart value from an aligned loan point (
owedorcredit). - Inputs:
point,series(owed|credit),scale(sat|fiat); when'fiat',fiat(FiatCode) selectscumulativeOwed*|cumulativeCredit*USD/CHF/EUR/PHP (USDwhen omitted).'sat'ignoresfiat. - Returns / side effects: Number used to place the polyline (may be negative).
- Used by:
LoanBalanceChart,loanAxis.
Function: loanAxis
- Purpose: Y-axis range for the loan chart: always includes 0.
minY/maxYare min/max of 0 and both series at the active scale (empty → both 0);spanismaxY - minY, or1when that difference is 0. - Inputs:
points,scale(sat|fiat), optionalfiat(FiatCode) — same asloanValue. - Returns / side effects:
{ minY, maxY, span }for SVG placement of positive and negative balances. - Used by:
LoanBalanceChart.
Function: useAccountTotals
- Purpose: Session-based GET
/me/activityviafetchAccountActivity; returns given/received sats plusdonateOverTime/receiveOverTime, and loanowedSats/creditSatsplusowedOverTime/creditOverTime. Fetches even before the in-app wallet is verified (forum gifts do not need it) and does not callfetchGiftStats. Missing loan fields become saldo 0 and empty loan series. - Inputs: Reads
sessionand whetheraccount.sparkWalletVerifiedis true fromuseAuthStore; callsfetchAccountActivitywhenever a session exists. Refetches when the session changes or the wallet becomes verified, so gifts to the newly set up wallet appear without a full reload. - Returns / side effects:
{ donatedSats, receivedSats, owedSats, creditSats, donateOverTime, receiveOverTime, owedOverTime, creditOverTime, loading, failed }. Fetch start:failedfalse, all series empty, the gift chart shows empty copy and the loan chart renders nothing. Success:failedfalse and series from the payload (?? []/?? 0for loan fields). Thrown fetch:failedtrue, zeros, empty series, both charts show error copy. Session null:failedfalse, no fetch. On each fetch start (including a session or wallet-verification change) totals and series reset to zeros/empty andfailedis false;AccountActivityChartshows empty copy (no SVG) andLoanBalanceChartrenders nothing while in flight. Drops stale or cancelled responses when the session or wallet verification changes mid-flight and does not apply them. - Used by:
ProfileScreen.
Function: WelcomePage
- Purpose: Next.js page for
/welcome. - Inputs: None.
- Returns / side effects: Flow
PageChrome(AppShellwrapper) withProfileChromeLefthideHistoryArrowandForumHomeWordmarktop-left, andWelcomeTopRight(the member menu when a session or a held-back session exists, otherwise a link to/login).OnboardingGatescreen="welcome"allowGuestwrapsWelcomeScreen. The history arrow is never shown, whatever this tab's view stack holds. - Used by: Route
/welcome.
Function: WelcomeScreen
- Purpose: Living-room screen. With a session it is the post-login screen after name, username, and living-room rules agreement are saved; it places
LoansCardand thenLenderWaitingCarddirectly under the welcome heading beforeForumLoader. Without a session it is the public active list. Page column ismax-w-xl(Card surface={false}) so the AppShell frame is the only page-levelrounded-3xl. - Inputs: Reads
sessionandaccountfromuseAuthStore; composesLoansCard place="welcome",LenderWaitingCard,useWallet,useWalletSend, anduseWalletPanel. A signed-in member also getsWalletTour,blockedwhile a wallet view or the writer is open, or while Receive / Send are folded away (a focused text field in the page). - Returns / side effects: Gift icon with an integrated Bitcoin symbol. Heading Welcome, {name} when the account has a name, otherwise Welcome. A signed-in member's
LoansCardfollows the heading when a loan is collecting or being repaid, collapsed by default;LenderWaitingCardfollows it whilelenderWaiting.sharesofGET /me/loansis above 0; then comes the forum board. A session writes in the writer, not on the page (below).ForumLoadersetsreadOnlywhen there is no session.WelcomePageshows Log in in the chrome. No name or address form. No donate CTA. NoLogoutButtonin the page column. A signed-in member whose wallet is configured (useWalletnotdisabled) also getsWalletFooterActions(Receive left, Send right) in the shell footer, fixed while the feed scrolls; Send and Receive are enabled also while the wallet still opens; only a step inside the view that needs the open wallet waits for it. Either opens a full-screen view (WalletPanelView) over/welcomefromuseWalletPanel(in-page state, not a route): the welcome column stays mounted buthidden, the footer buttons are not rendered, the view starts at the top, and closing it restores the feed's scroll position. The open view sets the top-left arrow throughuseChromeBack(nav.back, the slot an ask-wizard step uses): in Send it closes the manual-entry sheet or an open send step first (held while a send is in flight), then returns to the feed. The wordmark and the Menu's Home (FORUM_HOME_EVENT) close the view and return to the top of the feed. Signed-out visitors and members without a configured wallet see the column alone. A signed-in member gets a round + (IconButton size="xl"primary withshadow-lg, accessible nameforum.writerOpenWrite a post, lucidePlus) throughAppShellOverlay, at the bottom right of the frame (right-[11px], 24 px from the window edge): 23 px above Receive / Send while they are in the footer (calc(4.75rem + 23px - 1.75rem * var(--footer-collapse, 0)), so it follows them as they slim down and glides with them), otherwisebottom-6. It stays mounted and fades out (pointer-events-none invisible opacity-0, 250 msease-glide,motion-reduce:transition-none) while the writer is open, the same fade as while a field has the focus (below). A wallet view hides it at once (the same classes without the transition, also without thebottomglide it has while the frame body carriesdata-footer-snap): the footer buttons leave in that step, so a fade would show it dropping tobottom-6. It fades back in when the view closes. A tap opens the writer (ForumLoaderwriter, rendered byForumBoard) in the same task (flushSync), so the writer's text field takes the focus inside the tap and the keyboard comes up. While the writer is open, aPanelChromeBackregisters the top-left arrow (nav.back, notover: an Ask step inside the writer registers later and steps back first); the arrow closes the writer, and so do a successful post (ForumLoadercallsonClose), the wordmark and the Menu's Home. Closing first blurs the focused element, so the keyboard closes as a focus change foruseAppHeight. The arrow restores the feed's scroll position from when the writer opened; after a successful post from the open writer the feed shows its top with the new note (a posting fee that completes after the writer closed changes neither the scroll nor the focus); Home leaves the scroll to the forum's own scroll-to-top. Drafts live inForumLoader, so reopening shows an unsent draft. While a text field inside the page scrollport has the focus (atextarea, or aninputwhose type takes typed text:focusin/focusouton the scrollport), the + gets the same fade (pointer-events-none invisible opacity-0, 250 msease-glide;motion-reduce:transition-none), and only then doesWalletFooterActionsgetfolded. An open form in the feed whose field does not have the focus (an expanded post's reaction form or a gift amount box; the pay sheet is a dialog over the page, not a form in the feed) leaves both in place; the 80 px clearance below lets its controls scroll clear of the +. A form that focuses its field when it opens (React on a post that is already expanded) moves both aside in that tap. Both come back once the focus has left the field; a press that takes the focus out of it (a mouse click on the form's Post) keeps both aside until a task after itspointerup/pointercancel, so its click reaches the control it went down on and not the + coming back under the pointer. A focused field that disappears with its form, or with a wallet view, gives nofocusout, so while a field has the focus aMutationObserveron the scrollport (child list, subtree) and every wallet-view change read the focus again. A signed-in page ends with anaria-hidden80 px clearance (data-plus-clearance,h-20) under the column, so at the end of the feed the last note's controls scroll clear of the +. In a screenshot build a?visual=send-…pin opens the Send view on mount. The page sits in anOpenReceiveProvider: Add Bitcoin in a pay sheet on the forum home closes an open writer and opens this page's Receive view (while the member has a wallet; otherwise it goes to/wallet?receive=1). - Used by: Screen
/welcome.
Function: forumTextPreview
- Purpose: Collapse a public forum note or reply body to a 280-character UTF-16
.lengthcollapsed preview (FORUM_TEXT_PREVIEW_LIMIT) for the feed/profile timeline analog. Show more /truncated: trueonly whentext.lengthis greater than twice that (560,FORUM_TEXT_FULL_LIMIT). A body of 560 characters or fewer is returned unchanged. Word/line boundary cut when the last space or newline in the slice sits at index>= floor(limit * 0.8); trailing spaces/tabs trimmed; no ellipsis in the helper. If the hard cut splits an http(s) URL (no whitespace across the boundary), that incomplete trailing URL is dropped from the preview soLinkedTextcannot autolink a shorter href. - Inputs:
text— full body; optionallimitis this collapsed preview length (default 280); the full-body ceiling islimit * 2. - Returns / side effects:
{ preview, truncated }. Does not append…. No network. - Used by:
ForumNoteText.
Function: ForumNoteText
- Purpose: Client paragraph for remaining note/reply text on the feed and profile (via
ForumQuotedBody/QuotedForumNotewhentruncateis true). Empty text returns null. Bodies autolink http(s) URLs viaLinkedText. Optionalplainforwards plain rendering toLinkedTexton both the full and truncated (Show more) path. Bodies longer than 560 characters (twice the 280-character preview) render a collapsed preview of 280 characters,…, and inline Show more (forum.showMore, app inline link) for callers that do not passforceExpanded. OptionalforceExpandedrenders the full body and omits Show more. Expand in place; no Show less. Click and keydownstopPropagationso the parent cardrole="button"does not toggle replies. On/messages/[id], the original body isLinkedText(ForumQuotedBodywithtruncate={false}). - Inputs:
ForumNoteTextProps—text,className, optionalplain, optionalforceExpanded(default false). - Returns / side effects:
LinkedText(<p>plus optional overlay), ornullwhentext === ''. Local React expand state only. - Used by:
ForumQuotedBody/QuotedForumNote(remaining text and nested quoted note bodies whentruncateis true) andTranslatableNoteBody(original body only whentruncateis true, not the translation).
Function: readJpegTakenAt
- Purpose: Read a JPEG APP1 Exif capture time before the canvas re-encode strips it. Does not read GPS.
- Inputs: JPEG file bytes.
- Returns / side effects:
YYYY-MM-DDTHH:MM:SSplus the matching offset when the file has one, or null. Prefers DateTimeOriginal, then DateTimeDigitized, then IFD0 DateTime. No I/O. - Used by:
prepareForumPhoto.
Function: ForumPhotoGallery
- Purpose: Horizontal snap row for forum-note or public-shop stills. A forum note shows it when
photoCount > 1; the public shop page shows it for any number of stills. Earlier slides are 88% wide so the next still peeks; the last slide is full width. The row isdata-scroll-x(sideways only, vertical axis clipped) and is not a second page scroll. Acurrent/totalchip (forum.galleryPosition) sits on the visible still. Dots (gap-5,IconButtonsmghost,forum.galleryDot) scroll that row. Emptyphotosreturnsnull. Single still has the chip and no dots. The capture time is stored, not shown. - Inputs:
photos({ index, url, loading?, fetchPriority? }[]),alt, optionalclassName(ForumBoard passesmt-2), optionalonPhotoClick(ForumBoardstopCardToggle), optionalonPhotoError(the parent drops that index).urlis a blob or data URL, a same-origin public still path, or a public API URL.loadingdefaults tolazy.fetchPrioritydefaults tolow. - Returns / side effects: React element. Local scroll index only. No network. The
<img>uses the URL the parent passed. When an earlier still disappears, the chip stays on the same photo index and the row scrolls to that still's new slot; if that still is gone, the chip clamps to the last remaining still. The clamp is derived during render. - Used by:
ForumBoard,PublicThreadCardinPublicMessageLoader,ShopScreen.
Function: ShopAddWizard
Guided shop submission on /shops. Closed state is only Add a shop. The open steps are photos, a map place with shop name and structured address, text, a required 21.gifts username, then a summary. Every disabled Next/Post has a visible field error or step reason. Photo errors stay under the picker with the n / 10 count. Place uses a dialog/sheet, text has the live 1000-character counter and control-character rule, and the username step starts at @. A value that already starts with @ is kept. Leading space before @handle is trimmed to that one @, and any other value gets one leading @. An empty @ blocks Next and is a linked field error under the username (aria-invalid, no alert). A typed letter lists people whose username starts with that letter through ShopAccountSuggestions, the same list the moderator account field uses. Arrow keys move the highlight and Enter picks that person without posting. A non-empty username must match the API format and waits for an account lookup before Next enables. While that lookup runs, only the checking line is shown. A known username shows no extra line. An exact lookup that reports the account missing blocks Next; a failed lookup does not block the wizard and is not shown as no account, because the posting API still validates the account.
- Purpose: Replace the living-room composer on the shops feed. The shop tag is added when the note is sent, not typed in the text step. That text step lists people as soon as
@is typed, the same way a post does. The summary shows the photo count (stills plus a video), the shop name, the formatted address line, the text, and@username. Photos can be skipped and then show None. The user cannot be skipped. - Inputs:
posting, optionalbusyLabel(the sentence above the buttons whilepostingis true), optionalcancelDisabled(locks Cancel; omitted means Cancel followsposting), optionalallowStepsWhilePosting(Next and the chrome Back stay usable whilepostingis true; fields and Save stay locked, so a photo can finish preparing without a save),draft/onDraftChange,photoDrafts,videoDraft,onPickFiles,onRemovePhoto,onClearPhoto,place/onPlaceChange,username/onUsernameChange,onSubmit, optionalonCancel(edit mode only),resetToken(closes the wizard after a successful send),maxLength. Optionalmode(createdefault, oredit),submitLabel,keptMedia,onRemoveKept,imagesOnly,photoError(unsupported,tooLarge,tooMany, or APIformatOrSize),rejectedMedia(the media the API rejected for format or size; while one is still attached, step 1 Next stays off, those thumbnails get a danger outline linked to the photo feedback, and the feedback addsshops.photoRejectedHinton its own line under any later pick reason), andserverProblem; known server fallbacks move back to the owning step and field.imagesOnlyselects the photo-only format-and-limit copy. - Returns / side effects: React tree. A non-empty username is checked with
lookupAccountByUsername; a missing result blocks, while a failed lookup does not. File selection callsonPickFiles. Photo-pick errors and known server errors are announced as alerts, while live validation during typing remains linked field feedback without an alert. The hidden file input carries photoaria-invalid; its icon button keeps onlyaria-describedby, becausearia-invalidis not valid on a button. An API media error after a create or edit submit returns to this photo step. The summary button callsonSubmit(Post, orsubmitLabelsuch as Save changes). In edit mode, the icon-only Close (X) on the photo step callsonCancel. Its accessible name is Cancel, and there is no visible Cancel word. From the place step on, the top-left arrow returns to the previous step and is disabled whilepostingis true, unlessallowStepsWhilePostingis set. The card does not draw Back. - Used by:
ForumBoardwhenshopComposeris set, andShopNoteEditControlin edit mode.
Function: ForumAskWizard
Ask composer on /welcome. A donation is four steps and the counter reads {step} of 4. A credit is nine steps and the counter reads {step} of 9. Step 1 starts with the One-time / Daily pill and a Donation / Credit pill under it. Photos and text follow the credit confirmations. The preview shows the same pills and ForumGoalBar at 0 collected versus the ask. The heading and the step counter share one row (step on the right). The labeled Post on the preview is the only Ask submit. Switching to Credit on the preview returns to step 1. A shown bitcoin amount on this wizard's own plan also shows the visitor's fiat when a rate exists. The preview ForumGoalBar daily plan shows bitcoin and the current spot and calls satsToFiatAmount. Bitcoin stands alone only when that spot is not loaded. A fiat daily plan keeps the stored figure beside the bitcoin split of the goal sats and does not add the viewer's currency.
- Purpose: Walk Ask for money so Continue on the amount step still requires a local 1..10_000_000-sat parse. The amount step and the preview each start with a One-time / Daily
SegmentedControl(tone="neutral", two columns,rounded-2xl). A Donation / Credit pill sits under One-time / Daily, same classes, Donation pressed by default. The photo and text steps do not show either pill. Default cadence is once. One-time / Daily is not posted. The post itself sendsgoalCurrencyandgoalAmount. Only Credit is posted asgoalRepayabletrue, together withgoalTermDays. A donation stays on the four steps. A credit, after the amount, explains that the debt is fixed in the selected currency (bitcoin uses a shorter sentence, with no conversion, and warns that a rising bitcoin price can hurt the author because they bear the full price movement; a fiat credit says payments stay bitcoin and are only priced in that currency at the rate of each payment, not exchanged, and that the author receives bitcoin and bears the full price risk if the price falls before they spend it), then offers 30 days, 1 year, 2 years, or a custom whole number of days from 1 to 3650, then states that repayment is daily and starts the day after the credit is fully given, but never before November 16, 2026. A credit fully given before November 16 starts repaying on November 16. A credit fully given on November 16 starts repaying on November 17, shows the daily amount. The next screen repeats the amount, the currency sentence, the term, the daily rule, the daily amount. Its button confirms the author wants the credit. The screen after that states the daily plan, its button confirms the author can repay that plan. There is no checkbox. Photos are step 7 of 9, the message is step 8 of 9, the preview is step 9 of 9 with Credit pressed, a Loan tag beside the author, the daily plan. Post is the only submit. The credit counter reads n of 9. The daily amount is the total split across the days, any remainder is added to the last day. A fiat-draft preview shows the typed amount plus local Bitcoin and no third currency; a Bitcoin-draft preview shows Bitcoin plus the current spot rate. - Inputs:
step/onStepChange,askDraft/onAskDraftChange,draft/onDraftChange,posting,photoDrafts,videoDraft,onPickFiles,onRemovePhoto,onClearPhoto,authorName,onPost, optionalrateDay(Bitcoin-draft preview counterpart of the typed ask), optionalcomposerMaxLength(defaultFORUM_MESSAGE_MAX_LENGTH, 8000), optionalaskCadence('once'|'daily', default once) andonAskCadenceChange, optionalaskObligation('donation'|'credit', default donation) andonAskObligationChange, optionalshopElsewhere(the draft carries the shop tag outside Shops). - Returns / side effects: React tree. The One-time / Daily pill and the Donation / Credit pill are on step 1 and step 4. Continue on step 1 stays disabled until the parsed sats are 1..10_000_000. Continue on step 2 goes to step 3 with photos optional. Step 4 Post stays disabled without text, photo, or video, then calls
onPost. WhileshopElsewhereis true, step 3 Continue and step 4 Post are also disabled, and a live Post this shop from Shops line (forum.shopPostUseShops) under the text is linked througharia-describedbyandaria-invalid, withoutrole="alert". No network. - Used by:
ForumBoardwhencomposeIntentisask.
Function: parseForumAskAmount
- Purpose: Parse the Ask amount draft into a whole-sat goal.
- Inputs:
rawstring. - Returns / side effects: Integer 1..10_000_000, or
nullwhen empty, non-digits, 0, or above the max. - Used by:
ForumAskWizard,ForumLoader.
Function: parseCreditTermDays
- Purpose: Days a credit is repaid over. Presets are 30, 365, and 730. Custom is a typed whole number.
- Inputs: Preset
30|365|730|'custom', and the raw custom field. - Returns / side effects: Day count from 1 to 3650, or
nullwhen custom is empty, not digits, or out of range. No I/O. - Used by:
ForumAskWizard.
Function: creditSmallestUnits
- Purpose: Smallest units of a typed credit. Bitcoin is whole sats. Fiat is cents.
- Inputs: Amount draft and whether that draft is bitcoin.
- Returns / side effects: Non-negative bigint, or
nullwhen the draft is not that shape. No I/O. - Used by:
ForumAskWizard,ForumGoalBar,LoanRepayScreen.
Function: splitCreditPlan
- Purpose: Split a credit into equal daily units. Any remainder is added to the last day so the days sum to the debt.
- Inputs: Total sats or cents, and a day count from 1 to 3650.
- Returns / side effects:
{ perDay, last, days, remainder }, ornullwhen the day count is outside that range. No I/O. - Used by:
ForumAskWizard,ForumGoalBar,LoanRepayScreen.
Function: ForumGoalBar
SVG progress bar for a top-level forum note. One SVG: orange fill in user units 0–100; overflow past 100% continues in green (app-success) from x=100 at most another 100 units (visual max 200%). The {percent}% label is a sibling, so it stays readable, and is uncapped (110, 250, …). Above the track, the posted line is never one currency when a visitor figure exists. Ask label, then the defined fiat when goalCurrency is USD/CHF/EUR/PHP, then formatBitcoin(goalSats), then the visitor's default fiat unless the ask was defined in that same fiat. That visitor figure is the frozen snapshot when the string is present. A posted line with no snapshot shows the current spot beside bitcoin, and bitcoin alone only when that spot is not loaded. The wizard preview may use the spot rate when no snapshot is stored. Joined with ·. A legacy ask (goalSats, no goalCurrency) is bitcoin plus the visitor's fiat when that figure exists. Renders nothing when goalSats is missing or <= 0. Lengths use SVG width / x / viewBox attributes, not React style.
- Purpose: Show collected-versus-goal progress on a top-level note that has a positive
goalSats. BTC and legacy useforumGoalPercent(sats, goalSats); a fiat Ask usesforumFiatGoalPercentof the payment snapshot (nullcollected is 0%, not sats). Orange through 100%, green overflow, uncapped label. The amount line pairs currencies when a visitor figure exists: defined fiat plus bitcoin when the ask is in the visitor's fiat; otherwise bitcoin plus the visitor's stored snapshot. A posted bitcoin ask with no snapshot shows the current spot beside bitcoin, and bitcoin alone only when that spot is not loaded. The wizard preview may use the spot when no snapshot is stored. A third fiat is shown only when the definition currency is a different fiat. A repayable ask shows a Loan tag beside the author. Any other ask shows a Donation tag. Pressing the tag explains it. The bar does not repeat that sentence. A shop note keeps the #Shop link. - Inputs:
sats(collected),goalSats(whole-sat counterpart), optionalgoalCurrency/goalAmount/ goal snapshots / payment snapshots, optionalrateDay, optionalpreview, optionalgoalRepayable, optionalgoalTermDays, optionalgoalClosedAt(an authoritative loan close that suppresses lending immediately), optionalmessageId(posted credit; omitted in the wizard), optionalledgerCollapsed(feed and profile show a Repayment list link to/messages/<id>/repayment-listand do not mountCreditLedger; the open note leaves it false and rendersCreditLedgerwithlist="summary"), optionalonLend(posted loan only; omitted when the viewer cannot lend). Non-positive or non-finitegoalSatsyieldsnull. The percent comes fromforumAskPercent. OptionallendBlocked(posted loan only): the borrower cannot receive yet, so Lend shows disabled; passed toLoanBlock. - Returns / side effects: The bar, or
null. A posted loan (goalRepayablewithmessageId, notpreview) rendersLoanBlockinstead of the Ask line, the daily plan, and the bar: the ask markup, the collected amount and the goal for the status line in the ask line's pairs (a bitcoin ask: bitcoin plus the visitor's stored snapshot, and the current spot when that string is missing (bitcoin alone only when that spot is not loaded); a fiat ask: the defined currency from its payment snapshot, then bitcoin, then the stored viewer snapshot unless it is that currency, with no spot and no invented zero; a fiat ask without a payment snapshot counts zero in its own currency, like its percent, paired the same way), the percent,funded(sats >= goalSats),goalClosedAt,ledgerCollapsedas the Repayment list link,onLend, andlendBlocked.goalClosedAtsuppresses lending immediately, including on collapsed feed and profile cards that never load a ledger. WithledgerCollapsedfalse it also rendersCreditLedger(list="summary", which fetchesGET /messages/:id/repayment) and passes the ledger that component loads (onLedger) back intoLoanBlock, so the open note shows the paid-back share without a second request. WithledgerCollapsedtrue nothing is fetched. The wizard preview andLoansCard(nomessageId) keep the Ask line, the daily plan of a credit, and the bar. A bitcoin daily plan (goalCurrencymissing orBTC) shows bitcoin and the current spot and callssatsToFiatAmount, including in the preview. Bitcoin stands alone only when that spot is not loaded. A fiat daily plan uses the storedgoalAmountand keeps trailing zeros, so12.00stays12.00, shown beside the bitcoin split of the goal sats, and does not add the viewer's currency. The ask line uses the frozen snapshot, and a posted line shows the current spot when that string is missing, and bitcoin alone only when that spot is not loaded. The wizard preview uses that same spot. No other network. - Used by:
ForumBoard(top-level notes only; passesonLendandlendBlocked),PublicMessageLoader,ForumAskWizard(preview at 0 collected), andLoansCard.
Function: LoanBlock
Loan block of a posted loan note, in the rhythm of the goal bar and without a frame: a row with a small muted Loan request label (forum.loan.title, lucide HandCoins) on the left and the ask amount on the right (text-sm font-semibold), the 8px SVG bar with its percent label, one status line, and a bottom row.
- Purpose: Make a loan read as lending, not as a gift ask, while loans work exactly as before. The state follows the api: below the asked sats without
goalClosedAtthe owner's link is Pay early or end collecting; once funded or explicitly closed it is Repay your loan. The percent (a fiat ask in its own currency) is only the label and the bar. Only with the public ledger and its funding date (the open note) does funded become being repaid or paid back. Collecting: orange (fill-app-accent) bar at the collected percent, the label at most 99% and the line {collected} of {goal} lent (forum.loan.lentOf, the collected amount infont-medium). Funded without a ledger (or before the ledger has a funding date, or with a plan that has no rows because no 21.gifts member gave): a full orange bar, the label at least 100%, and Fully funded (forum.loan.funded). Being repaid: a green (fill-app-success) bar and the percent label at the paid-back share of the repayment rows (fiat rows usepaidAmountcents, bitcoin rows usepaidSats; a fully paid row contributes its whole original value, and rows without an amount are skipped), ariaforum.loan.paidBarAria, and Fully funded · being repaid. Paid back (every row paid, at least one row): a full green bar and Paid back intext-app-successwith lucideCircleCheck. No lender count, no line about the viewer's own share, and no repayment-plan explanation. - Inputs:
messageId,ask(markup),collectedandgoal(strings with their fiat),percent(uncapped; the label),funded(collected sats reached the asked sats),ledger(RepaymentLedgerornull),ledgerLink(show Repayment list to/messages/<id>/repayment-list), optionalgoalClosedAt(authoritative close from the note), optionalonLend. OptionallendBlocked: the borrower cannot receive yet. - Returns / side effects: A
sectionlabelled Loan request withdata-loan-block(collecting,funded,repaying, orrepaid). The bottom row shows Repayment list and, only while collecting, whilegoalClosedAtis null or absent, and while the loaded ledger does not have a non-nullclosedAt, Lend.goalClosedAttherefore suppresses lending immediately on collapsed cards that never load a ledger; any closed below-goal loan keeps its status but cannot be given more money. Both actions stop the click from toggling the card. No network. - Used by:
ForumGoalBar.
Function: LoanPayNotice
Calm sentence in the pay step of a money reaction on a loan, in a rounded-lg bg-app-card-muted px-3 py-2 text-sm text-app-muted box.
- Purpose: Say who is lent to and how it comes back, without warning words. A loan that still collects: You are lending to {name}. Once the loan is fully funded, you get it back in {days} daily payments. (
forum.loan.payNotice; one day usesforum.loan.payNoticeOne, a note without a termforum.loan.payNoticePlain). A loan that is already full: This loan is already fully funded. What you send now is a gift to {name}. (forum.loan.payNoticeFull). - Inputs:
name(the borrower's display name),days(term, orundefined),full. - Returns / side effects: A paragraph with
data-loan-notice(lendorfull). No network. - Used by:
ForumReplyPayPageandForumPaySheet(throughForumBoard'sloantarget).
Function: forumGoalPercent
Integer percent for a forum goal label. Uncapped (110, 250, …). Uses Math.floor((sats * 100) / goalSats) when goalSats is a positive finite number. Returns 0 when the goal is missing, not finite, or <= 0. Negative or non-finite collected sats count as 0 so the label never goes negative. Unchanged sats path for BTC and legacy; fiat Asks use forumFiatGoalPercent.
- Purpose: Compute the uncapped whole-percent label for
ForumGoalBarandLoansCardon BTC and legacy Asks. Fiat Asks useforumFiatGoalPercent. - Inputs:
sats(collected) andgoalSats(whole-sat goal). - Returns / side effects: Floored percent number. No I/O.
- Used by:
forumAskPercent,LoansCard.
Function: forumFiatGoalPercent
Integer percent of a fiat Ask from decimal strings. Uncapped. Scales collected and goalAmount to 8 decimal places with BigInt and floors the quotient. Does not use sats and does not use the goal snapshots.
- Purpose: Percent label for a fiat-defined Ask in the definition currency.
- Inputs:
collected(payment snapshotamountUsd/amountChf/amountEur/amountPhp, two-decimal string or null) andgoalAmount(defined amount string). - Returns / side effects: Floored percent. Null, missing, or non-two-decimal collected is 0. Unusable or zero goal is 0. No I/O.
- Used by:
forumAskPercent.
Function: scaleDecimalTo8
Decimal string scaled to 8 fraction digits as a BigInt: the integer part times 10^8 plus the fraction padded right with zeros. A bitcoin amount becomes its exact sats (0.00238093 → 238093n), without a float.
- Purpose: Exact integer arithmetic on decimal strings: the fiat Ask percent, and the sats of a shop payment's bitcoin amount.
- Inputs:
raw: digits with an optional fraction of 1–8 places. - Returns / side effects: The scaled BigInt, or
nullfor any other shape (a sign, an exponent, more than 8 decimals, spaces). No I/O. - Used by:
forumFiatGoalPercent,fetchShopPayLink.
Function: forumAskPercent
Integer percent of a note's Ask in the unit it was defined in. Uncapped.
- Purpose: The percent label and bar of an Ask (the goal bar and the loan block): a fiat Ask (USD, CHF, EUR, or PHP with a usable
goalAmount) usesforumFiatGoalPercentof the payment snapshot in that code; every other Ask usesforumGoalPercentof the sats. It is the label and the bar only: whether a loan is funded follows the sats, as the api counts it. - Inputs:
ForumAskProgress:sats,goalSats, optionalgoalCurrency,goalAmount, and the payment snapshotsamountUsd/amountChf/amountEur/amountPhp. - Returns / side effects: Floored percent. No I/O.
- Used by:
ForumGoalBar(the label and the bar of the goal bar and the loan block).
Function: formatDefinedGoalAmount
Defined Ask amount for the goal line. Prefix $ for USD and ₱ for PHP, otherwise CODE . At most two fraction digits pad to two (200 → ₱200.00). More than two keep every digit (10.125 → ₱10.125). One comma is the decimal mark. Grouping uses the visitor number format. Not the two-decimal snapshot formatter.
- Purpose: Show
goalAmountexactly, not the two-decimal snapshot of the same currency. - Inputs:
amountstring, fiatcode, number-formatstyle. - Returns / side effects: Prefixed string, or
''when the amount cannot be shown. No I/O. - Used by:
ForumGoalBar,LoanRepayScreen,PayLinkScreen.
Function: RepaymentPlanChart
- Purpose: Draw the repayment plan. Each day is a bar for the amount due that day. A line starts at the whole debt and falls to zero on the last day. The horizontal axis is the first day and the last day. When the credit is fully given those labels are the UTC dates. Before that they are day numbers. The words Per day and Still owed name the bar and the line.
- Inputs:
amounts(one positive number per day, same unit),from,to, andtotalText(the whole debt, already formatted). - Returns / side effects: A figure, or
nullwhen every amount is missing. No network. - Used by:
CreditLedger,ForumAskWizardplan and confirmation.
Function: revealInScrollport
- Purpose: Keeps a focused field or reply form inside the one active scrollport. A target taller than the scroller minus 24px is aligned to the scroller bottom minus 12px. Otherwise only a bottom or top overflow is corrected by that same 12px margin. It never calls
scrollIntoViewand it never scrolls the document. The same module exportsSCROLL_FOLLOW_ATTR(data-scroll-follow), the mark a reveal puts on the scrollport while it follows a moving target (ForumBoard);WalletFooterActionsand the forum's scroll memory skip scroll events while it is set. - Inputs: The active scrollport element and the target element (input, textarea, select, or reply form).
- Returns / side effects: Void. Mutates that scrollport's
scrollToponly. No network and nowindowscroll. - Used by:
revealReplyForm,ForumBoardcomposer and reply focus,useAppHeightafter a viewport change.
Function: revealReplyForm
- Purpose: Keeps a forum reply form inside the AppShell scroller by delegating to
revealInScrollportafter the null guards. That helper also corrects a top overflow and a target taller than the scroller. A missing scroller or form leaves the scroll position unchanged. - Inputs: The shell scroller (
HTMLElementor null) and the reply<form>(or null). - Returns / side effects: Void. Mutates that scrollport's
scrollToponly when both arguments are present. No network. NoscrollIntoView. - Used by:
ForumBoardafter an expanded reply composer is laid out, and only when no pay sheet is open.
Function: revealPaySheet
- Purpose: Pulls the part of an open payment that stays on the page, the gift amount box (
[data-pay-amount]), back into the AppShell scroller only when a jump has placed its top above the shell. A box that starts below the fold is left alone, so the note above it stays on screen. The bottom pay sheet itself sits in the frame's overlay, outside the scroller. The reply composer is not pinned while a payment is open. - Inputs: The shell scroller (
HTMLElementor null) and the gift amount box element (or null). - Returns / side effects: Void. When the box top is above the shell, subtracts that gap from
scrollTop. A box that starts below the fold, a missing scroller or box, and a top that is already inside leave the scroll position unchanged. No network. - Used by:
ForumBoardwhile a payment is open, including when the amount box or the reply form changes size.
Function: ForumVideo
- Purpose: Playable note video. No native controls; one play button while paused; a click on the playing video pauses it; the fullscreen button sits in an absolutely positioned wrapper because the small icon button stays relative; the frame is
mx-auto w-fitso the picture stays centered and both controls sit on it. The fullscreen button callsrequestFullscreenon that frame, orwebkitEnterFullscreenwhen that API is missing. Composer and ask previews do not use it. - Inputs: Native video attributes except controls, controlsList, and playsInline.
- Returns / side effects: The video, play button, and fullscreen button. No network.
- Used by:
ForumBoardfeed video,PublicMessageLoaderpublic note video.
Function: ForumBoard
- Purpose: Presentational public forum: each post card body without the action row is the expand/collapse control (
forum.expand/forum.collapse,role="button"wrapping header, media, and body text, not anIconButton; the footer ₿ amount button and the reply-count button (when shown) also callonToggleExpand; React on every top-level note (forum.react, lucide Reply; expands the reply composer; omitted whendeletedAtis set), a heart (lucide Heart;forum.heartAmount“Send ₿21” with a loaded account, otherwiseforum.heart“Send ₿1”) that sends the account's storedheartSats(default 1) on a non-deleted post and a non-deleted reply whenheartViewerId !== accountId(shown signed-out; hidden whenpayableis false and whenonHeartTipis omitted, except that a note whose author cannot receive yet (authorCannotReceive) shows the heart disabled with its count (a tap still in its +1 window keeps its fill, +1, and count), and an author-wallet line from an earlier refused heart stays alone on a note that is no longer payable; omitted on the viewer's own note; click callsonHeartTipand stops the card from expanding; it does not open the pay sheet; the count sits immediately to the right of the icon and the fill remains after a tap), a repayment link to/loans/repaywhenrepayLinkis true for the signed-in author of a non-deleted top-level repayable note: Pay early or end collecting while it is below goal and has nogoalClosedAt, otherwise Repay your loan (ForumLoaderandMemberProfileScreenpass it;PublicMessageThreaddoes not), Translate (Languages icon,controlSlotIdonTranslatableNoteBodyin this row), a copy-linkIconButtonon every note and every reply, optional Gift on a payable reply (disabled, and still inside the zapSundayWritingGate, on a reply whose author cannot receive yet; an open gift sheet or gift invoice for an author a refresh reports as unable to receive closes and callsonPayCancel, while a posting-fee sheet (payHostcomposer) stays), and optional delete sit outside that control as siblingIconButtons thatstopPropagation; whenshopNoteEditis set, the shop pencil sits in that right-hand footer after copy and before the place control, and the reply count stays in the left group; whenshopPlaceEditis set, a compact place control (Add a place or Edit place) sits in that footer after the pencil and before the account control; whenshopAccountEditis set, a compact account control (Add an account or Edit account) sits after the place control; Gift/Delete/reply composer also omit whendeletedAtis set). Optional dismissible living-room laws hint box (X control; two laws plus links to/rulesand/contact) whenlawsVisible, Active/No gifts yet/All/Most popularForumModeSelect(closed dropdown; selected label and chevron on the trigger; unpaid count chip on the closed trigger whenunpaidNewCount> 0 and unpaid is not selected), list of posts (name, the author row usesMessageKindTags(Loan and Donation buttons that show a sentence,#Shopstays a link), optional Founder / Moderator / Fond / Software Developer / Initiator / Verified role pill on notes and replies when the api role is one of those six (basishas no pill), top-level shop notes show a#Shoplink to/shopsand hide#21GiftsShop, timestamp, optional inline photo fromforumPhotoSrc(/messages/{id}/photo.jpg, extra stills/photo/{n}.jpg; blob and data URLs inphotoUrlswin for a composer preview; adeletedAtrow never gets the public URL) (single still whenphotoCount≤ 1; a horizontal snap row (ForumPhotoGallery,data-scroll-x, 88% peek) whenphotoCount > 1— sideways only,current/totalchip, dots keyed${id}:${index}) then caption text below the photo, a link to/shops?pin=<id>#map(the label, or coordinates when the label is null) on a top-level note that has a place, an@usernamelink to/members/{id}on a top-level note that has a shop account, optional inline<video>playback for notes with video (player keeps the clip aspect ratio withmax-h-80 max-w-full, no full-width black canvas), remaining body text throughForumQuotedBody/ForumNoteText(280-character preview plusforum.showMoreonly when the body is longer than 560 on the feed; signed-in/messages/[id]passestruncate={false}so the original stays full), Translate (Languages icon) / Show original / Show translation in the footer icon row viaTranslatableNoteBody(controlSlotId), which portalsNoteTranslatewithplacement="row"when the board has that row, a reply or note withvia === 'nostr'(a Nostr zapper with no 21.gifts account) renders the External button only when the api role has no tag (for examplebasis); a nostr note whose api role issoftware_developershows one Software Developer pill because the api sends that role, and a fond row shows the Fond pill. The External button shares the same per-message hint toggle state as the role pill's hint, and the note renders its body viaTranslatableNoteBodyplain(no quoted-note unfurl, URLs stay visible text) instead ofForumQuotedBody, ₿ amount plus optional preferred-fiat·formatFiatDisplayof the amount stored when the payment was made (a stored string as-is; a null or missing field on a passed payment shows the current spot, and stays off the line only when that spot is not loaded) with a Gift pay icon only when the card is a payable reply (parentIdset), or a disabled Gift withCannotReceiveLabelwhen the reply's author cannot receive yet; the card's copy control is labelledforum.copyReplyLinkwhen the card is a reply andforum.copyLinkotherwise, and always copies the card's own origin/l/<8 hex>(first UUID group) when that id is a UUID, otherwise origin/messages/<id>) or empty/loading/error, messenger-style composer (Send a post / Ask for money pill; Post is a photo icon row of Take a photo (CameraPhotoButton), Add a photo or video ImagePlus, and Add a place (MapPin,PlaceField) whenonPlaceDraftChangeis set, a chosen place on its own line between that row and the text field, then the textarea with the Post Send icon to its right on the row below; Ask isForumAskWizard(the amount step and the preview open with the One-time / Daily pill; the photo and text steps do not); whenallowAskis false the Post/Ask pill and Ask wizard are omitted;shopComposershowsShopAddWizardinstead of the post composer), optional photo draft preview (Selected photo) whenphotoDrafts.length === 1with Remove photo X, composer gallery whenphotoDrafts.length > 1(ulof Selected photo alts + per-index Remove photo), optional video draft preview with Remove video X — icon-only, catalogaria-labels,maxLengthfrom optionalcomposerMaxLength(default 8000)), in-card reply composer (amount row first:AmountEntrylayout="inline"id="forum-reply-amount"with the bitcoin/fiat switch on that same line, then one text line and Post aligned beside it), and a pay sheet on a payable reply or, whenpayHostiscomposer, on the top-level composer: amount form with a live equivalent in the preferred fiat only when the conversion is non-null (no picker; after mint the equivalent uses the invoice amount, not an empty draft's 21-sat default), then every user-agent amount CTA is Continue (forum.payContinue) and only requests the invoice; after mint the amount form stays in place, disabled, and every user-agent sees the same bottom pay sheet (PaySheetinside aCollapsewithholdMsPAY_SHEET_HOLD_MS: title, amount with fiat, and theWalletPaypay slot; no invoice QR and no button that hands the payment to another wallet app); Close (X) on the amount box or on the sheet dismisses it and stays on the page. That control is not Back. Gift-only replies show send ₿… (forum.giftReply) plus the same optional preferred-fiat·as notes; a reply with text and sats shows that formatted amount under the text. WhenreceivedSatsis greater than zero,forum.receivedOnReplyis a separate line and is not added tosats. A text reply that has both usesforum.sentOnReplyfor the sent line, and the two lines share a left rule. Clicking a role pill toggles a short explanation under that card header (one open at a time). Selector stays visible in every board state unlessmodeSelectoris false orcomposerHiddenis true. WhenmodeSelectoris false the list is every loaded row (mode all), including zero-sat basis notes; an empty loaded list still usesemptyKey, notforum.emptyPaid. Uses optionalemptyKey(forum.emptydefault,shops.emptyon shops) when the loaded list is empty,forum.emptyPaidwhen Active or Most popular hide every loaded row (Most popular remains paid-only; Active also keeps unpaid moderator notes; a top-level note withgoalSats> 0 and zero sats is not Active), andforum.emptyUnpaidfor No gifts yet when that filter hides all loaded rows. Propsmessagesare newest-first (API window); Active, No gifts yet, and All keep that order (newest at the top). Most popular stays sats-descending. The composer sits under the mode selector / filters, above the newest-first list; replies remain oldest-first. WhenonRefreshis passed, pull-to-refresh from the top of the AppShell inner scroller (useAppShellScroller) calls it; whilerefreshing(or a pull that reached the arm threshold) a visually hidden (sr-only)role="status"withforum.refreshingis mounted for assistive tech only — idle markup has no status node so welcome screenshots stay unchanged. WhennewPostsAvailableis true, a labeled primaryButton(forum.newPosts, decorative lucideArrowUp) issticky top-2in the scroller; the node is omitted when the flag is false. WhenmoderatorAppointedAvailableis true, a labeled primaryButton(forum.moderatorAppointed, sizesmwithshadow-lg, decorative lucideArrowUp) in the same visual language as New posts issticky top-2when it is the only pill and callsonShowModeratorAppointed; the node is omitted when the flag is falsy. When both this andnewPostsAvailableare true, the appointment pill stayssticky top-2and New posts issticky top-14. Listens forFORUM_COMPOSE_EVENT/requestForumCompose: focuses the new-post textarea withpreventScrolland thenrevealInScrollportwhen the shell scroller exists and consumes pending compose only when that textarea exists (composerHiddenboards keep the flag)./messages/<uuid>andhttp(s)://<host>/l/<8 hex>HTTP(S) URLs in a body unfurl into a nested post and the URL is removed from the visible text once that note loads. The pay sheet's pay control (gift, reaction and posting-fee sheets) isWalletPay, which pays from the member's in-app wallet (sparkInvoicewhen the api issued one, otherwisepr, which is also paid when the wallet refuses the Spark invoice); it is the only way to pay there. Loan repayment leaves the card for/loans/repay. WhenauthorCannotReceiveis true for a note or reply (apiauthorCanReceive: false, a live member note, not the viewer's own), that action row shows Can't receive yet (CannotReceiveLabel), the heart and Gift are disabled, Lend is disabled (lendBlocked), and the reaction Amount field on that note is disabled; a reply still posts its text. A body without the field shows none of this. A heart the api refuses withcannot_receiveshowsforum.payErrorAuthorWalletunder the heart (cannotReceiveon the heart view). - Nostr role pill: A
via: 'nostr'note whose api role has a tag shows that role pill instead of External. - Inputs:
ForumBoardProps—messages, optionalreadOnly(signed-out living room: no composer, pay, delete, or @mention links; an author name with a non-emptyaccountIdis still the profile button, including whenreadOnlyis true; Enter or Space on that button opens the profile and does not toggle the card, because the card key handler ignores a descendant target; the mode selector stays),error(boolean load-failure flag),loading, optionalrefreshing/onRefresh(omitonRefreshto disable pull-to-refresh), optionalnewPostsAvailable/onShowNewPosts(pill omitted when the flag is falsy), optionalmoderatorAppointedAvailable/onShowModeratorAppointed(pill omitted when the flag is falsy),posting,draft,onDraftChange,askDraft/onAskDraftChange, optionalallowAsk(default true; false omits the Post/Ask pill and the wizard) / optionalcomposeIntent/onComposeIntentChange/askStep/onAskStepChange/askCadence('once'|'daily', default once) /onAskCadenceChange/authorName,onPost,onRetry,formError(empty/tooLong/ask/request/rateLimit/unsupported/tooLarge/tooMany;ForumFormError = 'empty' | 'tooLong' | 'ask' | 'request' | 'rateLimit' | 'unsupported' | 'tooLarge' | 'tooMany' | null), controlledmode/onModeChange, optionalmodeSelector(default true), optionalnearEndRef(callback ref on the visible note about eight rows from the end soForumLoadercan prefetch the next page; when the loaded list is empty it sits on the empty-feed line instead, so a page whose notes were all dropped by the list schema still leads on to the next page), optionalunpaidNewCount(default 0), requiredlawsVisible/onDismissLaws,photoDrafts(ForumPhotoPayload[]),placeDraft(ForumPlacePin | null), optionalonPlaceDraftChange(omit it and the place control is absent, so replies have none),videoDraft,onPickFiles(files: File[]),onRemovePhoto(index: number),onClearPhoto,photoUrls, optionalphotoVersions(Readonly<Record<string, string>>, default{}; a non-empty token is appended as?v=on the public still path),videoUrls, optionalcomposerHidden(hides the new-post composer; the textarea is absent so compose-pending is not consumed), optionalcomposerMaxLength(defaultFORUM_MESSAGE_MAX_LENGTH; shops pass 7986 so the#21GiftsShopsuffix fits), optionalemptyKey(forum.emptydefault,shops.emptyon shops), plus pay sheet props (payMessageId, optionalpayHost(composerkeeps the sheet on the top-level composer;cardbinds to the matching parent or reply; omit/nullinfers from the list),payDraft,payBusy,payError(amount/request/rateLimit/authorWallet/deleted),payInvoice, optionalreplyPayPreview(string | null, defaultnull; when set with a matching card invoice,ForumReplyPayPageopens over the page and the reply composer stays, disabled), optionalrateDay(FiatRateDay | null; omit ornullleaves unsent previews bitcoin-only because no rate is loaded; a presentrateDayprices an unsent preview that passed no stored object; a passed payment keeps its stored string, and shows the current spot when that string is missing (bitcoin alone only when that spot is not loaded)),onPayOpen, optionalviewerAccountId, optionalrepayLink(default false; on the viewer's own credit it shows Pay early or end collecting while open below goal, otherwise Repay your loan, both to/loans/repay),onPayDraftChange,onPaySubmit,onPayCancel), expand/replies (expandedId,onToggleExpand,replies,repliesLoading,repliesError,onRetryReplies, reply composer with optionalreplyAmountDraft/onReplyAmountDraftChange,replyFormErrorincludingamountfor a non-numeric or overflowing paid-reply sats field,deletedwhen that note is missing or was deleted, andauthorWallet(forum.payErrorAuthorWallet) when the author's wallet cannot take a paid reply), optionalshopComposer(shops;ShopAddWizardinstead of the post composer),shopUsername/onShopUsernameChange/shopResetToken, optionalshopNoteEdit/onShopNoteUpdated(moderator pencil on a top-level shop note), optionalshopPlaceEdit(true on shops; the footer place control is absent when omitted) andonShopPlaceUpdated(applies a saved or cleared pin to that row), optionalshopAccountEdit(true on shops; the footer account control is absent when omitted) andonShopAccountUpdated(applies a saved or cleared shop account to that row), and optionalonDeleted(moderatorDeletePostControlon the parent footer and on nested replies withkind="reply"), optionalheartViewerId(default null; hides the heart when it equalsaccountId), optionalheartViewerSats(default null; whole sats the loaded viewer's heart sends, named throughforum.heartAmount“Send ₿21”; null keepsforum.heart), optionalonHeartTip/heartTipViews(heart fromuseHeartTip; omitonHeartTipto hide the heart on every note), optionalpermalinkTargetId(nested reply ring only:data-permalink-target="true"andring-1 ring-app-fg; parent notes are not ringed), and optionaltruncate(default true;PublicMessageThreadpasses false). Gift-only replies (text === ''andsats > 0) renderforum.giftReplywithformatBitcoinplus the same optional preferred-fiat·formatFiatDisplaysuffix as notes (the current spot when the stored field is null or missing, and bitcoin alone only when that spot is not loaded); text plus a gift shows that formatted amount under the text.receivedSatsgreater than zero addsforum.receivedOnReplywith the received fiat fields, not a sum. A text reply with both amounts labels the sent lineforum.sentOnReply. The video-draft X still callsonClearPhoto; each photo-draft X callsonRemovePhoto(index). OptionalonShopNoteSavedruns once per shop-note save: after a complete save, or after a partly written one when its editor closes or unmounts. - Returns / side effects: React tree. Copy-link always copies origin
/l/<8 hex>(first UUID group) when the id is a UUID, otherwise origin/messages/{id}— a note copies its own id, a reply copies its own id (no parent resolution). Filters viavisibleForumMessages. Load error copy isforum.errorviat(), neverError.message. Formats timestamps viaformatForumTime. Hides empty text paragraphs; public stills useforumPhotoSrc; blob and data URLs stay for the composer preview; a deleted staff row has no public URL. Feed video isForumVideo(no native controls; one play button while paused; one fullscreen button on the picture). Inline feed<video>keeps the clip aspect ratio (max-h-80 max-w-full, no full-width black canvas). A failed<video>errorevent hides that player (photo fallback when a still URL exists: the publicforumPhotoSrcpath, or a blob or data URL inphotoUrls). Clicking a role pill toggles a short explanation under that card header (one open at a time). Dismiss control callsonDismissLawsonly; persistence is owned byForumLoader. ForumBoard itself does not fetch; nestedNoteTranslateGETs/translateon mount and POSTs on Translate. No mode state of its own. AfteronPaySubmitresolves to an invoice, ForumBoard does notwindow.location.assign; every user-agent shows the same bottom pay sheet, whose pay slot isWalletPay(the in-app wallet only); the sheet mounts noQrCode. AFORUM_COMPOSE_EVENTfocuses the new-post composer when it is mounted; acomposerHiddenboard leaves pending compose set for a later visible board. While a payment is open,revealPaySheetruns on its gift amount box ([data-pay-amount]; the bottom pay sheet sits in the overlay, outside the scroller) instead ofrevealReplyForm. The scroll position from before the box opened is restored, so inserting the box does not scroll the note away, and a box that starts below the fold is not pulled to the top. The reply composer on that note is disabled while its pay sheet is open, and after a paid reaction also through the sheet's success step (usePaySheetHold), when the card also ignores expand and collapse, so the held sheet is not cut short. A paid reaction keeps the reply composer in place, disabled, with the typed sentence in it, and opens ForumReplyPayPage (the bottom pay sheet, no reaction text) over the page. Gift-on-reply and composer-hosted sheets stay ForumPaySheet. The amount box's close control sits in an absolutely positioned wrapper at its top left, because the small icon button itself staysrelative; the pay sheet's close sits at the right end of its title row. WithviewerAccountIdset, the viewer's own note (isOwnNote) shows the reply form without the Amount field, and the viewer's own payable reactions show no Gift (Send Bitcoin). - Heart refusals: A heart view with
cannotReceiveshowsforum.payErrorAuthorWallet;creditClosedreuses the localizedforum.payErrorCreditClosedloan-no-longer-collecting alert. Either line remains when an older refresh removes the heart and clears on the next tap. - Repayment link: With
repayLink, the viewer's own live top-level credit always links to/loans/repay: Pay early or end collecting while it is still open below goal, otherwise Repay your loan. Deleted, reply, other-author, and non-credit rows have no link. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,ExternalAuthorProfile. - Writer: Optional
writer(ForumWriter:open,onOpen,onClose; onlyForumLoaderfor the forum home passes it) moves the composer off the page. Closed, the board shows no Post / Ask pill, no composer, no posting-fee pay slot and no composer errors; the laws hint, the mode filter and the feed stay. Open,AppShellOverlayholds the writer: aScrollport(absolute inset-0 z-30 rounded-b-3xl bg-app-card) over the frame under the header row, whose inner column (data-writing-composer,flex flex-col gap-4 px-5 pt-6 pb-6) shows a centredh2(forum.composePost, orforum.composeAskwhile Ask is chosen), the Post / Ask pill, the Ask wizard or the Post composer as on every other board, and the composer errors; the posting-fee pay sheet (payHostcomposer) is hosted on the page beside the overlay, in its ownCollapsewithholdMs, so closing the writer on a paid post does not unmount it before its success step. A pay sheet for a note that is not listed stays on the page. Opening it focuses the text field in a layout effect, so a tap that opens it synchronously brings up the keyboard. A compose request (FORUM_COMPOSE_EVENT) while it is closed callsonOpensynchronously; a request left pending before mount callsonOpentoo. Pull-to-refresh is off while it is open. Its Post composer has the same two rows on every pointer: the photo icon row (camera, photo, place), then the text field with Post on its right; a chosen place shows on its own line between them. Withoutwriterthe board renders as before. - Loans: A top-level loan note (
goalRepayablewith a positivegoalSats) passesonLendtoForumGoalBarwhen the board is notreadOnly, it is not the device's local Sunday, the note ispayable, not deleted, and not the viewer's own (isOwnNote). Lend expands that card when it is closed and, once its replies are loaded, puts the focus in the reaction's amount field (forum-reply-amount) and reveals that form in the scrollport; a field that is disabled then keeps no focus. Every host opens the card in the same click, so a card that is not open after that click (the host refused, or it was closed again before its form was ready) drops the intent, and a later open does not take the focus. The same note gives its money reaction aLoanPayTarget(name,goalTermDays, and full once the collected sats reachgoalSats, as the api counts it): while the loan still collects the amount field reads Amount to lend (forum.loan.amountLabel), and the reaction pay sheet (ForumReplyPayPage, on the forum home, the note page and the profile post and credit cards alike) and the gift pay sheet word the payment as lending. The feed reads no repayment ledger for a loan card. - First post free: Optional
firstPostFree(default false) adds the muted lineforum.firstPostFree(Your first post is free.) under the message composer row, below Post. It is plain text, not a control, and only the message composer shows it; the Ask wizard and Add a shop do not. - Motion: Motion in the reaction flow (
CollapseandAutoHeight, withsrc/lib/motion.ts; seedocs/ui.mdMotion): the expanded block of a card (replies, retry, reaction form) opens and closes withCollapse, and its height glides while it is open. The card-level, per-reply and composer gift boxes open and close withCollapse; each pay host'sCollapse(those three and the reaction'sForumReplyPayPage) carriesholdMsPAY_SHEET_HOLD_MS, so thePaySheetdrawn from it over the frame body can show its success step after the payment closed it. The reaction form stays in place, disabled, while its pay sheet is open; it showsLoanPayNoticeat its top on a loan (not on the viewer's own note). Reply form errors fold in and out (Collapse), and a reply that mounts fades in (animate-fade-in). While the replies of the open card are fetched again (after a paid reaction or a posting fee), the list stays on screen and the form stays disabled; Loading reactions… shows only while there is no list yet. A gift amount box that is folding away sits in aninertCollapseand no longer counts as open; thePaySheetitself is drawn in the frame's overlay and is never scrolled to. The reaction form of a card that is folding away counts as closed too, so closing a card never pulls the page back to it. When another card opens, the card that was open closes at once instead of folding (Collapseinstant), so there is only ever one reaction form. The reveal that keeps the open gift amount box (data-pay-amount) or the reaction form in the scrollport reads both again on each size change of them and of the fold around them, so it follows a sheet that opens in steps. While a fold or a height glide around that target is still moving (Collapseabout to open oropening,AutoHeightwithdata-gliding; a glide of a box further out than the target's own counts only right after a new reply list arrived, since otherwise it comes from other content, such as a reply above opening its own controls, and leaves the page where it is), every step reveals from where the page last came to rest: the target already sits at its final place inside the moving box, so each step lands on the final position or as close as the growing page allows, whatever the frames in between did. During such a move the scrollport carriesSCROLL_FOLLOW_ATTR, so the footer's slim/full progress and the scroll memory do not count those in-between scrolls. When a move around the target ends (MOTION_SETTLE_EVENT), the page is placed once more from that rest position by the final layout; once nothing around the target moves any more, the mark goes and that last placement is a scroll that counts, as one move. A card that closes while its form is still easing open ends the move where the page is, and that position counts the same way. When the fold has eased open before the replies arrived (the page was placed with Loading reactions… still above the form) and the reader has not scrolled since, the move the arriving list causes starts from where the opening started, so the page rests by the final layout whichever came first, the list or the end of the fold; a scroll by the reader in between keeps the page where the reader put it. A scroll by the reader during the 280 ms of a move is replaced by that placement.
Function: ReplyDirectionAmounts
- Purpose: Money on a reply. What the author sent and what later arrived stay two lines and are never added. A gift-only reply (
text === ''andsats > 0) isforum.giftReply. A reply with text and sats, and no later receipt, is the bare formatted amount under the body. WhenreceivedSatsis greater than zero, that receipt isforum.receivedOnReplyon its own line. A text reply that also sent sats labels that lineforum.sentOnReply, and the two lines share a left rule. Zero or a missing receipt draws no received line. Nothing to show returns null. - Inputs:
text,sats, optionalreceivedSats,rateDay,fiat,numberFormat, optionalsentfiat fields forsats, optionalreceivedfiat fields forreceivedSats. - Returns / side effects: React element, or null when both amounts are absent. No network. Bitcoin via
formatBitcoin. Fiat viapreferredFiatSuffixon the passed stored object. A missing string shows the current spot, and stays off the line only when that spot is not loaded. - Used by:
ForumBoardon every nested reply, andPublicThreadCardinPublicMessageLoaderwhen the unsigned card is a reply withreceivedSatsgreater than zero.
Function: ForumPaySheet
- Purpose: The gift amount box and the pay sheet for a payable forum note or reply. A habit comment uses this same component: Amount and Continue in the card, then the
PaySheetwith the in-app wallet pay slot (WalletPay) over the page. It does not show the raw invoice or an invoice QR. - Inputs:
messageId, the pay draft, busy, error, and invoice; draft, unit, submit, and cancel callbacks;rateDayand optionalratePending(default false; Continue does not submit while it is true);showPaymentQris accepted and not rendered;onInteractso the box does not toggle the card under it; optionalloan(LoanPayTarget: borrower name, term, and whether the loan is full) and optionalrecipient. - Returns / side effects: The amount box (
data-pay-amount,rounded-xl border p-3 pl-12 pt-12, itsXatleft-3 top-3):AmountEntry, a pay error that folds in and out (Collapse), including thecreditClosedsentence that the loan no longer collects,LoanPayNoticewhenloanis set, and Continue. While an invoice is open it keeps the existingPaySheetand wallet-only flow. No network of its own. - Used by:
ForumBoardandHabitComments, each inside aCollapsewithholdMsPAY_SHEET_HOLD_MS.
Function: ForumReplyPayPage
- Purpose: The pay sheet of a money reaction. After the reaction is sent with an amount, the reaction form stays where it is under the post, disabled, and this
PaySheetslides up over the page with the amount and theWalletPaypay slot, which pays from the member's in-app wallet (sparkInvoicewhen the api issued one, otherwisepr, which is also paid when the wallet refuses the Spark invoice). It shows no reaction text, no loan notice (the form shows it), and no invoice QR. - Inputs:
amountSats,pr, optionalsparkInvoice,rateDay,onCancel, optionalonSentChange(passed to the sheet, forusePaySheetHold), optionalloan(LoanPayTarget), and optionalrecipient(the author of the post). - Returns / side effects: The sheet reads Send to {recipient} with Send {amount} on the wallet button (Send without a recipient), and Lend to {recipient} with Lend {amount} while the loan still collects; on a full loan it reads Send to {recipient}. Its success step reads Sent to {recipient}, Lent to {recipient}, or Sent. Its
WalletPayreports a payment that did not go out under the flowreaction. Close (X) callsonCancel. It is not the top-left back arrow. There is no button that hands the payment to another wallet app. No network of its own. - Used by:
ForumBoard, inside aCollapsewithholdMsPAY_SHEET_HOLD_MSnext to the reaction form.
Function: Collapse
- Purpose: Shows and hides its content by easing the height and the opacity, so the content around it moves instead of jumping. The box is a one-column grid (
grid-cols-[minmax(0,1fr)], so it never grows wider than its parent) whose row goes fromgrid-rows-[0fr]togrid-rows-[1fr]withopacity-0toopacity-100over 280 ms (ease-glide). Content shown on the first render shows at once, without a move. Whenshowturns true the content mounts in the same commit, closed; the closed box is laid out, then it eases open. When it turns false the last shown content stays in place,inert, until it has folded away, then unmounts. The box clips its content only while it opens or folds, so at rest a focus ring or a pop-up list is not cut off. Each move settles when the box's owngrid-template-rowstransition ends (the browser's clock, so it also settles while a page's timers are held), at the latest after 320 ms. While open, a change in the content's height glides too (AutoHeight). With reduced motion it opens and unmounts at once. WithholdMs, closed content stays mounted,inert, for that many ms instead of until it has folded away (also with reduced motion), so a layer it draws elsewhere can leave on its own clock; inside,usePresentsays whether the fold still shows it. - Inputs:
show, the content, optionalclassNamefor the inner box that holds the content, optionalinstant(default false): closes at once instead of folding, for content whose place another one takes in the same step; it also drops a fold already in progress. Opening still eases. OptionalholdMs(ms;instantwins). - Returns / side effects: The folding box (
data-collapseclosedwhile closed or folding,openinguntil it has settled open, thenopen; withholdMs,heldonce it has folded away while the hold keeps it mounted, so a wait for moving boxes does not wait for the hold), ornullwhile closed. Settling open sendsMOTION_SETTLE_EVENTwhile the box still saysopening, and the box saysopenright after it, in the same task, so a size observer that runs before React renders the settled state does not read it as still moving. Timers and frames are dropped on unmount. No network. - Used by:
ForumBoard(expanded replies block; the card-level, per-reply and composer gift boxes and pay sheets and the reaction pay sheet, each of those withholdMsPAY_SHEET_HOLD_MS; reply form errors),ForumPaySheet(pay errors),HabitCommentsandInboxScreen(their pay sheets, withholdMs),AmountEntry(counter line).
Function: usePresent
- Purpose: Tells content inside a
Collapsewhether that fold still shows it, so a layer it draws elsewhere (thePaySheetin the frame's overlay) knows the fold is closing. - Inputs: None; reads the nearest
Collapse. - Returns / side effects: False from the commit in which the nearest
Collapsegetsshowfalse (while it folds or holds its last content), true otherwise, and true outside aCollapse. No network. - Used by:
PaySheet.
Function: AutoHeight
- Purpose: Glides its height to the height its content needs whenever that changes (one view swapped for another, a line added or removed), so the content below follows smoothly. A
ResizeObserveron the content writes the height on the box before the frame is painted, and the box eases it over 280 ms (transition-[height],ease-glide). The box clips its content (overflow-hidden) only while the height moves, from a change until its height transition ends (at the latest 320 ms after the last change), so at rest focus rings and pop-up lists stay visible. The first measurement sets the height without a move. While a box inside it is still gliding (data-gliding), it follows that glide at once (data-followturns its own transition off) instead of gliding a second time behind it. WithoutResizeObserverthe box keeps its natural height. With reduced motion the height follows at once and nothing clips. - Inputs: The content, optional
classNamefor the innerflow-rootbox that holds it. - Returns / side effects: The gliding box (
w-full min-w-0,data-auto-height;data-glidingwhile its own glide runs). It writesstyle.heightfrom the observer, the waysrc/lib/scroll-surface.tssizes a textarea, never as a JSXstyleattribute (CONTRIBUTING Styling allows a measured height written from script); on unmount it disconnects the observer, drops its timer and clears the height. No network. - Used by:
Collapse,Swap.
Function: Swap
- Purpose: Replaces one view with another in steps instead of at once.
viewKeynames the view. Changes inside the same view render right away. A new key fades the old view out in place over 180 ms (opacity-0,inert); when that fade ends (at the latest after 180 ms) the new view takes its place, fades in over 180 ms, and the box glides to the new height (AutoHeight). A key that comes back before the old view has left shows that view again at once; a third key during the fade ends on that key. The wait for the fade-out to end starts only once the old view is atopacity-0and that style has been applied (getComputedStyle), so a fade-in still running is cancelled instead of ending into the wait and cutting the fade-out short. With reduced motion the new view shows at once. - Inputs:
viewKey, the view, optionalclassNamefor the box that holds the view (for example the flex column and gap its parts sit in). - Returns / side effects: The swapping box (
data-swapnames the view on screen). The fade timer is dropped on unmount. No network. - Used by:
PaySheet(the pay step and the success step).
Function: afterTransition
- Purpose: Settles a move of
Collapse,AutoHeightorSwaponce: when the element's own CSS transition of the given property ends, or after a fallback wait, whichever comes first. A transition of the content that bubbles up, or of another property, does not count. The transition end counts first because the browser runs transitions on its own clock, also while a page's timers are held.src/lib/motion.tsalso holds the shared time windowsMOTION_EASE_MS(280 ms, also the shell footer's fold inWalletFooterActions),MOTION_SWAP_FADE_MS(180 ms) andMOTION_FOLD_MS(320 ms, the latest settle of a move), andMOTION_SETTLE_EVENT(21gifts:motion-settle). - Inputs: The element, the transition property as
transitionendnames it, the fallback wait in ms, and the callback that settles the move. - Returns / side effects: A function that cancels the wait without settling. Adds one
transitionendlistener and one timer, both removed when the move settles or is cancelled. No network. - Used by:
Collapse,AutoHeight,Swap.
Function: announceSettle
- Purpose: Tells the page that a fold or a height glide has ended, by sending
MOTION_SETTLE_EVENT(21gifts:motion-settle, it bubbles) from the box that moved. It is sent before the box reports itself settled, so a reveal that places the page by the final layout runs first. - Inputs: The box whose move has ended.
- Returns / side effects: Void. Dispatches one event. No network.
- Used by:
Collapse(eased open),AutoHeight(glided to its height);ForumBoardlistens.
Function: prefersReducedMotion
- Purpose: Whether the visitor asked for reduced motion (
prefers-reduced-motion: reduce), so the motion timers do not wait for a move the global CSS rule makes instant. False when the browser has nomatchMedia. - Inputs: None.
- Returns / side effects: Boolean. No network.
- Used by:
Collapse,AutoHeight,Swap.
Function: ContactLoader
- Purpose: Client loader for in-app contact on
/contact. Session fromuseAuthStore; returns null without a session. Posts viapostContact. On success fetches conversations and navigates to/messagesor/messages?c=for the official 21.gifts thread. No local success-hide of the form. UsesnextContactRequirementso missing name/rules openRequirementsOverlay(no Skip); a wallet is not required for contact. - Inputs: None (reads session from the auth store).
- Returns / side effects: React element wrapping
ContactScreen, ornull. Owns draft/posting/formError. Empty or whitespace drafts setempty; trimmed text longer than 8000 characters setstooLongand does not callpostContact. After a successful post, the draft is cleared andpostingis set false, thenfetchConversationsandreturnToViewopen the inbox thread (a step back when that thread opened Contact, otherwise a replace). A failed post setsrequestand clearspostingso Send can retry, and the draft stays. - Used by: Screen
/contact.
Function: ContactPage
- Purpose: Next.js page for
/contact. - Inputs: None.
- Returns / side effects:
AppShellwithProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGatearoundContactLoader. - Used by: Route
/contact.
Function: ContactScreen
- Purpose: Presentational in-app contact: heading Contact, lead, link to living-room rules, and a messenger-style composer (textarea with icon-only Send
IconButton, catalogaria-labelcontact.send, no HTML max length). Over 8000 characters is the field message. Success is owned byContactLoader(navigate to the inbox thread), not a local success copy. - Inputs:
ContactScreenProps—posting,draft,onDraftChange,onPost,formError(empty/tooLong/request). - Returns / side effects: React element. No network.
- Used by:
ContactLoader.
Function: middleware
- Purpose: Redirect
/mapto the shops map, rewrite a public language URL onto the unprefixed page, and give every other matched response its Content-Security-Policy. - Inputs: The incoming request. The matcher covers
/mapand every path except/_next/static,/_next/image,/sw.js, and the files underpublic/(icons,og.png,robots.txt,sitemap.xml,handbook-images/,happyland/). It readsCSP_MODEthroughgetCspModeon every request. Language URLs are/en,/de,/es,/fil, alone or followed by/about,/donate, or/rules. Every other path under a language prefix, such as/de/login, is not one of them. - Returns / side effects: For
/map, redirects to/shopsand keeps the query string, with the hash#map. A public language URL is rewritten to the unprefixed path, the request getsx-21gifts-public-locale, and a document open sets thelocalecookie (Path=/,Max-Age=31536000,SameSite=Lax,Secureon HTTPS). Every other matched request passes on. A fresh nonce (createCspNonce) goes into the policy (buildCsp). The policy is set on the response asContent-Security-Policy-Report-Only, orContent-Security-PolicywhenCSP_MODE=enforce, withReporting-Endpoints: csp="/monitoring/csp". The same policy and the nonce (x-nonce) are set on the request, so Next.js puts the nonce on its own scripts andRootLayouton its inline bootstrap scripts. - Used by: Next.js, before every matched request.
Function: PlacesMapScreen
- Purpose: Presentational map card: heading Map, then every live forum pin from
fetchPlaces. Without a Google key the pins are links. With a keyGoogleMapCanvasdraws the same pins as markers and does not replace the list. With a country, the list and the markers keep only the shop pins in that country. Each row is the author name and the pin text fromformatPlacePinText(name and address line, or coordinates). A pin label opens/{shopNpub}whenshopNpubis set, and/messages/:idwhen it is null. Those links arenext/link, so opening a member or a note keeps the document. After a pin edit saves, the row takeslat,lng,label,address, andshopNpubfrom the updated note; a response withoutshopNpubkeeps the old value. A name with an account id links to/members/:accountId; a name without one stays on the pin link. A moderator sees the shop pencil on a pin withshop: true; it loads that note and opens the same steps as editing a shop post. A failed load showsforum.editShopNoteLoadFailed, not the save-failure sentence.embeddedreturns that body without the heading or card. A long pin name or label wraps inside the row. With a key, one pin, or a?pin=that matches a pin, centers that pin at zoom 14. Several pins and no matching?pin=frame every pin (fitBounds, padding 32). A fitted zoom above 14 is set back to 14. - Inputs: Optional
embedded(default false),country(ISO 3166-1 alpha-2, or null for every pin), andonShopsChanged(run once after a moderator's shop save (a complete save, or a partly written one when its editor closes or unmounts)). Catalog viauseTranslations. Session fromuseAuthStore. Optional?pin=id. - Returns / side effects:
Card maxWidth="xl"surface={false}, or only the body whenembedded. Fetches places and/maps/key. With acountry, the list and the markers keep only the shop pins (shop: true, the pins the filter counts) whosecountryCodematches and the map fits (or centers on) those pins; none left is the empty copymap.empty. The Maps script loads once: a redraw while it is still loading (another country) waits for the same script, a superseded draw leaves the newer map alone. Fetches places and the browser key viafetchMapsKey. - Interaction log: An opened
?pin=whose place is a shop (shop: true) is recorded once asshop_openedwith that pin's note id; other pins are not recorded. - Used by:
ShopsScreen.
Function: fetchMapsKey
- Purpose: One shared loader for the browser Google Maps key from same-origin
GET /maps/key, used by the places map, the public shop page, and the place field instead of separate copies of the same fetch and parse. - Inputs: None. Reads the JSON body's
key. - Returns / side effects:
Promise<string | null>: the trimmed key, ornullfor a missing, non-string, or blank key and for any network or JSON failure. Never rejects. - Used by:
PlacesMapScreen,ShopScreen,PlaceField.
Function: loadGoogleMaps
- Purpose: One page-wide loader for the Google Maps JavaScript API, shared by
GoogleMapCanvasandPlaceFieldso they never add a second script. Calls made while the script is still loading get the same in-flight promise. - Inputs: Browser key from
GET /maps/key. The one script (script[data-gmaps="weekly"]) loadshttps://maps.googleapis.com/maps/api/js?key=…&v=weeklywith no extra libraries. Ascript[data-gmaps="weekly"]this loader did not add is replaced by a fresh one with the given key, since its load or error event may already have fired; one markeddata-gmaps-state="error"rejects at once. - Returns / side effects:
Promise<void>that resolves at once whengoogle.mapsexists, otherwise when the script loads and installsgoogle.maps. On a script error it rejects and removes the script, so the next call adds a fresh script and retries. On a load withoutgoogle.mapsit rejects, marks that scriptdata-gmaps-state="error", and every later call rejects until the script is removed from the document. - Used by:
GoogleMapCanvas,PlaceField.
Function: onGoogleMapsAuthFailure
- Purpose: One owner for Google's global rejected-key hook
window.gm_authFailure.GoogleMapCanvasandPlaceFieldon the same page both subscribe, so neither overwrites or deletes the other's handler. - Inputs: A listener called when Google rejects the browser key. The module installs its one hook on the first subscribe or
loadGoogleMapscall, and puts it back if another script replaced it. - Returns / side effects: An unsubscribe function. A report is remembered for the
google.mapsnamespace that was on the page when Google made it: a later subscriber on the same page is called at once. A report beforegoogle.mapsexists reaches current subscribers only. - Used by:
GoogleMapCanvas,PlaceField.
Function: fetchPlaces
- Purpose: Load every live top-level forum pin for the signed-in session.
- Inputs:
sessionTokenbearer. - Returns / side effects:
ForumPlaceRow[]fromGET /forum/messages/places. A row may includeshop: truewhen the note is a shop,shopNpub(npub for a listed shop, null before its key exists; an older api omits it and the schema normalizes that to null), andcountryCode(ISO 3166-1 alpha-2 of the pin's coordinates, null in the open sea, omitted by an older api). Throws the visitor-facing load error on a non-2xx status, a network failure, or a body that fails the schema. - Used by:
PlacesMapScreen,ShopsCountryFilter.
Function: proxyMessagesPlacesGet
- Purpose: Same-origin Bearer proxy of api
GET /messages/places. - Inputs: Incoming request.
- Returns / side effects: The upstream response. No session of its own.
- Used by:
GET /forum/messages/places.
Function: PlaceField
- Purpose: Optional place control on the top-level forum composer, the compact editor a moderator uses on a shop note. Opens a map when
/maps/keyreturns a key. Confirm stores{ lat, lng, label }. No key shows the unavailable sentence and does not confirm a pin. On the device's local Sunday the dialog is not rendered. A confirmed composer place isPlacePinChip, not a preview in this control. It opens a centered desktop dialog or full-screen mobile sheet. The body is the only active scroll surface, the confirm row stays visible, Tab / Shift+Tab wrap between the dialog's first and last enabled controls. Shop mode orders map, shop name, street/house, postal/city, country; touched fields show concrete live errors while the footer explains why confirm is disabled; when the map is unavailable, the message where the map would be is that reason and the footer does not repeat it. With stored shop text, the trimmed shop name that will be committed is also checked live against the API's 20–1000-character and strictly-shorter-than-text rule. A current live name error wins over an older reported server name error. - Inputs:
place,disabled,onChange. OptionalbuttonSize(lgdefault, orsm),buttonVariant(secondarydefault, orghost),previewSlot(accepted and not read),ariaLabel(default Add a place),onCommit. WithoutonCommit, Use this place and Remove place callonChangeand close. WithonCommit, those buttons wait; a rejection keeps the dialog open with its reason; a success closes without callingonChange. When a pin is already set, Remove place stays inside the open dialog, including when the map is unavailable. OptionalshopDetails(shop name and the five address fields; a shop dialog never offers Remove place),shopText(checks the shop name against that text while typing),problem(a known API fallback shown at its field),autoOpenProblem(default true: such a problem opens the dialog once),onAvailabilityChange(reports a checked map availability to the wizard). The oldshowPreviewprop is removed; a confirmed composer place shows asPlacePinChip. - Returns / side effects: Attach button and an accessible modal dialog. Fetches
/maps/keywhen opened. A stored place can be removed from the living-room composer (noshopDetails). A shop dialog never offers Remove place, because a shop name cannot be cleared. Fetches/maps/keythroughfetchMapsKeywhen opened and loads Google's script through the sharedloadGoogleMaps. Subscribes to a rejected key throughonGoogleMapsAuthFailurefor its whole lifetime: an open dialog switches to the unavailable sentence, and a closed one stays unavailable when it is opened again. A known server problem reopens the dialog at its field. - Used by:
ForumBoard(top-level composer, noshopDetails),ShopAddWizard(shopDetails), andShopPlaceControl(shopDetails).
Function: PlacePinChip
- Purpose: Shows a confirmed forum-composer place in normal document flow so it cannot cover validation or request feedback below the composer.
- Inputs:
place(ForumPlacePin), optionaldisabled, andonRemove. - Returns / side effects: A full-width, content-capped muted chip with MapPin, localized label or coordinates, and an icon-only Remove place control. Removal calls
onRemove; disabled state reaches the control. On the device's local Sunday the chip content is removed by the same writing gate as the place field. - Used by:
ForumBoard, on its own line between the photo row and the text field.
Function: CameraPhotoButton
- Purpose: The camera button beside a gallery button wherever a member adds a photo. It is an icon-only
IconButton(lucideCamera) with its own hidden<input type="file" accept="image/*" capture>. On a phone,captureopens the camera instead of the photo picker. Android's photo picker, which opens for the gallery inputs with their explicit type lists, has no camera. A desktop browser ignorescaptureand opens its file dialog. The input takes one photo per press and no video; video stays on the gallery button. - Inputs:
label(catalog accessible name and tooltip), optionalfacing(environment, the back camera, by default;user, the front camera, for the profile photo),size(mddefault,lgbeside a large gallery button),disabled(button and input together),name(on the hidden input), andonChange, the change handler of the gallery input beside it. - Returns / side effects: The icon button followed by its hidden input. A press clicks the input. The picked photo goes to
onChange, so it gets the same type check, resize, Exif capture time, error sentences, and photo limit as a gallery photo. No network by itself. - Used by:
ForumBoard(top-level composer),ForumAskWizard(photos step),ShopAddWizard(photos step, also when a shop note is edited),InboxScreen(thread composer, also in the moderator staff room),AboutMeSection(photo, profile photo, and wide image in the editor), andProfileScreen(empty profile-photo and wide-image slots).
Function: fitBoxInFrame
- Purpose: Places one popover inside the app frame. The width is the preferred width when it fits, otherwise the room between the insets. The left edge stays on the anchor unless that would cross an inset. Vertically it opens downward when that side has at least 280px and at least as much room as above, otherwise upward, otherwise from the top inset across the whole frame height. It returns null when the frame has no positive room or the preferred width is not positive.
- Inputs: Frame left, right, top, and bottom, anchor left, top, and bottom, gap, preferred width, inset, and viewport height, all in pixels.
- Returns / side effects:
{ left, width, maxHeight, top, bottom }with exactly one of top or bottom set, or null. No DOM writes and no network. - Used by:
ForumModeSelectfor the chip listbox.
Function: pageFrameProblems
- Purpose: Reads the live document and lists sideways scroll of the document, sideways scroll of the active page scroller, boxes whose border box leaves the window by more than one pixel on the left, right, top, or bottom, and position:fixed overlays whose border box covers the app chrome row (
[data-app-chrome]) by more than one pixel. An overlay whose root or an ancestor carriesdata-covers-chrome(the tour, the top toast, a full-screen dialog, the lifted menu) is exempt from the chrome check. Content inside[data-scrollport]may sit past the top or bottom of the window unless it is position:fixed. A position:fixed box is still reported. A box inside[data-scroll-x]is ignored for the horizontal check unless it is position:fixed and its border box already crosses the left or right edge of the window. The sideways row itself is not ignored. - Inputs: None. Uses the open document,
window.innerWidth, andwindow.innerHeight. - Returns / side effects: A string array. Empty means the page stays in the window and no overlay covers the chrome row. No DOM writes and no network.
- Used by:
shotScreenine2e/visual.spec.ts, before every screenshot, and the behavior testFunction: pageFrameProblems.
Function: ShopPlaceControl
- Purpose: Moderator-only place editor on a listed shop note. Hidden on replies, hidden notes, non-shop text, unsigned sessions, and ranks below moderator.
- Inputs:
message(top-level shop note) andonUpdated(message id plus the saved pin). The control does not clear a shop place. - Returns / side effects: Compact
PlaceField(small ghost Add a place / Edit place) withmessage.text, so invalid name/text combinations are linked under Shop name and block Use this place before the request.onCommitcallssetMessagePlace; a failed save keeps the panel open and maps known API reasons back to their owning field or footer. - Used by:
ForumBoardwhenshopPlaceEditandonShopPlaceUpdatedare set (ForumLoaderfeed="shops").
Function: ShopNoteEditControl
- Purpose: Moderator-only pencil on a listed shop note. Opens the same five steps as adding a shop, already filled in, plus the edit history. Hidden on replies, hidden notes, non-shop text, unsigned sessions, and ranks below moderator.
- Inputs:
message(top-level shop note),onUpdated(the saved note, after each saved part), optionalonSaved(once, after every changed part is saved; when a later part fails after earlier parts were written, the editor stays open with its error andonSavedruns once when it is closed or unmounted, except when only a place written ahead of the text was saved; never while a save is still running: a close or unmount mid-save reports once when the save settles; the pencil does not reopen the steps until a running save has settled), optionalexistingPhotos, optionalexistingVideoUrl, and optionalstartOpen. - Returns / side effects: Small ghost pencil (Edit shop note). The summary button is Save changes. A picked or camera photo that cannot be used shows
inbox.errorUnsupported(also when the browser cannot decode it, such as HEIC in Chromium) orinbox.errorTooLargeunder the steps, and stills past ten showforum.errorTooMany; the next usable pick clears that sentence, and so does removing a still or opening the editor again. While a picked photo is prepared the steps stay busy (Save and the photo controls are disabled), and a photo still being prepared when the editor closes is dropped. It writes only the text, place, account, or stills that differ from the values captured when the editor opened: the text without the shop tag, a structural copy of the place, and the username. A later change to the listed note's place or account is not written back unless that field was edited in the editor. Whether this editor changed the place is decided by the place captured when it opened. When both the text and the place changed, write order uses the place still on the message, because a shop name changed outside the open editor can make the new text invalid until that place is written. Stills still use the photo baseline. A video stays. Cancel, and closing the open pencil, discard a photo that is still being prepared, so a late result does not enter the draft. Save stays locked while a preparation runs, and Wait until this photo is ready. sits above the buttons. A save that has not returned shows Saving this shop note. in that same place and keeps Save changes disabled. Rejected stills show the concrete reason under the picker; APIAt most 10 photosmaps totooMany, andPhoto must be a JPEG, PNG, or WebP under 1 MiBmaps toformatOrSize(inbox.errorFormatOrSize), returning to the photo step instead of showing the generic save error. Overlapping picks compute their remaining room from the latest pending-photo state and never exceed 10. Already-shown stills are copied onto addresses this editor owns before the steps open, so a partial save can revoke the feed addresses without blanking the open editor. A failed copy opens the steps withforum.editShopNoteFailedand no stills, and does not revoke the feed addresses. Stills are not replaced unless every current still loaded. A known API 400 returns to its owning wizard field; changing another field keeps that feedback until its owning place, text, or username field changes. Only unknown failures useforum.editShopNoteFailed. History rows show who, when, and the field (text, place, or account). Until the history response arrives, Loading the history. is shown under History and is not an alert. Rows replace that sentence. A failed history load showsforum.editHistoryFailedinstead of the loading sentence. The place dialog shows Loading the map. until its map script is ready, and does not show that sentence together with the unavailable map. - Used by:
ForumBoardwhenshopNoteEditandonShopNoteUpdatedare set (ForumLoaderfor a moderator on every feed),ShopTable, andPlacesMapScreenfor a pin withshop: true.
Function: ShopAccountSuggestions
- Purpose: The People list under a shop-account field. Each row is
@usernameand the display name when it differs. The highlighted row uses the hover fill. Choosing a row reports that username and does not save. - Inputs:
listId,rows(id,username,name),activeIndex,disabled,className,optionId, andonPick. - Returns / side effects: A
listboxlabelled People.onPickruns on mouse down and on click. No network. - Used by:
ShopAddWizardon the username step andShopAccountControlin the moderator panel.
Function: ShopAccountControl
- Purpose: Moderator-only shop-account editor on a listed shop note. Hidden on replies, hidden notes, non-shop text, unsigned sessions, and ranks below moderator.
- Inputs:
message(top-level shop note) andonUpdated(message id plus the saved{ id, username, name }, ornullwhen the saved message omitsshopAccount). - Returns / side effects: Small ghost account editor. The People list is
ShopAccountSuggestions. Arrow keys move the highlighted row and Enter writes that username into the field without saving. A valid non-empty username starts a 150 ms debouncedlookupAccountByUsernamecheck. The untouched initial@keeps Save disabled and shows the linked muted hint Type or pick the 21.gifts username to continue. After an edit, or when that field is left, an empty value or a bare@is put back to@and shows that same sentence as the linked field error witharia-invalid, and Save stays disabled. A value that does not start with@gets one, so a typed letter still lists accounts. Save is also disabled while the current non-empty value is pending or proven missing; pending shows the linked muted Checking that account… reason, and the linked missing message is live without an alert. A failed lookup does not block and does not show that the account is missing, becausesetMessageShopAccountvalidates again. Only errors returned after Save userole="alert"; success callsonUpdatedand closes. The control does not offer a way to clear the account. A response that omitsshopAccountstill passes null toonUpdated. - Used by:
ForumBoardwhenshopAccountEditandonShopAccountUpdatedare set (ForumLoaderfeed="shops").
Function: ShopsPage
- Purpose: Next.js page for
/shops. FlowAppShell(align="start") withProfileChromeLeft+SignedInChrome,OnboardingGatescreen="welcome", andShopsScreen. Noroute.tsbeside the page. - Inputs: None.
- Returns / side effects: The shops screen.
- Used by: Route
/shops.
Function: ShopsScreen
- Purpose: Presentational shops card: heading Shops, lead
shops.lead, a country filter in the top bar, and a List / Map / Table / Post pill, then the selected body. List isShopList. Post isForumLoaderfeed="shops". Map isPlacesMapScreenembedded. Table isShopTable. A plain click on a link to a view of this same page (a place opens/shops?pin=…#map) selects that view once the click is dispatched (no or an unknown hash is List, as on load), because the client-side push fires nohashchange. The push keeps the entry the link was clicked from, so browser Back (popstate) returns to that view. The top-left arrow is the exception: it carriesdata-view-history-back, its href is the view-stack path and has no hash, and whencanStepBackis true the click steps back withrouter.back()and the view follows the restored entry instead of treating that href as List. Any other link to this page, including a hashless/shopslink, still selects the view in its href. Links with atargetordownloadare left alone. - Inputs: Catalog via
useTranslations. The view stays unset until the hash is read./shops#post,/shops#map, and/shops#tableopen that view. A missing or unknown hash opens List. Choosing an option writes the same hash. List clears it. Thecountryquery (shopCountryFromQuery) is the country filter: it is read with the hash on load, onpopstate, and from a link to this page. - Returns / side effects:
Card maxWidth="xl"surface={false}.ShopsCountryFilterregisters its chip in the top bar. Choosing a country sets or removescountrywithuseRouter().push(scroll: false), keeping the other query values and the hash, so each choice is a history entry that browser Back and Forward return to. The country goes toForumLoader,ShopTable, andPlacesMapScreen(the post list and the table remount per country, so their pages restart).ShopListremounts with the same view key and still loads the full directory. Each of the post list, map, and table reportsonShopsChangedafter a shop is added or hidden, or once per moderator save of a shop note or pin (complete, or partly written once its editor closes or unmounts); the filter then reloads its counts, and a filtered view reloads from the api, because only the api knows the country of a new or moved pin. The list, post feed, map, and table mount only after the hash is read. The map and table fetch only after their option is selected. - Used by:
ShopsPage.
Function: ShopsCountryFilter
Compact country chip in the top bar, to the right of the wordmark. It reuses the chip variant of ForumModeSelect, with the accessible name Country (shops.countryLabel); its listbox is placed inside the frame box. The first row is All countries (shops.countryAll); the others come from shopCountryOptions and read {name} ({count}) (shops.countryOption), with no count while the pins load or when they could not be loaded.
- Purpose: Choose the country whose shops
/shopsshows, or All countries. - Inputs:
value(ISO 3166-1 alpha-2 code or null) andonChange. Session fromuseAuthStore; locale and catalog viauseTranslations. - Returns / side effects: The select, or null without a session. Loads the pins once with
fetchPlaces; a failed load keeps the choice and shows no error (the lists below show their own). Choosing All countries callsonChange(null), a country calls it with its code. - Used by:
ShopsScreen.
Function: shopCountryFromQuery
Reads the country query of /shops. A shared link can carry any text, so only the codes the api gives a pin count: the 249 assigned ISO 3166-1 alpha-2 codes plus XK (Kosovo), in any case; the code is upper-cased. A grouping (EU), an alias (UK), a withdrawn code (YU), or a reserved one (EA) is All countries.
- Purpose: Country code from the address, or All countries.
- Inputs: The raw
countryvalue, or null when it is absent. - Returns / side effects: The upper-case code, or null for anything that is not one of those 250 codes. No I/O.
- Used by:
ShopsScreen.
Function: shopCountryOptions
Builds the country list of the Shops filter from the pins of GET /forum/messages/places. Only shop pins (shop: true) are counted, per countryCode; a pin without a country (open sea, or an older api) counts only under All countries. Names come from Intl.DisplayNames in the UI language (an unnamed code keeps its letters) and sort with that language's collation.
- Purpose: Countries that have shops, with their localized name and shop count.
- Inputs: The pins (or null while loading), the UI locale, and the selected code (or null).
- Returns / side effects:
{ code, name, count }[]sorted by name. A selected code with no shop left is listed with count 0; while loading every count is null. No I/O. - Used by:
ShopsCountryFilter.
Function: ShopsViewSwitch
- Purpose: Neutral
SegmentedControllabelled Shop view that switches the shops page between List, Map, Table, and Post. A missing or unknown hash opens List. Choosing List clears the hash.#postopens Post. - Inputs:
value(list,map,table, orpost) andonChange. - Returns / side effects: A
SegmentedControltone="neutral"in the order List, Map, Table, Post. The pressed option uses the app button fill. No network. - Used by:
ShopsScreen.
Function: ShopList
- Purpose: List of shop pages. A row is the shop name linking to
/{npub}. Forum notes without a shop page stay on Post. - Inputs: Catalog and locale via
useTranslations. An account is not required. - Returns / side effects: Calls
fetchListedShops. The page size stays inside that function. The link text is the shop name trimmed,classNameunderline, andhrefis/{npub}. Whenplaceis non-null, the place line under the link isformatPlacePinTextand is not a link. Whenplaceis null, that line is omitted. Rows are keyed bynpub. Show more loads the next page. An empty page with a next cursor keeps Show more and does not showshops.empty. A failed later page keeps the rows, showsshops.loadError, and Try again reloads that same cursor. A failed first page replaces the list withshops.loadError, and Try again loads the first page again. Until the first page arrives, the line ismap.loading. Does not callfetchMessages, does not open/setup/rules, and does not render/map,/members/, or Edit shop note. - Used by:
ShopsScreen.
Function: ShopTable
- Purpose: Table of shop notes with name, place, and operator. A moderator sees the same shop pencil on each row. Place and operator are client-side links (
next/link), so opening them keeps the document. - Inputs: Optional
country(ISO 3166-1 alpha-2, or null for every shop); with it every page also sendscountry, so the api returns only shops pinned in that country and Show more pages only those. OptionalonShopsChanged, run once after a moderator's shop save (a complete save, or a partly written one when its editor closes or unmounts). Session fromuseAuthStore. Catalog viauseTranslations. - Returns / side effects: Loads
GET /forum/messages?hashtag=21GiftsShop&mode=all. Name is the place label when the pin has a non-empty name and an address; otherwise the first note line, or the stored author name. Place links to/shops?pin={id}#mapviaformatPlacePinText(name and address line, or coordinates;ShopsScreenthen shows its map on the same page). Operator links to/members/{id}as@username. A missing place or operator is an em dash (shops.missing). Show more loads the next page. If a page has no shop rows and another page exists, Show more stays and the empty sentence does not. If that page fails, the rows already shown stay, with the forum error and Try again, which reloads the same page. A failed first page replaces the table with that error. A missing-requirements response opens/setup/rulesinstead withreturnToView(a step back when setup opened this page, otherwise a replace). Null without a session. - Used by:
ShopsScreen.
Function: MessageKindTags
- Purpose: Author row for a note, plus one tag per kind. Loan and Donation are buttons. Pressing one shows its explanation and pressing it again hides it. #Shop stays a link to
/shops. - Inputs:
kindsfromnoteKinds.childrenis the author name and any role tag. - Returns / side effects: The row and, when a loan or donation tag is open, a
role="status"sentence. No network. - Used by:
ForumBoard, the public note page, and theForumAskWizardpreview.
Function: noteKinds
- Purpose: Which tags a note shows. A reply has none. A repayable ask is a loan. Any other positive ask is a donation. A
#21GiftsShoptoken adds shop. - Inputs:
parentId,text, optionalgoalSats, optionalgoalRepayable. - Returns / side effects:
loan,donation, andshopin that order, or an empty list. No network. - Used by:
ForumBoard,ForumAskWizard.
Function: isShopNote
- Purpose: True when
textcontains a#21GiftsShoptoken (case-insensitive; next character not[A-Za-z0-9_]). - Inputs:
text: string. - Returns / side effects: boolean. No network.
- Used by:
ForumLoader,ForumBoard,ensureShopHashtag.
Function: stripShopHashtag
- Purpose: Remove
#21GiftsShoptokens from display text and collapse leftover blank lines. - Inputs:
text: string. - Returns / side effects: Display string (empty if only the hashtag was present). No network.
- Used by:
ForumBoard.
Function: ensureShopHashtag
- Purpose: Append
\n\n#21GiftsShopwhen missing; empty/whitespace becomes#21GiftsShop; already-tagged text is unchanged. - Inputs:
text: string. - Returns / side effects: Text to POST when the author is unpaid-write exempt, otherwise the compose-fee invoice comment. No network.
- Used by:
ForumLoader(shops compose).
Function: ISO_COUNTRIES
- Purpose: ISO 3166-1 alpha-2 country codes accepted on a shop pin address. Same set as the 21gifts API place contract.
- Inputs: None. A
Setof uppercase two-letter codes. - Returns / side effects: Membership lookup for
countryOptionsand address validation. No network. - Used by:
countryOptions,shopAddressProblem(via country normalize).
Function: countryDisplayName
- Purpose: Localized region name for an ISO 3166-1 alpha-2 code via
Intl.DisplayNames. - Inputs:
code(uppercase ISO code) andlocalefor the display names. - Returns / side effects: The localized name, or
codewhen the runtime has no name. No network. - Used by:
countryOptions,formatShopAddressLine.
Function: countryOptions
- Purpose: Country options for a native
<select>, labeled inlocaleand sorted by that label. - Inputs:
localeforIntl.DisplayNamesandlocaleCompare. - Returns / side effects: One
{ value, label }per code inISO_COUNTRIES. No network. - Used by:
ShopAddressFields.
Function: shopAddressProblem
- Purpose: First invalid address field on a shop pin, or null when the address matches the API rules. Empty address is
'missing'. Field order is street, house number, postal code, city, country. Each value is trimmed before its control-character rule, so pasted edge tabs are ignored while an inner tab is rejected. - Inputs: Structured
ForumPlaceAddress, ornullwhen every field is empty. - Returns / side effects:
'missing','street','houseNumber','postalCode','city','country', ornull. No network. - Used by:
shopPlaceComplete.
Function: shopAddressProblems
- Purpose: Reports every broken API address rule at its own field instead of reducing the address to one generic error. Control-character checks use each trimmed draft, accepting pasted edge tabs but rejecting inner tabs.
- Inputs: Structured
ForumPlaceAddress, ornullwhen every field is empty. - Returns / side effects: Sparse field-to-rule map for street, house number, postal code, city, and country. No network.
- Used by:
PlaceFieldfor live adjacent errors and its visible disabled-button reason.
Function: shopNameProblem
- Purpose: Name problem of a shop pin. Blank label is
'name'; over 80 characters is'nameLong'; control characters inside the trimmed name are'nameControls'; a standalone street or postal-code token in the name is'nameAddress'. Pasted edge tabs are ignored because the API stores the trimmed name. - Inputs: Pin label (shop name) and the structured address, each
nullorundefinedwhen unset. - Returns / side effects:
'name','nameAddress','nameLong','nameControls', ornull. No network. - Used by:
PlaceField,shopPlaceComplete,ForumLoader(pre-fee guard).
Function: shopDescriptionProblem
- Purpose: Shop-text problem of a shop note. Apart from LF/CR, control characters are rejected after the text is trimmed (an edge tab is ignored, like in the API). After CRLF is folded to LF and the shop tag is stripped, the text must be 20–1000 characters and strictly longer than the pin label.
- Inputs: Composer or stored note
text, and the pinlabel(ornull). - Returns / side effects:
'short','long','notLonger','controls', ornull. No network. - Used by:
ShopAddWizard,PlaceField,ForumLoader,ShopNoteEditControl.
Function: shopDescriptionText
- Purpose: The shop text as the 20–1000 character rule measures it: CRLF and lone CR are folded to LF, then the shop tag is stripped.
- Inputs: Composer or stored note
text. - Returns / side effects: The measured text. No network.
- Used by:
shopDescriptionProblem,shopDescriptionRemaining, and theShopAddWizardtext counter.
Function: shopDescriptionRemaining
- Purpose: Remaining characters needed to reach the 20-character shop-text minimum after the shop tag is stripped.
- Inputs: Composer or stored note
text. - Returns / side effects: Non-negative count. No network.
- Used by:
ShopAddWizardfor the text-step hint.
Function: shopAccountRequiredProblem
- Purpose: Required-account rule for a shop username, including an optional leading
@. Empty input, a bare@, and surrounding spaces are required. A typed handle is not this problem. - Inputs: Raw username draft.
- Returns / side effects:
'required'when the handle is empty after trim and one leading@is removed, otherwisenull. No network. Format stays inshopUsernameProblem. - Used by:
ShopAddWizard,ShopAccountControl, andcomposeShopUsernameinForumLoader.
Function: shopUsernameProblem
- Purpose: Checks the shop-account username format, including an optional leading
@. Empty input returns null.shopAccountRequiredProblemowns the required-account rule. - Inputs: Raw username draft.
- Returns / side effects: Trims, removes one leading
@, trims again, lowercases, then returns'format'outside^[a-z0-9][a-z0-9._-]{0,31}$; empty input returnsnull. No network. - Used by:
ShopAddWizard,ShopAccountControl, and the pre-payment validation inForumLoader.
Function: usernameProblem
- Purpose: Username problem for the login name and the account username, mirroring the api after trim and lowercase. A leading
@is not removed. - Inputs: Raw username draft.
- Returns / side effects:
'empty'when blank after trim,'format'when longer than 32 characters, only_, or outside^[a-z0-9][a-z0-9._-]{0,31}$, otherwisenull. No network. - Used by:
LoginCardname view,UsernameForm,usePasskeyLogin.
Function: entryTextProblem
- Purpose: Required text problem in message-API order: trim, then empty, then UTF-16 length.
- Inputs: Raw text and the maximum length after trim.
- Returns / side effects:
'empty'when blank after trim,'tooLong'over the maximum, otherwisenull. No network. - Used by:
ContactScreen.
Function: optionalTextProblem
- Purpose: Optional text problem. Blank after trim is valid. Length is UTF-16 after trim.
- Inputs: Raw text and the maximum length after trim.
- Returns / side effects:
'tooLong'over the maximum, otherwisenull. No network. - Used by:
placeLabelProblemfor the living-room place name length.
Function: composerTextProblem
- Purpose: Composer text. A photo or video makes a blank message valid. Over-length never is.
- Inputs: Raw message, maximum UTF-16 length after trim, and whether a photo or video is attached.
- Returns / side effects:
'tooLong'over the maximum,'empty'when blank without media, otherwisenull. No network. - Used by:
ForumBoard,ForumAskWizard,InboxScreen.
Function: shownEntryProblem
- Purpose: Which problem to show. Empty waits for blur or submit. Any other problem shows at once.
- Inputs: The current problem, or
null, and whether the field was blurred or submitted. - Returns / side effects: The problem to render, or
nullwhile an untouched field is empty. No network. - Used by: Contact, the living-room composer, Ask, inbox, daily amounts, and habits.
Function: replyTextIsTooLong
- Purpose: True when a reply is over 8000 characters. The
inReplyTo:line is counted only when this submit stores it. An explicit amount, and an exempt viewer, are checked on the typed text only. - Inputs: Reply draft, the parent note id or
null, whether this viewer may reply without the payment prefix, and whether this submit stores that prefix. - Returns / side effects: Whether the reply is too long. No network.
- Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread.
Function: placeLabelProblem
- Purpose: Living-room place name. Empty is a valid clear. Length is checked before controls. A name that is both too long and has a control stays the length problem. The server still answers both with one sentence, so a name the form already accepted keeps the 80-character sentence.
- Inputs: Raw place name.
- Returns / side effects:
'tooLong'over 80 characters,'controls'for a character below 32 or DEL in a name that fits, otherwisenull. No network. - Used by:
PlaceFieldwhen the dialog is not a shop.
Function: habitTextProblem
- Purpose: Habit field problem, matching the member-habit route. Name and comment are trimmed. Description and notes are not.
- Inputs: Field kind and the raw text.
- Returns / side effects:
'empty'when a required field is blank,'tooLong'over 80 code points for a name or 2000 for the other fields, otherwisenull. No network. - Used by:
MemberHabits.
Function: displayNameProblem
- Purpose: Display-name problem in api order: trim, then empty, then length, then controls.
- Inputs: Raw display name. Inner spaces stay.
- Returns / side effects:
'empty'when blank after trim,'long'over 80 characters,'controls'for a character below 32 or DEL, otherwisenull. No network. - Used by:
NameForm.
Function: locationProblem
- Purpose: Location problem. Blank after trim is a valid clear, unlike the display name.
- Inputs: Raw location. Inner spaces stay.
- Returns / side effects:
'long'over 80 characters,'controls'for a character below 32 or DEL, otherwisenull. No network. - Used by:
LocationForm.
Function: aboutMeTextProblem
- Purpose: About me text problem, in the same order as forum text: trim, then length, then controls. Line breaks stay valid.
- Inputs: Raw About me note. Inner spaces and line breaks stay.
- Returns / side effects:
nullwhen blank after trim,'long'over 8000 characters,'controls'for a control other than LF or CR, or for DEL, otherwisenull. No network. - Used by:
AboutMeSection.
Function: formatShopAddressLine
- Purpose: One address line for a shop pin: street, house number, postal code, city, and the localized country name.
- Inputs: Complete structured address and UI
locale. - Returns / side effects:
${street} ${houseNumber}, ${postalCode} ${city}, ${countryName}. No network. - Used by:
formatPlacePinText,ShopAddWizardsummary.
Function: formatPlacePinText
- Purpose: Visible text for a forum pin. With an address, name · address line, or the address line alone. Without an address, the name or five-decimal coordinates.
- Inputs: Stored
ForumPlacePinand UIlocale. - Returns / side effects: Link or table cell text. No network.
- Used by:
ForumBoard,ShopTable,PublicMessageLoader,ShopNoteEditControl,PlacePinChip,PlacesMapScreen.
Function: shopPlaceComplete
- Purpose: Whether a shop pin has a valid name and structured address.
- Inputs: Composer pin, or
nullwhen unset. - Returns / side effects:
truewhenshopNameProblemandshopAddressProblemare both null. No network. - Used by:
ShopAddWizard(place-step Next and summary Post),ForumLoader,ShopNoteEditControl.
Function: apiMediaProblem
- Purpose: Map the API's exact photo-count and photo/video/poster size-or-format rejection bodies to media pick reasons rendered by the composer without claiming that every combined rejection is only a size problem.
- Inputs: An
Error.messagestring from a forum post or shop-photo update. - Returns / side effects:
'tooMany'for the 10-photo limit,'formatOrSize'for the photo, video, and poster messages that can mean an unsupported/undecodable file or an exceeded limit, ornullfor unknown text. No network. - Used by:
ForumLoadershop creation andShopNoteEditControlphoto updates.
Function: shopApiProblem
- Purpose: Map an exact API 400 body to a shop form error. Unknown text returns null so the generic save copy stays.
- Inputs:
Error.messagefrompostMessage,setMessagePlace, orsetMessageShopText, plus whether that request belongs to a shop post or place. - Returns / side effects: A field/step-specific shop problem for name, address, description, or username, or
null. Generic forum text-range and place-label-length bodies map only for shop requests. No network. - Used by:
ForumLoader,PlaceField,ShopNoteEditControl.
Function: shopProblemField
- Purpose: Identify which editable shop field owns a mapped API problem, so unrelated edits keep their server feedback.
- Inputs: A
ShopApiProblemfor a shop name/address, description, or username rejection. - Returns / side effects:
'place','text', or'username'. No network. - Used by:
ShopAddWizard,ForumBoard,ForumLoader, andShopNoteEditControlfor server-error routing and field-scoped clearing.
Function: isShopApiProblem
- Purpose: Narrows an unknown composer value to one of the mapped shop API problems shared by the loader and board.
- Inputs: Any unknown value.
- Returns / side effects:
trueonly for string keys inSHOP_API_MESSAGE; otherwisefalse. No network. - Used by:
ForumLoaderto preserve or clear mapped shop errors andForumBoardto route them to the shop wizard or localized alert copy.
Function: ShopAddressFields
- Purpose: Five native fields for a shop pin address in the professional street/house and postal/city row order, plus a country
<select>. Street and house number, and postal code and city, show their messages under their row in field order; country shows its own under the select. - Inputs:
value,disabled,onChange, optional per-fielderrors, and optionalonBlur(field). - Returns / side effects: Labeled inputs with linked
aria-invalid/aria-describedbyerrors. Autocompleteoff/off/postal-code/address-level2/country. No network. - Used by:
PlaceFieldwhenshopDetailsis set.
Function: RulesDocument
- Purpose: Presentational living-room rules body from catalog keys: lead with the The test callout, three rule cards (
rules.lawKickerwith{n}, title, body, optional test callout), welcome / allowed / better-not / forbidden lists rendered as bordered cards with lucide glyphs (Checktext-app-fg,Checkmuted,Minus,Xtext-app-danger), the Our house closing block (rules.houseBody+rules.houseClosing), and an optional Contact CTA to/contact. There is no forum back CTA in the document. - Inputs:
messagescatalog for the request locale; optionalshowNav(defaulttrue); optionalchapter(RulesChapterId). Whenchapteris set, only that chapter is rendered and the public nav is omitted (showNavignored). WhenshowNavisfalseandchapteris omitted, the public Contact nav is omitted. - Returns / side effects: React element. Server component — uses
translate, notuseTranslations. No network. - Used by:
RulesPage,RulesSetupPage.
Function: RulesPageChrome
- Purpose: Client chrome wrapper for public
/rules: when a session is hydrated (ready && session !== null), mounts signed-in shell (ProfileChromeLeft+SignedInChrome); otherwise mountsProfileChromeLeftwithHomeWordmark(publicHrefishomeHref, the language home) plusLanguageSwitcher. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. The signed-in wordmark stays/welcome. - Inputs:
children(heading +RulesDocumentfromRulesPage) andhomeHref(unsigned language home). UsesuseHydrateSessionanduseAuthStoreforsession. - Returns / side effects:
PageChromewith the matching top-left / top-right slots aroundchildren. The unsigned wordmark openshomeHref. No network beyond session hydration. - Used by:
RulesPage.
Function: RulesPage
- Purpose: Next.js page for
/rules,/en/rules,/de/rules,/es/rules, and/fil/ruleswith localized heading and living-room rules document, wrapped inRulesPageChrome(signed-in or unsigned chrome depending on hydrated session). - Inputs: None. Calls
getRequestLocale()for the page title and document catalog, and passeshomeHref={localizedPublicPath(locale, '/')}toRulesPageChrome. - Returns / side effects: Heading +
RulesDocumentinsideRulesPageChrome(chrome is no longer always unsigned Wordmark + Language). The unsigned wordmark opens that language home. - Used by: Routes
/rules,/en/rules,/de/rules,/es/rules, and/fil/rules.
Function: ForumLoader
- Purpose: Client loader for the public forum on
/welcomeand/shopswithfeed="shops"(filter#21GiftsShop, hide laws, append hashtag on compose,emptyKeyshops.empty, passshopPlaceEditandonShopPlaceUpdatedso a moderator can set or replace the pin on an existing shop note, andshopAccountEditandonShopAccountUpdatedso a moderator can set or replace the shop account). Session and account fromuseAuthStore; shops return null without a session, and the living room loads the public active page instead. The laws hint stays hidden without a session. Living-room default remains Active (first paint{ mode: 'active', limit: 20 }, no hashtag). Shops always requestsmode: 'all'withhashtag: '21GiftsShop'and does not mount the mode selector, the Post/Ask pill, orForumAskWizard(allowAsk: false); it mountsShopAddWizardthroughshopComposerand does not apply active/unpaid/popular. A moderator session passesshopNoteEditon every feed, not only shops. A mode switch resets the loaded pages and refetches page 1 of the new mode without blanking the current list. AnIntersectionObserversentinel about eight notes from the visible end prefetches the next page whennextCursoris present; when a page kept no note (every row failed the note schema), the sentinel is the empty-feed line, so the next page still loads. An empty shops page showsshops.emptyimmediately. The 30-second visible-tab poll,visibilitychange, persistedpageshow, and pull-to-refresh fetch page 1 only, without a cursor; applying page 1 does not replace already-loaded older pages. Fetches viafetchMessages, renders public stills viaforumPhotoSrc; composer previews stay blob URLs inphotoUrls, and a shop-note save clears that id's blob URLs whilephotoVersionsbusts that id. LoadsrateDayvia the shareduseSpotRate()hook on mount (failure leavesrateDaynull), posts viafetchComposeTargetthenpostMessageInvoice(1 sat to 21.gifts,payHost: composer) for anyone below verified, otherwisepostMessagewith aphotosarray sopostMessagedual-sends{ photo, photos }(non-emptyphotoswins; max 10) orpostMessageVideo(multipart clip); composer submit is ignored while a note POST is in flight (syncnotePostInFlightRef, not only thepostingprop); prepares picks viaprepareForumPhoto/isForumVideoFile/prepareForumVideo; ownsphotoDrafts(plural, notphotoDraft),placeDraft, andvideoDraft/videoUrls;onPickFilesappends stills and setsformErrortooManywhen the selectedFilelist (not successful prepares) would exceed 10, preparing only the firstremainingslots; video xor stills; video-only posts are allowed. Pay invoices viapostMessageInvoice(optionaltextwhen the reply composer pays) and waits onfetchPublicMessagewhile the pay sheet is open (no attempt cap; aborts in-flight wait on Close / clear). A top-level note passessinceSatsand closes whensatsrises. An existing reply passessinceReceivedSatsand closes whenreceivedSatsrises. After that rise, the row is merged into loadedreplies/messages(no thread refetch). A text-only posting fee (a top-level post or a reply) closes the pay sheet once the compose-target note'ssatsrose and a new own row with that exact text is listed; when the own rows could not be read before the payment, any own row with that text counts, so one failed request cannot leave the sheet open after the payment (the member profile and the signed-in public note do the same for a reply). On every feed it passesrepayLinkso a funded credit of the author links to/loans/repay; the post itself has no repayment payment state. Owns Active/No gifts yet/All/Most popular feed mode (default Active) and the No gifts yet last-visit stamp (21gifts.forum-unpaid-seen): hydrates it on mount, stamps on entering unpaid and while unpaid as the list refreshes, and passesunpaidNewCounttoForumBoard(0 while unpaid is selected or messages are still null). After a successful living-room post withcreated.sats === 0, switches mode to All so the author sees the note, including a positivegoalSatsAsk, because Active and Most popular hide a note that has not received sats. If All is already selected, loaded pages andnextCursorstay. Shops already lists withmode: 'all'and does not switch. The sheet clears when the pay target is no longer in the visible parent list and not in loadedreplies(mode change, collapse, or delete), not when Active merely hides the parent note. Also pollsGET /forum/messagesuntil the merged list is payable (8 attempts, 2s; local extras kept until GET echoes), cancelled-flag fetch likeStatsLoader. Silently re-fetches onvisibilitychange(hidden→visible), onpageshowwhenpersistedis true, on aFORUM_LIST_POLL_MSvisible-tab interval, onFORUM_HOME_EVENT(wordmark / Menu Home while already on/welcome), and when the board pull-to-refresh callsonRefresh— shared load path with mount/retry; silent refresh does not flip the board to the loading copy when a list already exists, keeps the list when a silent refresh fails, and does not auto-scroll the newest note when a newer note arrives from refresh. When not at top (shellScrollTop(scroller) < 8is at-top;window.scrollYis only the no-shell fallback) andhasUnseenForumPostsis true, the fetch is held andForumBoardshows New posts; at the top the list is applied. With a session, fetchesGET /forum/notificationsvia existingfetchNotifications(cancelled-flag fetch like other ForumLoader loads) and, when an unreadmoderator_appointedrow exists (readAt === null), drives the ForumBoard pill (moderatorAppointedAvailable/onShowModeratorAppointed); click marks that row read viamarkNotificationReadand clears the flag, staying on/welcomewithout auto-scroll; a fetch error leaves the banner hidden; a mark-read failure leaves the banner (does not crash). The payable poll updates sats, payable,authorCanReceive, and the four payment snapshots (amountUsd,amountChf,amountEur,amountPhp) on already-listed ids only and does not insert unseen ids. A refresh held behind New posts applies the same update to the notes already shown. Owns the living-room laws hint visibility fromaccount.forumLawsDismissedand persists dismiss viadismissForumLaws(optimistic; applies the response or restores the previous flag only when the session token is unchanged and an account is still present). Owns expand/replies (fetchReplies, retry, moderator nested-reply hide viaonDeleted/deleteMessagewithout removing the parent, reply composer: empty reply text and an empty amount invoices 21 sats even for verified (except toward an author who cannot receive yet: then it showsforum.errorEmptyand invoices nothing); unpaidpostMessagewithinReplyToonly when there is text and the amount is empty, and only for verified or on the member's own note (isOwnNote: no amount, an empty reply setsempty, never an invoice); below verified on someone else's note invoices 1 sat to 21.gifts via the compose-target note (payHost: composer); expand is ignored while a reply posts). A signed-in note card fully inside the shell scrollport callsmarkVisibleForumNoteRead; expanding still callsmarkNotificationsReadForMessage. After a failed media POST following compose-pay, the pay sheet is cleared (payWaiting/payInvoice/payMessageId/payHost) so a later compose invoices 21.gifts again. UsesnextPostRequirementso a missing name, username, wallet (apilightning-address), or rules agreement opensRequirementsOverlay(no Skip) before a post or reply retries. After a successful top-level post or reply, setshasPosted: trueon the session account when the session token is unchanged and an account is still present (no persist-flag / Skip-forever POST). A reply to a note whose author cannot receive yet (authorCannotReceive) never invoices a gift to the author: an empty one setsempty, and one with text posts unpaid (verified or above) or pays only the 1 sat posting fee. - Inputs: Optional
writer(ForumWriter, the forum home only): handed toForumBoard, so the living-room composer lives in the writer; every successful own post calls itsonClose: fromapplyCreatedNotewhen the app created the note (directly, or after the posting fee for a post with photos, a video, an Ask, a place or a shop), and from the posting-fee pay poll (startPayPollwithownPost) when the payment itself created a text-only post. A failed post leaves it open with its error. Optionalfeed('living-room'default,'shops') andcountry(ISO 3166-1 alpha-2, or null); on the shops feed a country is sent with every page, so only shops pinned in that country load. The living room ignores it.ShopsScreenremounts the loader when the country changes. OptionalonShopsChangedruns on the shops feed after a shop is created, a moderator hides a shop, saves its place, or saves a shop note (onShopNoteSaved: once per save, not after each part; a partly written save reports when its editor closes or unmounts). Reads session and account from the auth store. - Returns / side effects: React element wrapping
ForumBoard, ornull. Owns draft/askDraft/composeIntent/askStep/askCadence/placeDraft/photoDrafts/videoDraft/photoUrls/videoUrls/posting/formError/feedMode/loaded-pages/nextCursor/pay/expand/replies/refreshing/rateDaystate, the No gifts yet last-visit stamp, and retry attempts.askCadencedefaults to once and returns to once after the visitor's own compose is paid (postAfterPayorswitchToAllin the pay poll) and inapplyCreatedNote. A gift or a reply does not clear it. Empty text without photos and without a video setsempty; trimmed text longer than 8000 characters setstooLongand does not callpostMessage/postMessageVideo. Photo-only and video-only posts are allowed. Empty reply text with an empty amount invoices 21 sats (pay-sheet default) (except toward an author who cannot receive yet: then it showsforum.errorEmptyand invoices nothing) and does not setempty, including when the parent omitsaccountId. A non-exempt reply with text and an empty amount still invoices 1 sat instead of settingamount.0is billed as 1 sat. Non-digits and overflowing amounts still setamount(forum.errorReplyPayment). When the parent omitsaccountId, an unpaidpostMessageis attempted only for a reply that has text and an empty amount, and a payment 403 starts a 1-sat invoice. Fetch failure sets the error flag without clearing an already-posted list; the board still shows Try again. A failed silent refresh with an existing list does not set the error flag. A late GET merges locally posted rows that the response does not yet contain; a POST whose id is already in the list is not prepended again. An empty or whitespace-only pay amount requests 21 sats and does not fillpayDraft. ACannotReceiveError(apicodecannot_receive) on a gift or a paid reply maps toauthorWallet; on a posting fee (the 1 sat to 21.gifts before a note or a reaction) it staysrequest; aWalletRequiredError(apicodewallet_required) on a gift, a paid reply, or a posting fee opens theRequirementsOverlaywalletstep; a missing or deleted note (NoteDeletedError, HTTP 404) maps todeletedon the pay sheet and on a paid reply; a 404 on the platform compose-target invoice staysrequest; other invoice failures stayrequest; rate limit staysrateLimit. Revokes photo and video blob URLs on unmount. May POST/me/forum-laws-dismissed. After a successful top-level post or reply, writeshasPosted: trueon the session account only when the session token is unchanged and an account is still present (no persist-flag POST). On shops, passesshopComposerso the board mountsShopAddWizard,shopPlaceEdit/onShopPlaceUpdatedso a saved or cleared pin updates that row, andshopAccountEdit/onShopAccountUpdatedso a saved or cleared shop account updates that row. For a moderator on every feed, including the living room, passesshopNoteEdit/onShopNoteUpdated. PassesrepayLinkon every feed (the viewer's own credit links to/loans/repayas Pay early or end collecting while open below goal, otherwise Repay your loan),lawsVisible/onDismissLaws,mode/onModeChange,nearEndRef,unpaidNewCount,refreshing/onRefresh,newPostsAvailable/onShowNewPosts,moderatorAppointedAvailable/onShowModeratorAppointed, andrateDaytoForumBoard. Stamps last visit on unpaid; mode is not persisted. Does not passError.messageto the board. A paid reaction keeps the reply composer in place, disabled, with the typed sentence in it, and opens ForumReplyPayPage (the bottom pay sheet) over the page; the draft and amount stay until payment is observed, then both clear together with the preview; Close clears the preview and leaves the draft and amount in the composer, enabled again. Gift-on-reply and composer-hosted sheets stay as they are. Its redirects (/loginfor a signed-out mode or page that needs a session,/setup/rulesfor missing rules) usereturnToView: a step back when that page is the view below, otherwise a replace. When the post after a paid posting fee fails, it shows the request error, keeps the draft and the paid fee, and setsPaySheetFailedaroundForumBoarduntil the next invoice opens, so the fee's sheet slides away without Paid and posted. On a shop submit, a blank username is refused before post (usernameRequired).composerShopErrormaps shop name/address 400s outside Shops toshopElsewhere. - First post free: while the signed-in member is below verified and has no missing requirements, the loader calls
fetchComposeTargetonce (again when the session, role, or missing list changes) and passesfirstPostFreetoForumBoardfor the hint; a failed call shows no hint. On Post below verified (and without a paid fee waiting), it callsfetchComposeTargetagain, and that answer also decides the hint; an older mount answer that arrives later is ignored. When that answer hasfirstPostFree, it creates the note directly withpostMessageorpostMessageVideo(text, photos, video, place, shop account, and Ask goal as a paid post would carry): no invoice and no pay sheet. The created note is shown exactly as after a paid post (applyCreatedNote: All when the note has no gifts and is not an Ask, cleared composer,hasPosted: true), and the hint goes away. When the api refuses that create withPostFeeRequiredError, the hint goes away and the same Post continues into the normal 1-sat posting fee. Any other error keeps its usual handling. - Used by:
WelcomeScreen,ShopsScreen.
Function: hasDisplayName
- Purpose: True when the account has a non-null display name that is non-empty after trim.
- Inputs:
account. - Returns / side effects: Boolean. No side effects.
- Used by:
nextOnboardingPath,NameForm.
Function: hasAgreedToRules
- Purpose: True when the account has a non-null
rulesAgreedAttimestamp (epoch ms of first living-room rules agreement). - Inputs:
account. - Returns / side effects: Boolean. No side effects.
- Used by: UI that still checks agreement state (overlays, payable); wizard order uses
account.setuponly.
Function: nextOnboardingPath
- Purpose: Picks
/setup/name,/setup/username,/setup/rules, or/welcomefromaccount.setup.setup === 'wallet'maps to name, username, rules, or/welcomefrom the other fields; it does not map to/wallet. There is no address step: a member receives on their own in-app wallet, which background wallet setup registers without adding an onboarding step, and the api'ssetup === 'lightning-address'(which follows the name step, filled or skipped) resolves to username, rules, or/welcomewithout checking the name again. Other values stay a 1:1 map (skips advancesetupwithout clearingmissing). Username still cannot be skipped. - Inputs:
accountwith requiredsetupandmissing. - Returns / side effects: Path string. No side effects.
- Used by:
OnboardingGate.
Function: skipSetup
- Purpose: Skips the current onboarding name step without filling the field. Rules and username cannot be skipped.
- Inputs: Bearer session and
step(nameonly). - Returns / side effects: Updated
AccountfromPOST /me/setup/skip; callers mergesetupandmissinginto the auth store. - Used by: The
NameFormonboarding Skip button.
Function: fetchMember
- Purpose: Loads a signed-in member profile by account id.
- Inputs: Bearer session and
accountId. - Returns / side effects: Validated
MemberProfile, includingpostCount,replyCount, optionalshopCount, and optionalcreditCount, ornullon 401/404. ThrowsMissingRequirementsErroron 409. Hits/forum/members/:id. AprofileMessagethat failsforumMessageSchema(an About me saved empty: no text, no media, 0 sats) reads asnull, so the profile renders with the About me empty state instead of failing; the drop is counted in oneconsole.warnwithout content. - Used by:
MemberProfileLoader,ProfileScreen, andViewProfileLoader(signed-in refetch when the public payload has an id).
Function: fetchMemberPosts
- Purpose: Loads a member's top-level forum posts with
GET /forum/members/:id/posts. - Inputs: Bearer session and
accountId. - Returns / side effects: Parses
forumListSchemaand returns the messages newest-first, capped by the api at 200. Rows are parsed one by one (forumMessageRowsSchema): a note that failsforumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in oneconsole.warnwithout its content, and the other rows still render; only an invalid envelope fails the list. A 401/404 uses the same visitor-facing message-list failure asfetchMessages; a 409missing_requirementsthrowsMissingRequirementsErroras infetchMember/fetchMessages. - Used by:
MemberProfileScreen.
Function: fetchMemberShops
- Purpose: Loads a member's top-level forum shop notes with
GET /forum/members/:id/shops. - Inputs: Bearer session and
accountId. - Returns / side effects: Parses
forumListSchemaand returns the messages newest-first, capped by the api at 200. A 401/404 uses the same visitor-facing message-list failure asfetchMessages; a 409missing_requirementsthrowsMissingRequirementsErroras infetchMember/fetchMessages. - Used by:
MemberProfileScreen.
Function: fetchMemberCredits
- Purpose: Loads a member's top-level forum credit notes with
GET /forum/members/:id/credits. - Inputs: Bearer session and
accountId. - Returns / side effects: Parses
forumListSchemaand returns the messages newest-first, capped by the api at 200. A 401/404 uses the same visitor-facing message-list failure asfetchMessages; a 409missing_requirementsthrowsMissingRequirementsErroras infetchMember/fetchMessages. - Used by:
MemberProfileScreen.
Function: fetchMemberReplies
- Purpose: Loads a member's forum replies with
GET /forum/members/:id/replies. - Inputs: Bearer session and
accountId. - Returns / side effects: Parses
forumListSchemaand returns the messages newest-first, capped by the api at 200; reply messages may be payable when the author has a published event and can receive, and may includeparentId. Rows are parsed one by one (forumMessageRowsSchema): a note that failsforumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in oneconsole.warnwithout its content, and the other rows still render; only an invalid envelope fails the list. A 401/404 uses the same visitor-facing message-list failure asfetchMessages; a 409missing_requirementsthrowsMissingRequirementsErroras infetchMember/fetchMessages. - Used by:
MemberProfileScreen.
Function: parseMissingRequirements
- Purpose: Parses a 409
{ error: 'missing_requirements', missing: [...] }body. - Inputs: Unknown JSON body.
- Returns / side effects:
MissingRequirementsErrorornull. - Used by:
fetchMessages,postMessage,postMessageVideo,postContact,fetchMember,fetchMemberPosts,fetchMemberShops,fetchMemberCredits,fetchMemberReplies.
Function: MissingRequirementsError
- Purpose: Typed error for api 409 missing name/rules/username requirements, or the api's
lightning-addresskey, which means the member cannot receive yet (thewalletstep ofnextPostRequirement). - Inputs:
missingarray from the api body. - Returns / side effects: Error instance with
missingfield; not shown as a generic toast. - Used by: Forum and contact loaders (open
RequirementsOverlay) and member fetch.
Function: WrongAccountError
- Purpose: Typed error for api 403 when the visitor signed in with an account whose session is refused.
- Inputs: None; message is the exact api English string.
- Returns / side effects: Error instance named
WrongAccountError. Callers clear the session and showlogin.wrongAccount. - Used by:
fetchMe,finishPasskeyAuthentication,finishPasskeyRegistration,startPasskeyRecovery,finishPasskeyRecovery,useHydrateSession,usePasskeyLogin.
Function: NoteDeletedError
- Purpose: Typed error when a forum reply or a payment invoice gets HTTP 404 because that note is missing or was deleted.
- Inputs: None. The message is exactly
This note was deleted. - Returns / side effects: Error instance named
NoteDeletedError. Reply and pay-sheet callers showforum.errorNoteDeletedinstead of the generic send error. A 404 on the platform compose-target invoice stays the generic request error. - Used by:
postMessage,postMessageInvoice,ForumLoader,PublicMessageThread,MemberProfileScreen.
Function: WalletRequiredError
- Purpose: Typed error for the api's HTTP 400 answer with
codewallet_required(WALLET_REQUIRED_CODE): the action needs the signed-in member's own in-app wallet to be set up first. Recognised by the body'scode, never by status or text; screens show catalog copy. - Inputs: None. The message is
wallet_required. - Returns / side effects: Error instance named
WalletRequiredError. On/pos/amountit shows thepos.needWalletalert. On a forum, member, or public-note gift, paid reply, or posting fee it opens theRequirementsOverlaywalletstep; on/loans/repayit becomes the wallet-unavailable repayment state; in the inbox it shows the wallet-required alert link to/wallet. - Used by:
throwIfWalletAnswer(sopostMessageInvoice,postRepaymentDue,postConversationInvoice, andcreatePosCharge),PosAmount,useLoanRepay,ForumLoader,MemberProfileScreen,PublicMessageThread, andInboxLoader.
Function: CannotReceiveError
- Purpose: Typed error for the api's answer with
codecannot_receive(CANNOT_RECEIVE_CODE; HTTP 400, or 409 on a habit donation): the receiving wallet cannot take this payment. Recognised by the body'scode, never by status or text; screens show catalog copy. - Inputs: None. The message is
cannot_receive. - Returns / side effects: Error instance named
CannotReceiveError. Forum, member, public-note, and inbox pay sheets and the paid-reply composers map it toauthorWallet, and so does the habit pay sheet (MemberHabits);sendHeartTipmaps it toauthor_cannot_receive(forum.payErrorAuthorWalletunder the heart);/loans/repay(useLoanRepay) showsloans.errorCannotReceive;/pos/amountshows Your wallet cannot receive this payment right now. Please try again later. - Used by:
throwIfWalletAnswer,ForumLoader,MemberProfileScreen,PublicMessageThread,InboxLoader,PosAmount,postMemberHabit,MemberHabits,useLoanRepay,sendHeartTip.
Function: CreditClosedError
- Purpose: Keeps an invoice api 409
credit_closeddistinct from missing requirements and generic payment failures. - Inputs: None. The message is
credit_closed. - Returns / side effects: Error instance named
CreditClosedError. Forum, member-profile, and public-message gift flows map it toForumPayError: 'creditClosed', whilesendHeartTipmaps it tocredit_closed; both paths clearly say that the loan no longer collects. - Used by:
postMessageInvoice,ForumLoader,MemberProfileScreen,PublicMessageThread, andsendHeartTip.
Function: throwIfWalletAnswer
- Purpose: Turns the api's wallet answers into typed errors before any other status handling. On HTTP 400 it reads a clone of the JSON body:
codewallet_required(WALLET_REQUIRED_CODE) throwsWalletRequiredError,codecannot_receive(CANNOT_RECEIVE_CODE) throwsCannotReceiveError. Status alone and theerrortext are never used to decide. Any other status, body, or code passes through, and the caller can still read the body. - Inputs: The raw fetch
Response. - Returns / side effects: A promise that resolves when the response is not a wallet answer; rejects with the typed error otherwise.
- Used by:
postMessageInvoice,postRepaymentDue,postConversationInvoice, andcreatePosCharge.
Function: isWrongAccountError
- Purpose: Detects a wrong-account rejection (
WrongAccountErroror anErrorwhose message is exactlyWRONG_ACCOUNT_ERROR). - Inputs:
errorunknown. - Returns / side effects:
truefor that instance or exact message;falseotherwise. - Used by:
useHydrateSession,usePasskeyLogin.
Function: UnknownCredentialError
- Purpose: Typed error for api 400 when authenticate finish rejects a credential the server does not store (
Unknown credential). - Inputs: None; message is the exact api English string.
- Returns / side effects: Error instance named
UnknownCredentialError.usePasskeyLoginmay signal the credential unknown and sets statusunknown.LoginCardshows the unknown login card.ViewProfileClaimshowsview.claimErrorand Try again callsauthenticate(), neverregister. - Used by:
finishPasskeyAuthentication,usePasskeyLogin.
Function: isUnknownCredentialError
- Purpose: Detects an unknown-credential rejection (
UnknownCredentialErroror anErrorwhose message is exactlyUNKNOWN_CREDENTIAL_ERROR). - Inputs:
errorunknown. - Returns / side effects:
truefor that instance or exact message;falseotherwise. - Used by:
usePasskeyLogin.
Function: RecoveryError
- Purpose: Typed rejection of a social recovery request (
startPasskeyRecovery,finishPasskeyRecovery,putRecoveryShare), so the recovery screens choose catalog copy without reading English api text. A kind is recognised by the status together with the body'scodeor exacterror. - Inputs:
kind:not_found(the old wallet holds no account),done(already recovered; sign in with the new passkey),operator(only an operator can recover the account),unavailable(5xx or 429, which can pass),invalid(any other non-2xx),challenge(unknown, expired, or used finish challenge; the account did not move),pending(another recovery is pending), orkey_in_use(the new wallet key is in use; on the share upload, the wallet is not connected or changed). - Returns / side effects: Error named
RecoveryErrorwith a readonlykindand the messagerecovery_<kind>. - Used by:
startPasskeyRecovery,finishPasskeyRecovery,putRecoveryShare, the recovery flow on/recover, anduseSocialRecoverySetup.
Function: RecoveryPendingError
- Purpose: Typed error for the api's HTTP 409 answer with
coderecovery_pendingon authenticate finish: the passkey belongs to a social recovery that is not finished yet. Recognised by that status together with the body'scode, never by text. UnlikeUnknownCredentialError, the authenticator must not be told that this passkey is unknown, or a recovery that still commits would lose its only passkey. - Inputs: None. The message is
recovery_pending. - Returns / side effects: Error instance named
RecoveryPendingError. - Used by:
finishPasskeyAuthentication,usePasskeyLogin, and the recovery flow's sign-in with the new passkey.
Function: nextPostRequirement
- Purpose: Picks the next overlay step before a forum post (
rules, thenname, thenusername, thenwallet). The api'slightning-addresskey means the member cannot receive yet and maps to thewalletstep (the member's own in-app wallet). The api'swalletkey is ignored; it is not a posting overlay field. - Inputs:
missingarray from the account or a 409 body. - Returns / side effects:
'rules','name','username','wallet', ornull. No side effects. - Used by:
ForumLoader,MemberProfileScreen,RequirementsOverlayflow.
Function: nextContactRequirement
- Purpose: Picks the next field to collect before a contact send (
rulesbeforenamebeforeusername). A missing wallet (the api'slightning-addresskey) returnsnull— contact does not open an overlay for it. - Inputs:
missingarray from the account or a 409 body. - Returns / side effects:
'rules','name','username', ornull. No side effects. - Used by:
ContactLoader,RequirementsOverlayflow.
Function: RequirementsOverlay
- Purpose: Modal to add a missing name (
NameFormprofile), username (UsernameForm), or agree to rules before retrying a post. No Skip. Thewalletstep has the title Your wallet is not set up and explains Gifts and posts need your own 21.gifts wallet, and it is not set up yet. Open your wallet to set it up., with a labeledButtonLinkOpen your wallet (requirements.walletOpen) to/walletand no form: wallet setup runs in the background after the member supplies the phrase through a money action; it is not a field in this overlay. - Inputs:
requirement(name|username|rules|wallet),onDismiss,onSatisfied. - Returns / side effects: Dialog UI; merges account fields on success then calls
onSatisfied. Title/aria-labelfromrequirements.nameTitle,requirements.usernameTitle,requirements.rulesTitle, orrequirements.walletTitle. Thewalletstep showsrequirements.walletBodyand a labeledButtonLinkOpen your wallet (requirements.walletOpen) to/wallet; it has no form. - Used by:
ForumLoader,ContactLoader,MemberProfileScreen,PublicMessageThread.
Function: WalletTour
- Purpose: One-time spotlight tour on the forum home (
/welcome) that explains that the app is now the wallet. It highlights the real elements in place and never navigates: 1 the header balance ([data-wallet-tour="balance"],walletTour.balanceTitle21.gifts is now your wallet /walletTour.balanceBody), 2 Receive ([data-wallet-tour="receive"],walletTour.receiveTitle/walletTour.receiveBody), 3 Send ([data-wallet-tour="send"],walletTour.sendTitle/walletTour.sendBody), 4 Menu (#signed-in-menu-button,walletTour.menuTitleEverything else /walletTour.menuBody). No final card after step 4. The copy never mentions the recovery phrase. - Inputs:
blocked(true while a wallet view or the writer is open over the forum, or while the page has folded Receive / Send away, so a folded button is never highlighted). Readssessionandaccount.walletIntroSeenfromuseAuthStoreanduseWallet().status. - Returns / side effects: Shown only while there is a session,
walletIntroSeen === false(a missing field from an older api counts as seen), the wallet is no longerconnecting(so the balance step is not lost to a wallet that is still opening),blockedis false, and no otheraria-modal="true"dialog (the introduce overlay, the requirements overlay, a pay or link warning) the move-funds sheet (data-move-funds), and no open Menu (aria-expanded="true"on the Menu button) is up; it waits behind those and starts or resumes once they are gone. The steps are the ones whose target is on screen (a box with width and height that overlaps the window) when the tour starts; a target that is gone by its turn is skipped, and when none is left the tour ends as if finished. The measured box belongs to the step it was measured for, sowallet_tour_stepis recorded only once a step's own target was measured: a step skipped because its target is gone is never recorded as shown. Afixed inset-0 z-[95]layer takes every click; inside it anaria-hiddenring box (fixed rounded-2xl ring-2 ring-white, ashadow-[0_0_0_9999px_rgb(0_0_0/0.62)]spread darkening the rest of the window,transition-all duration-300) sits 8 px around the target, clamped to the window; itsstylesets only the measuredtop,bottom,left, andwidth(the fixed-overlay exception). The card (role="dialog"aria-modal="true"data-wallet-tour-card, labelled by its title and described by its text,fixed inset-x-3 mx-auto max-w-sm rounded-2xl bg-app-card p-4 shadow-xl) sits 12 px under the ring when the target's centre is in the upper half of the window, otherwise 12 px above it (styletoporbottomonly). It shows N of M (walletTour.progress,text-[11px]muted uppercase; M is the number of steps found at the start, normally 4), the title (h2,text-base font-semibold), the text (text-sm text-app-muted), Skip (walletTour.skip, an underlined muted text button) and a primaryButton size="sm"Next (walletTour.next), on the last step Got it (walletTour.done), which takes the focus on every step. Escape skips. The box is measured again onresize, on anyscroll(capture), and on every change of the page (MutationObserverondocument.body). Skip, Escape, and Got it setwalletIntroSeen: trueon the stored account at once, so the tour never comes back in this session even when the request fails, and callmarkWalletIntroSeen(a failure is ignored). - Used by:
WelcomeScreen.
Function: IntroduceYourselfOverlay
- Purpose: Modal on the forum home (
/welcome) that tells a signed-in member whose onboarding is complete (setup === null) and who has not posted (hasPosted === false) to introduce themselves in the forum.SignedInChromemounts it on/welcomeonly, so it never covers/wallet,/wallet/*, the point of sale, the profile, messages, or the setup flow. Close (X) dismisses this mount only. Primary CTA Write an introduction is aButtonthat dismisses, opens the forum home writer and focuses its text field (requestForumCompose/FORUM_COMPOSE_EVENT); it does not navigate. No Skip-forever. Hidden whenhasPostedis true or omitted (older api) and whilesetupis not null. - Inputs:
onDismiss. - Returns / side effects: Dialog UI (
role="dialog"aria-modal="true", fixed inset cardz-50). Title/aria-labelfromintroduce.title; bodyintroduce.body; CTAintroduce.ctaas catalogButtontype="button"size="lg"; closeintroduce.close. Does not writeforumLawsDismissedor any account field. - Used by:
SignedInChrome.
Function: SocialRecoveryPromptOverlay
- Purpose: Modal on the forum home (
/welcome) that tells a grant member (fundingadmitted, ortrialfor today) whose account has no Social Recovery yet (socialRecoverySetUp === false) to set it up, and names the day from which grant payouts require it.SignedInChromemounts it on/welcomeonly, after Introduce yourself: once that dialog is closed, by its Close or by Write an introduction (which also opens the writer under this one), it shows in the same visit; its own Close hides it until the next visit; the date sits in the copy and is not checked. - Inputs:
onDismiss. - Returns / side effects: Dialog UI with the introduce anatomy (
role="dialog"aria-modal="true", fixed scriminset-0 z-50 bg-app-overlay,Card maxWidth="sm"). Title andaria-labelsocialRecoveryPrompt.title; an icon-only ghost closeX(socialRecoveryPrompt.close) callsonDismiss; bodysocialRecoveryPrompt.body; a labeledButton size="lg"Secure my account (socialRecovery.secure) callsonDismissandrouter.push('/settings/social-recovery'), without a document load. Writes nothing. - Used by:
SignedInChrome.
Function: ReceivedNotice
- Purpose: In-app banner for a received payment that completed while the app is open, so the member sees the money arrive without opening the wallet. Never for a payment the wallet already held when it connected (see
onIncomingPayment). No system or push notification. - Inputs: None. Reads
useIncomingPayment(6000),useNumberFormat, anduseSpotRate(only while a payment is showing). - Returns / side effects:
nullwithout a payment. Otherwise a portal todocument.body: apointer-events-none fixed inset-x-0 top-3 z-[90]row centring amax-w-smcard (role="status",animate-slide-downfrom the top,rounded-2xl border border-app-success/40 bg-app-card shadow-lg) with lucideArrowDownLeftin anh-9 w-9bg-app-success/15 text-app-successcircle, then You received ₿500 (wallet.receivedNotice,text-sm font-semibold). A received payment has no stored fiat figure, so a muted line under the bitcoin shows the current spot, and that line is left out only when the spot is not loaded. That text is onenext/linkto/walletthat also closes the banner. An icon-only ghostIconButtonX(wallet.receivedClose, Close) closes it. It closes itself after 6 s; a newer payment replaces it and starts the 6 s again. Under the Playwright-only?visual=wallet-receivedpin a fixed ₿500 payment arrives on mount and is held like a real one. - Used by:
SignedInChrome.
Function: MoveFundsBack
- Purpose: Registers the top-left arrow as the move-funds flow's one step back while the flow is open, laid over the page's own steps, so the sheet needs no Back button of its own (CONTRIBUTING "One back").
- Inputs:
onBack— the flow's step back (3 → 2 → 1; closes the flow on steps 1 and 4). - Returns / side effects:
null. On mount it callsuseChromeBack().setOverridewithlabelKeynav.back,over: true, and anonClickthat calls the latestonBack(kept in a ref, so a new callback does not register again); on unmount it clears the override. - Used by:
MoveFundsSheet.
Function: MoveFundsSheet
- Purpose: Guided move of the member's Bitcoin from another wallet into the in-app wallet. Only copy and QR: no other wallet app is named, linked, or opened, and there is no
lightning:link. - Inputs: Optional
onOpenChange(open), told whether the sheet is open (andfalseon unmount), soSignedInChromecan take the Menu out of reach behind it. Readsaccount.usernamefromuseAuthStore,useWallet(the balance on the last step),useSpotRate(asked while open),useFiatPreference,useNumberFormat,useCopied, and the user agent (isSmartphoneUserAgent, never the viewport width). - Returns / side effects:
nullwhile closed. It opens whentakeMoveFundsRequestfinds a request, on mount and onMOVE_FUNDS_EVENT(a?move=1link throughMoveFundsLink, also one followed before signing in, or the Receive view's Move Bitcoin from another wallet), and then removesmovefrom the address withhistory.replaceState. It takes a request only while signed in, done with onboarding (nextOnboardingPathis/welcome), and with a username; until then the request stays stored, so a link opened before signing in or during onboarding opens the flow afterwards. A sign-out (signed in, then signed out while this sheet is mounted) takes and drops a request still waiting, so a request followed during one member's onboarding never opens for the next member who signs in in this tab; a visitor's request from before any sign-in still waits. Open, it is anAppShellOverlayover the page body under the header row (absolute inset-0 z-[95] bg-app-overlay) holding arole="dialog"sheet labelled by its step title (data-move-funds,max-w-md rounded-t-3xl bg-app-card p-5 shadow-xl, from the bottom on a phone andsm:rounded-3xlcentred on a wider frame): four progress dots (aria-hidden, with ansr-onlyStep N of 4,moveFunds.progress) and an icon-only ghostX(moveFunds.close, Close). Steps: 1 Bring your Bitcoin here (moveFunds.introTitle), the textmoveFunds.introBody, three numbered lines (moveFunds.introStep1–3), and Start; 2 Send to your 21.gifts address with the member's own address (giftsLightningAddress, as on Receive), on a desktop user agent also Open your other wallet on your phone, tap Send and scan this code (moveFunds.scanHint) over the same address QR as Receive (openCryptoPayQrValue,profileQrLogo), a secondary Copy my address (moveFunds.copy; Copied for two seconds), and I sent it; 3 a spinner with Waiting for your Bitcoin… (role="status") and Finish sending in your other wallet. This screen updates by itself.; 4 a success check, ₿X arrived (role="status") with the spot fiat under the bitcoin (bitcoin alone only without a rate), Your wallet now holds ₿Y · fiat. (the fiat left out only without a rate; the sentence left out while the balance is unknown) and Something left over there? You can do this again any time from Receive., then Done. Steps 2 and 3 move to step 4 by themselves when a received payment completes (onIncomingPayment). While open it registers the top-left arrow (nav.back,over) throughMoveFundsBackas its one step back: 3 → 2 → 1, and it closes the flow on steps 1 and 4; there is no Back button in the sheet. Escape and Done close it. Log out closes an open flow before step 4 too and recordswallet_move_closedwith that step under the ending session (LOGOUT_EVENT, sent bylogLogoutbefore the session is cleared). Under the Playwright-only?visual=move-arrivedpin it opens on step 4 with ₿500. - Used by:
SignedInChrome.
Function: keepTabInside
- Purpose: Keeps Tab and Shift+Tab inside an open modal panel so keyboard focus cannot reach the inert page behind it.
- Inputs:
event, the TabKeyboardEvent; andpanel, the modal dialogHTMLElement. - Returns / side effects:
void. Finds the panel's enabled links, buttons, inputs, selects, textareas, and non-negative-tabindex elements. Tab on the last control moves focus to the first; Shift+Tab on the first control or the panel moves it to the last; focus outside the panel moves to its first control. With no reachable control, the panel keeps focus. Wrapped moves prevent the default key action and do not scroll. - Used by:
LoanPayMoreandPaySheet.
Function: PaySheet
- Purpose: The bottom sheet that holds the last tap of every payment from the in-app wallet in the forum and the inbox: what is paid to whom, the amount, and the pay slot. Where the amount is chosen stays on the page; the sheet opens only once the invoice exists. It holds no reaction text, no loan notice, and no invoice QR.
src/components/PaySheet.tsxalso holdsPAY_SHEET_SUCCESS_MS(1400 ms) andPAY_SHEET_HOLD_MS(PAY_SHEET_SUCCESS_MSplusMOTION_FOLD_MS, 1720 ms). - Inputs:
title(Send to {name}, Lend to {name} on a loan that still collects, Pay to post for the posting fee, Send when no name is known),amountSats,rateDay(the current spot rate, ornull),successTitle(Sent to {name}, Lent to {name}, Paid and posted, or Sent),onClose(the member left the payment), optionalonSentChange(told whether the pay slot has a payment out or on its way, forusePaySheetHold), optionalstored(the fiat stored with the amount; a figure for the visitor's currency is shown as-is, and a missing figure uses the current spot), and the pay slot as children. ReadsuseTranslations,useNumberFormat,useFiatPreference,usePresent(whether the host'sCollapsestill shows it), and the flag of an enclosingPaySheetFailed. - Returns / side effects: An
AppShellOverlaylayer over the frame body under the header row (absolute inset-0 z-[95],data-pay-sheet-layeropenorclosed): a dimmed scrim (bg-app-overlay, abuttonwithforum.payClosethat is not in the tab order) and arole="dialog"aria-modalpanel labelled by the title (data-pay-sheetpayorsuccess,max-w-md rounded-t-3xl border-t bg-app-card px-5 pt-2 pb-6 shadow-xl, from the bottom on a phone andsm:rounded-3xl sm:bordercentred on a wider frame). The panel shows a decorative handle, the title (h2, centred) with the icon-only ghostX(forum.payClose, Close) on its right, the amount (formatBitcoin,text-4xl font-semibold) with one fiat figure under it (a stored figure for the visitor's currency as-is, otherwiseformatFiatDisplayof the current spot; left out only when neither exists), and the pay slot. It takes the focus when it mounts, keeps Tab and Shift+Tab inside the panel while it is shown (focus that is outside moves to its first control; with no control the panel keeps it), and slides up on the next frame (translate-y-fulltotranslate-y-0, the scrim fading in; 280 msease-glide; on a wide frame a short rise with a fade). Close, a tap on the scrim, and Escape callonCloseonce and slide the sheet away at once. The Escape and Tab listener is attached in a layout effect, so it works from the first frame the sheet is on screen. A leaving sheet isinertwhile its host still holds it, and the focus goes back to what had it before the sheet opened, when that is still on the page. A host renders it inside aCollapsewithholdMsPAY_SHEET_HOLD_MS; when that fold closes without such a close (usePresentturns false) while the pay slot reports a send that went out (usePaySheetSentpaid), the pay step fades into the success step (Swap;role="status": a greenCircleCheck,successTitle, and the amount with its fiat), which stays untilPAY_SHEET_SUCCESS_MSafter the close, then the sheet slides away; Escape, a tap on the scrim or Close lets it go at once without callingonCloseagain. A send stillpendingat that close keeps the pay step until the wallet answers: once it went out the success step follows, otherwise the sheet slides away; either way it is gonePAY_SHEET_SUCCESS_MSafter the close. A host close with no send out (a failed check, another thread), or one underPaySheetFailed(a paid post that failed), slides the sheet away at once, without that step. Outside a fold it never shows that step. With reduced motion nothing slides or fades; the success step still shows. No network. - Used by:
ForumPaySheet(forum and habit comment gifts, the posting fee),ForumReplyPayPage(money reactions), andInboxScreen.
Function: usePaySheetClose
- Purpose: Gives a control inside a
PaySheetthe sheet's own close, for an action that leaves the payment, such as the pay slot's Add Bitcoin. - Inputs: None; reads the nearest
PaySheet. - Returns / side effects: The sheet's close (it calls the sheet's
onCloseand slides it away without a success step, because the member left the payment), ornulloutside a pay sheet. - Used by:
AddBitcoinButton.
Function: usePaySheetSent
- Purpose: Lets the pay slot tell the
PaySheetaround it where its wallet send stands, so only a payment that went out ends in the success step. - Inputs: None; reads the nearest
PaySheet. - Returns / side effects: The sheet's report (
(sent: 'pending' | 'paid' | null) => void;WalletPaypassesuseWalletPay'ssent), ornulloutside a pay sheet. When the host then closes the payment, apaidsend shows the success step; apendingone keeps the pay step until the wallet answers, then shows the success step if it went out and slides the sheet away otherwise; with no send the sheet slides away at once. - Used by:
WalletPay.
Function: PaySheetFailed
- Purpose: Tells the pay sheets inside that the host closed the payment because what it paid for failed after the payment went out (the post behind a paid posting fee could not be sent), so the sheet does not claim Paid and posted.
- Inputs:
failed(true from that close until the host opens the next payment) andchildren(the content with the hosts). It sits outside the hosts'Collapse, so it still reaches a sheet the fold holds. - Returns / side effects: The content with the flag in context. A
PaySheetthat the host closes while the flag is set slides away like a cancel, with no success step, even with a payment out; the page shows the error. - Used by:
ForumLoader(aroundForumBoard; set when the post after a paid posting fee fails, cleared when the next invoice opens).
Function: usePaySheetHold
- Purpose: Keeps the page controls behind a pay sheet disabled through its success step, for a host whose form sits beside the held sheet rather than inside its
Collapse(the forum reaction form, the inbox amount row). - Inputs:
openKey, the key of the payment whose sheet is open, ornull. - Returns / side effects:
{ held, closedByMember, sentChange }. The host passessentChangeto the sheet asonSentChangewith the key of the payment that sheet shows ((sent) => sentChange(key, sent)); a report counts only for its own payment, so a sheet still held for one payment never frees or holds the next one. When the open payment closes with a payment out or on its way (apaidorpendingsend) and without the member closing it,heldis its key forPAY_SHEET_SUCCESS_MS, thennull; the next payment frees it at once, and so does a pending send that then does not go out (sentChange(key, false)).closedByMember(), called before the host cancels a payment the member closed, makes that close hold nothing, and so does a close with no payment out (a failed check). A timer only; no network. - Used by:
ForumBoard(the reaction form besideForumReplyPayPage, keyed by the card) andInboxScreen(the amount row, keyed by the invoice'spr).
Function: AddBitcoinButton
- Purpose: Add Bitcoin (
paySheet.addBitcoin) of the pay slot when the balance is too low: the way to add money instead of an address or a QR in the sheet. - Inputs: None; reads
usePaySheetClose, the nearestOpenReceiveProvider, anduseRouter. - Returns / side effects: A full-width
Button variant="secondary" size="lg". A tap closes the pay sheet around it (a cancel, no success step), then opens the wallet's Receive view: the page's own one under anOpenReceiveProviderwith an opener (the forum home), otherwiserouter.push('/wallet?receive=1')(client-side, no document load). No network of its own. - Used by:
WalletPay.
Function: OpenReceiveProvider
- Purpose: Gives the controls inside a page the page's own Receive view, so Add Bitcoin in a pay sheet opens Receive over the forum home instead of leaving it.
- Inputs:
onOpen(the page's Receive opener, ornullwhile the page has no wallet view) and the page. - Returns / side effects: The page under that opener. No network.
- Used by:
WelcomeScreen(itsuseWalletPanelReceive, after closing an open writer;nullwhile the member has no wallet).
Function: useReceiveLink
- Purpose: Opens the Receive view once when
/walletwas opened with?receive=1(from Add Bitcoin on a page without its own Receive view). - Inputs: The page's Receive opener.
- Returns / side effects: On mount, when the address has
receive=1, removesreceivefrom it withhistory.replaceState(keeping the other parameters, the hash, and the history state), then calls the opener once. Otherwise nothing. No network. - Used by:
WalletScreenView.
Function: MemberProfileLoader
- Purpose: Client loader for
/members/[accountId]: UUID check,fetchMember, thenfetchMemberActivityeven when the member has no wallet yet. It does not prefetch post/reply/shop/credit feeds;postCount,replyCount, optionalshopCount, and optionalcreditCountarrive with the profile JSON. Maps gift and loan series onto the screen; missing loan fields become empty series and saldo 0. - Inputs: Route
accountId; session from auth store. - Returns / side effects: Loading / missing (
view.missing) / error+retry /MemberProfileScreen.fetchMember409missing_requirements→/setup/rules(returnToView).fetchMemberActivity409missing_requirements→/setup/rules(returnToView). Any other activity error (other thanMissingRequirementsError) keeps the card and both charts show their error copy (profile.chartError/profile.loanChartError).MissingRequirementsErrorstill goes to/setup/rules. - Used by:
MemberProfilePage.
Function: MemberProfileScreen
- Purpose: Signed-in member identity card (gift chart from given and received activity, then
LoanBalanceChartdirectly under it with the sameactivityFailedflag, About me inside the card not as a forum post (Translate, Languages icon, whenprofileMessage.idoraboutMessageIdis set), name, location, publicusername@21.gifts(profile.giftsHeading), role pill, optional funding-program icon-only button (pressing it reveals that one sentence; that result is the separate screenshot statefunding-program-open) whenfundingReviewedAtis a number, copy-profile-link, and post/reaction count toggles) plus stackedForumBoardactivity feeds loaded on demand. Location is read-only on someone else's card (location.unsetwhen empty). When the signed-in account id matches, the owner edits the centered name and location. The owner About me editor passesomitEmptySlotAddsandimageEpoch, so empty profile-photo and wide-image adds stay on the header and a header save reloads those slots while the editor stays open. PublicAboutMeSection(name={profile.name}) shows filled text and/or photo, or omits the heading when neither. A labeled MessageButton(profile.message) with a decorative Mail icon sits on the card when another member has aprofileMessage— not on a post. Staff Trust Chain actions sit behind the closed Moderator functions disclosure when the viewer is a moderator and the subject is someone else. Clicking a count opens its feed below the card; clicking it again collapses it. There is no separately pinned profile-noteForumBoard; the posts feed lists that note when present. A feed shorter than its profile count gets a mutedprofile.activityLatesttruncation line. Posts show React and do not show Send Bitcoin; a payable reply card in the replies feed shows Gift (disabled withCannotReceiveLabelwhen its author cannot receive yet). Nested Gift Continue looks up sats on the visible feed only (reactions-feed cards when activity is replies; expanded-thread replies otherwise). Collapsing or switching Posts/Reactions cancels a Gift whose target is in the expanded thread or the reactions feed; a parent composer invoice stays. Expanding a reply withparentIdnavigates to/messages/{parentId}. Verified members mayPOST /messagesunpaid only when there is text and the amount is empty; empty text and an empty amount invoices 21 sats even for verified (except toward an author who cannot receive yet: then it showsforum.errorEmptyand invoices nothing); everyone else invoices ≥ 1 sat with optional text; typed0is always billed as 1 sat even for exempt. When a note omitsaccountId, a text reply with an empty amount tries unpaidPOST /messages; a payment 403 starts a 1-sat compose invoice to 21.gifts on the composer slot (payHost: composer,payMessageId= compose-target note). Extra gifts and Gift-open stay on the card (payHost: card). Posts, replies, shops, and credits useforumPhotoSrc. About me /loadPhotostaysfetchMessagePhoto(andfetchPublicMessagePhotowhen signed out). ForumBoard does not paint photos on nested replies. LoadsrateDayviauseSpotRate(failure leavesnull) and passes it to everyForumBoardso unsent previews can use the current spot rate; feed ₿ amounts show optional preferred-fiat·from the amount stored when the payment was made (a stored string as-is, a null or missing field on a passedstoredobject shows the current spot, and stays off the line only when that spot is not loaded) (no FiatPicker on the chart or the feed; member profiles are always signed-in). UsesnextPostRequirementso a missing name, username, wallet, or rules agreement opensRequirementsOverlay(no Skip) before a reply retries. When a username is set, a centeredQrCode(labelprofile.giftsQr) under the address encodesopenCryptoPayQrValue(https://<domain>/pl/?lightning=plus the uppercase LNURL ofhttps://<domain>/.well-known/lnurlp/<local>), including on a smartphone. A missing username shows no QR. Without a receiving address (lightningAddress: null), Can't receive yet replaces the address, the QR, and Shop sticker. When a username is set and the member can receive, a labeled Shop stickerButtonunder the QR opensShopStickerOverlaywith the sameopenCryptoPayQrValueand the public handle, including on a smartphone; Close and Escape unmount it. On the full member view, an own credit uses theForumBoardPay early or end collecting link while open below goal, otherwise Repay your loan; both open/loans/repay; the post itself has no repayment payment state. - Shop activity:
profile.shopCountappears after reactions only when optionalshopCount > 0and loads the member shops feed on demand. It follows the posts feed behavior: top-level in-feed expansion, photos, truncation notice, empty state, shared pay/expand state, and moderator shop-note editing; edits update the shops list. Shop notes remain in the posts feed too. - Credit activity:
profile.creditCountappears after shops only when optionalcreditCount > 0and loads an on-demandForumBoardfromGET /forum/members/:id/credits. It follows the posts feed, including top-level expansion, photos, truncation notice, empty state, and shared pay/expand state. This feed does not passshopNoteEdit. Credit notes remain in Posts. Credits are not prefetched. - Inputs:
MemberProfile(includesaboutMe,aboutMeHasPhoto, andlocation) plus received, donated, owed, and credit series (loan series default[]); optionalfactsOnly(default false); optionalomitPills(default false;/profiledoes not pass it); optionalloadPublicListfor the share link's public posts, replies, shops, and credits; optionalloadAboutPhotofor that link whenaboutMeHasPhotois true and the profile note has no id (fetchViewAboutMePhoto); optionalactivityFailed(default false), passed to both charts asfailed; session/account from the auth store. The full card loads publicGET /pictures/:idandGET /banners/:id(no bearer).factsOnlydoes not. PublicAboutMeSectionhasPhotofromaboutMeHasPhoto/profileMessage.hasPhotowithloadPhoto(fetchMessagePhoto, andfetchPublicMessagePhotowhen signed out). Public Translate usesprofileMessage.id, oraboutMessageIdwhen the share link has no profile note. OptionalshareViewKeyis the/view/:viewKeyroute key: when it is set, the copy button writes${origin}/view/${shareViewKey}and does not use the owner view key or the short/l/link. - Returns / side effects: React tree. A stored public profile photo and wide image sit above the heading; a missing slot draws nothing. With About me, copy-profile-link, optional Message, staff Trust Chain actions, and a location row on the card (read-only for someone else; the owner edits it when the account id matches); lazily fetches the selected member posts or replies; loads
GET /fx/spotintorateDayviauseSpotRate; posts, replies, shops, and credits useforumPhotoSrc; About me stays afetchMessagePhotoblob (andfetchPublicMessagePhotowhen signed out); mayPOSTgift or posting-fee invoices, conversations, and replies and navigate to/messages?c=or a reply's/messages/{parentId}. WhenactivityFailedis true and a series is empty, that chart shows its error copy.factsOnlystill has no charts.factsOnlyreturns only the role pill, the funding-program icon, the gifts address, QR, Shop sticker, count buttons, the activity feed, andRequirementsOverlay— no heading, charts, About me, name, location, Message, or staff block./profile,/members/:id, and/view/:viewKeyeach render this screen once. Owner edits appear when the signed-in account id matches the profile. AWalletRequiredError(apicodewallet_required) on a gift, a paid reply, or a posting fee opens theRequirementsOverlaywalletstep. A paid reaction keeps its text and amount in the disabled form behind the reaction pay sheet (replyPayPreviewonForumBoard); both clear once the payment is seen, and a cancel leaves them in the form. While that sheet is open, the card does not expand or collapse (and on the profile the activity feeds do not switch), as on the forum home. Gift and posting-fee invoices keep the api'ssparkInvoiceso the wallet pays it before the payment request. A reply to the viewer's own note (isOwnNote, as on/profile) has no Amount field and posts unpaid; an empty one setsempty. AMissingRequirementsErrorwhile loading a feed goes to/setup/ruleswithreturnToView. Without a receiving address (lightningAddress: null), Can't receive yet (CannotReceiveLabel) replaces the address, the QR, and the Shop sticker. A reply to a feed note whose author cannot receive yet (authorCannotReceive) never invoices a gift to the author: an empty one setsempty, and one with text posts unpaid or pays only the 1 sat posting fee. - Used by:
MemberProfileLoader,ProfileScreen, andViewProfileLoader.ProfileScreenrenders this screen once and does not passfactsOnly.
Function: MemberProfilePage
- Purpose: Route
/members/[accountId]with profile onboarding gate and signed-in chrome. - Inputs: Dynamic
accountId. - Returns / side effects:
AppShellwithProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGatearoundMemberProfileLoader. - Used by: App Router.
Function: proxyMeSetupSkipPost
- Purpose: Proxies
POST /me/setup/skipto the api. - Inputs: App Router request (Bearer +
{ step }). - Returns / side effects: Upstream response.
- Used by:
/me/setup/skiproute.
Function: proxyMembersGet
- Purpose: Proxies
GET /members/:accountIdto the api. - Inputs: App Router request and
accountId. - Returns / side effects: Upstream response via
/members/${encodeURIComponent(accountId)}. - Used by:
/forum/members/[accountId]route.
Function: proxyMembersPostsGet
- Purpose: Proxies
GET /members/:accountId/poststo the api. - Inputs: App Router request and
accountId. - Returns / side effects: Upstream response via
/members/${encodeURIComponent(accountId)}/posts. - Used by:
/forum/members/[accountId]/postsroute.
Function: proxyMembersShopsGet
- Purpose: Proxies
GET /members/:accountId/shopsto the api. - Inputs: App Router request and
accountId. - Returns / side effects: Upstream response via
/members/${encodeURIComponent(accountId)}/shops. - Used by:
/forum/members/[accountId]/shopsroute.
Function: proxyMembersCreditsGet
- Purpose: Proxies
GET /members/:accountId/creditsto the api. - Inputs: App Router request and
accountId. - Returns / side effects: Upstream response via
/members/${encodeURIComponent(accountId)}/credits. - Used by:
/forum/members/[accountId]/creditsroute.
Function: proxyMembersRepliesGet
- Purpose: Proxies
GET /members/:accountId/repliesto the api. - Inputs: App Router request and
accountId. - Returns / side effects: Upstream response via
/members/${encodeURIComponent(accountId)}/replies. - Used by:
/forum/members/[accountId]/repliesroute.
Function: useHydrateSession
- Purpose: Rehydrates a persisted session token, but does not count it as signed in when its eligible wallet phrase is missing from this tab.
- Inputs: Reads
loadSession, callsfetchMe, and evaluateshydratesLocked(account). - Returns / side effects:
{ ready }. A valid account whose wallet is already open, or to which the wallet gate does not apply, goes throughsetAuth; otherwisesetLockedSessionkeeps the stored token (and the account's name or username aslockedName, for the login card's greeting) while leaving activesessionandaccountnull.WrongAccountErrorcallsclearAuthandsetWrongAccount(true)then becomes ready so the stale token is not left. Generic/mefailures log and do not set the flag.readyis false until storage//mehas settled so gated screens do not redirect early. Unmount invalidates in-flight work. - Used by:
OnboardingGate.
Function: QrCode
- Purpose: SVG QR for a string (LNURL or bolt11). Optional
logocenters that image at 48px and sets error correctionH; profile cards passprofileQrLogo, the inlined apple-touch icon. - Inputs:
value(required) andlabel(required accessible name, already translated). Optionallogo. - Returns / side effects: React element.
- Used by:
PayLinkScreenshows an invoice QR only when the user agent is not a smartphone.PosTill,ShopScreen,MemberProfileScreen,ViewProfileScreen,WalletReceive, andWalletOwnAddressrender this QR when the value exists, including on a smartphone.FondDepositrenders the Fond wallet's on-chain deposit address as abitcoin:QR on every device (the documented Fond exception in CONTRIBUTING "Payment QR vs wallet links").MoveFundsSheetrenders the same address QR only off a smartphone.HeldSharesScreenshows a kept share's code on/settings/held-shares, andSocialRecoveryScreenshows the codes for person 1 and person 2 on/settings/social-recovery; those codes are not payment QRs. Member pay sheets (ForumPaySheet,ForumReplyPayPage,InboxScreen) do not render this component.
Function: QrScanner
- Purpose: Live camera QR reader for the wallet Send view (on
/walletand over/welcome) and for keeping a share on/settings/held-shares. Asks once per mount for the camera, rear camera preferred (facingMode: { ideal: 'environment' }, no audio), and fills its positioned parent (absolute inset-0, black,[container-type:size]), whichWalletSendmakes the whole visible page port. The picture covers it (object-cover) under a centred viewfinder square of 68% of the smaller side (white border with corner marks, the rest dimmed; it does not take taps), and the hint sits in large white type over the top of the picture on afrom-black/80gradient: by default Point the camera at a Bitcoin QR code, or the hint key incopy. The viewfinder only shows where to aim: every frame is read whole. Reads about eight frames a second: with the browser'sBarcodeDetectorwhen it listsqr_codeamong its formats, otherwise withjsqron a canvas copy at most 640 pixels on its long edge. A single frame that cannot be decoded is skipped and scanning continues. The first non-blank text stops every camera track and is reported. A blocked camera (NotAllowedError,SecurityError) shows, by default, Camera access was blocked. Allow it in your browser settings, or paste the payment request. (copy.deniedotherwise) in large white type on the black area, a third of the way down, so the floating buttons below stay where they are; no camera, any other failure of the camera request, a page without a secure context, a browser without media devices, or a QR decoder that cannot load (the camera is stopped then) shows, by default, No camera found. Paste the payment request instead. (copy.unavailableotherwise). Both arerole="alert", and the hint line is hidden then. Unmounting stops the tracks and the frame loop, and a stream or frame result that arrives after unmount is stopped or dropped. - Inputs: Optional
onPicture(picture), called withshowingwhen the preview plays while the camera delivers pictures, or the picture comes back,deniedorunavailablewhen the alert replaces the preview, orpausedwhen the preview did not start or stopped (paused or ended), or the camera track is muted or ended. No alert is shown in that case. The latest callback is used.onResult(text), called once with the first QR text, after the camera has stopped. The latest callback is used. Optionalcopy(QrScannerCopy: catalog keyshint,denied,unavailable, and optionalhintVars, the placeholder values ofhint) for a scan that is not a payment; the default is the wallet Send wording (wallet.scanHint,wallet.cameraDenied,wallet.cameraUnavailable). - Returns / side effects: A region named by the hint, holding the preview or the alert. Requests camera access; never stores or sends a frame.
- Used by:
WalletSend(input step, default wording),HeldSharesScreen(the camera of Keep a share, with theheldShares.*wording), andOldWordsInput(two share codes on/recoverand/settings/previous-wallets/[sparkPubkey], with Scan code {n} of 2 and therecover.*camera wording).
Function: RootLayout
- Purpose: Root HTML shell for every route. Negotiated
lang(en/de/es/fil), global CSS, English metadata (title, icons, Open Graph, Twitter), blockingAPP_HEIGHT_BOOTSTRAP_SCRIPTthenTHEME_BOOTSTRAP_SCRIPTin<head>,suppressHydrationWarningon<html>, token body classes (bg-app-bg text-app-fg), andAppHeightSync. Nest is Locale → NumberFormat → FiatPreference → Theme. InsideThemeProvider:AccountPreferenceSync,LocaleRouteSync,PushOpenListener,WalletSync,FondPayoutSync,FondDepositSync,InteractionLog,RememberWalletReturninSuspense,MoveFundsLinkinSuspense, thenViewHistoryRootaround the page children. - Inputs:
childrenReact nodes. CallsgetRequestLocale()forhtml langand messages,getRequestNumberFormat()for the number-format provider,getRequestFiat(locale)for the fiat provider, reads thex-noncerequest header thatmiddlewaresets. - Returns / side effects: The document wrapper for every route. The three inline bootstrap scripts (
APP_HEIGHT_BOOTSTRAP_SCRIPT,THEME_BOOTSTRAP_SCRIPT,SUNDAY_BOOTSTRAP_SCRIPT) carry the Content-Security-Policy nonce; the JSON-LD data block needs none. - Used by: All screens.
Function: clearSession
- Purpose: Removes the bearer token from
localStorage. - Inputs: None.
- Returns / side effects: void. No-op during SSR (
windowundefined). - Used by:
useAuthStore.clearAuth.
Function: fetchTrustChain
- Purpose: GET
/trust/graph(same-origin proxy of apiGET /trust-chain) with Bearer and parse the Trust Chain graph. Optionalaroundloads one hop (?around=). - Inputs: Bearer
sessionToken, optionalaroundaccount id. - Returns / side effects:
TrustChain. Throws visitor copy when the api is down, the body is invalid, or the response is 401/403. - Used by:
TrustChainLoader.
Function: postTrustVerify
- Purpose: POST
/trust/verifywith{ accountId, confirmedName }so a moderator verifies a basis member. - Inputs: Bearer
sessionToken, subjectaccountId,confirmedName. - Returns / side effects:
{ id, name, role }. Throws visitor copy on any failure. - Used by:
MemberVerifyScreen.
Function: postTrustPropose
- Purpose: POST
/trust/propose-moderatorwith{ accountId }. - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
{ id, name, role }. Throws visitor copy on any failure. - Used by:
MemberTrustActions.
Function: postTrustConfirm
- Purpose: POST
/trust/confirm-moderatorwith{ accountId }(caller must not be the proposer). - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
{ id, name, role }. Throws visitor copy on any failure. - Used by:
MemberTrustActions,ProposalsScreen.
Function: postTrustReject
- Purpose: POST
/trust/reject-moderatorwith{ accountId }. - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
{ id, name, role }. Throws visitor copy on any failure. - Used by:
ProposalsScreen.
Function: postTrustAppoint
- Purpose: POST
/trust/appoint-moderatorwith{ accountId }(founder only). - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
{ id, name, role }. Throws visitor copy on any failure. - Used by:
MemberTrustActions.
Function: fetchTrustProposals
- Purpose: GET
/trust/proposals(same-origin Bearer proxy of apiGET /trust/proposals) and parsemoderatorProposalsResponseSchema.proposals. Next.js forbids aroute.tsbeside/moderate/proposals, so the proxy lives at this path. - Inputs: Bearer
sessionToken. - Returns / side effects: Open-proposal array. Throws visitor copy
Could not load moderator proposals. Please try again.on 401/403/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
ProposalsScreen,useUnreadCount.
Function: postFundingApply
- Purpose: POST
/funding/apply(Bearer) and parse{ funding }viafundingApplyResponseSchema. Rolebasisis 403. 400About me is required/About me photo is required/Location is requiredare rethrown; other failures use visitor copyCould not submit your application. Please try again. - Inputs: Bearer
sessionToken. - Returns / side effects: Updated
OwnerFunding. Throws the 400 api string, or visitor copy on 401/403/409/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
FundingApplyScreen: a verified account with statusnoneorrejectedsees the walk and callspostFundingApplyafter Yes on the truth question. Applications are open to every verified member.
Function: postFundingWithdraw
- Purpose: POST
/funding/withdraw(Bearer, no body): the signed-in member withdraws their own grant, an open application, a one-day trial, or an admitted place, so the place becomes free for someone else. Parses{ funding }viafundingWithdrawResponseSchema; after a withdrawal the status isnone(the same enum as every other owner funding answer). - Inputs: Bearer
sessionToken. - Returns / side effects: Updated
OwnerFunding. ThrowsUnauthorizedon 401 andConflicton 409 (nothing to withdraw, or a staff decision at the same moment), so the caller can sign out or load the account again. 403, 404 (an api that does not have the endpoint yet), 503, any other non-2xx, a network failure, or a body that fails the schema throw the visitor copyCould not withdraw. Please try again. - Used by:
FundingWithdrawControlon/grants, after the member confirms Withdraw my application or Leave the grant.
Function: fetchFundingPayoutDays
- Purpose: GET
/funding/payout-days(same-origin Bearer proxy of apiGET /funding/payout-days) and parsefundingPayoutDaysResponseSchema. Next.js forbids aroute.tsbeside/moderate/payouts, so the proxy lives at this path. Seven UTC days, oldest first, and one row per person. - Inputs: Bearer
sessionToken. - Returns / side effects:
{ days, rows }. Throws visitor copyCould not load the payout table. Please try again.on 401/403/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
FundingPayoutsScreen.
Function: fetchShopActivityShops
- Purpose: GET
/shops/activity/shops(same-origin Bearer proxy of apiGET /shops/activity/shops) and parseshopActivityShopsSchema.todayandlastChargeDaymust be real calendar days (isUtcDay). Keeps the api order of the shops. - Inputs: Bearer
sessionToken. - Returns / side effects:
{ windowDays, today, shops }. Throws'moderate.forbidden'on 403. Throws visitor copyCould not load shop activity. Please try again.on 401/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
ShopActivityShopsScreen.
Function: fetchFundingApplications
- Purpose: GET
/funding/applications(same-origin Bearer proxy of apiGET /funding/applications) and parsefundingApplicationsResponseSchema.applications. Next.js forbids aroute.tsbeside/grants/applications, so the proxy lives at this path. - Inputs: Bearer
sessionToken. - Returns / side effects: Open-application array. Throws visitor copy
Could not load grant applications. Please try again.on 401/403/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
FundingApplicationsScreen.
Function: fetchFundingApplication
- Purpose: GET
/funding/applications/:accountId(Bearer) and parsefundingApplicationDetailSchema. - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects: Account, grant, and living-room posts. Rows are parsed one by one (
forumMessageRowsSchema): a note that failsforumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in oneconsole.warnwithout its content, and the other rows still render; only an invalid envelope fails the detail. Throws visitor copyCould not load this application. Please try again.on 401/403/404/503, other non-2xx, network failure, or a body that fails the schema. - Used by:
FundingApplicationDetailScreen.
Function: fetchDailyRoster
- Purpose: GET
/funding/daily-roster(same-origin Bearer proxy of apiGET /funding/daily-roster) and parsedailyRosterSchema. Next.js forbids aroute.tsbeside/grants/payments/comment,/grants/payments/amounts, and/grants/payments/moderators, so the proxy lives at this path. The body is{ comment, paymentsEnabled, defaultAmountUsd, recipients, moderatorPaymentsEnabled, moderators }with{ address, amountUsd, accountId, name }rows on both lists.addressstays in the JSON and is not rendered.defaultAmountUsdis a finite number. Moderator rows stay out ofrecipients. - Inputs: Bearer
session. - Returns / side effects: Parsed roster. Throws
funding.daily.forbiddenon apiForbidden. Throws visitor copyCould not load daily payments. Please try again.on 401, other 403, 503, other non-2xx, network failure, or a body that fails the schema. - Used by:
DailyPaymentCommentScreen,DailyPaymentAmountsScreen,DailyPaymentModeratorsScreen.
Function: saveDailyRosterComment
- Purpose: POST
/funding/daily-roster/commentwith{ comment }and parse the returned roster. - Inputs: Bearer
session, comment text. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. Maps apiInvalid commenttofunding.daily.invalidComment. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentCommentScreen.
Function: saveDailyRosterPayments
- Purpose: POST
/funding/daily-roster/paymentswith{ enabled }and parse the returned roster.enabledis a boolean. - Inputs: Bearer
session,enabled. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. Maps apiInvalid payments switchtofunding.daily.invalidSwitch. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentAmountsScreen.
Function: addDailyRosterRecipient
- Purpose: POST
/funding/daily-roster/recipientswith{ accountId, amountUsd }and parse the returned roster.amountUsdis a real number, not a numeric string. - Inputs: Bearer
session, account id, USD amount. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsInvalid person or amount,Unknown person,Person has no Lightning address, andAddress already listed. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentAmountsScreen.
Function: updateDailyRosterRecipient
- Purpose: POST
/funding/daily-roster/recipients/updatewith{ address, amountUsd }and parse the returned roster. - Inputs: Bearer
session, stored address, new USD amount. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsInvalid address or amountandUnknown address. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentAmountsScreen.
Function: deleteDailyRosterRecipient
- Purpose: POST
/funding/daily-roster/recipients/deletewith{ address }and parse the returned roster. - Inputs: Bearer
session, stored address. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsUnknown address. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentAmountsScreen.
Function: addDailyRosterModerator
- Purpose: POST
/funding/daily-roster/moderatorswith{ accountId, amountUsd }and parse the returned roster.amountUsdis a real number, not a numeric string. - Inputs: Bearer
session, account id, USD amount. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsInvalid person or amount,Unknown person,Person has no Lightning address, andAddress already listed. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentModeratorsScreen.
Function: updateDailyRosterModerator
- Purpose: POST
/funding/daily-roster/moderators/updatewith{ address, amountUsd }and parse the returned roster. - Inputs: Bearer
session, stored address, new USD amount. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsInvalid address or amountandUnknown address. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentModeratorsScreen.
Function: deleteDailyRosterModerator
- Purpose: POST
/funding/daily-roster/moderators/deletewith{ address }and parse the returned roster. - Inputs: Bearer
session, stored address. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. MapsUnknown address. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentModeratorsScreen.
Function: saveDailyRosterModeratorPayments
- Purpose: POST
/funding/daily-roster/moderators/paymentswith{ enabled }and parse the returned roster.enabledis a boolean. - Inputs: Bearer
session,enabled. - Returns / side effects: Updated roster. Throws a
funding.daily.*catalog key. Maps apiInvalid payments switchtofunding.daily.invalidSwitch. Any other failure isfunding.daily.saveError. - Used by:
DailyPaymentModeratorsScreen.
Function: postFundingAdmit
- Purpose: POST
/funding/admitwith{ accountId }(staff). Target pending or trial. - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
FundingDecisionResult. ThrowsError(FUNDING_PLACES_FULL_ERROR)(All grant places are taken) when the api answers 409 with that error (the round has no free place), and visitor copyCould not update this member. Please try again.on any other failure, including another 409 or an unreadable 409 body. - Used by:
FundingApplicationDetailScreen.
Function: postFundingReject
- Purpose: POST
/funding/rejectwith{ accountId }(staff). The subject may re-apply. - Inputs: Bearer
sessionToken, subjectaccountId. - Returns / side effects:
FundingDecisionResult. Throws visitor copyCould not update this member. Please try again.on any failure. - Used by:
FundingApplicationDetailScreen.
Function: mergeTrustChain
- Purpose: Merge a newly loaded neighborhood into the already visible Trust Chain without duplicating nodes or edges.
- Inputs:
currentgraph,incominghop fromGET /trust-chain?around=. - Returns / side effects: Combined
{ nodes, edges }. No I/O. - Used by:
TrustChainLoader.
Function: layoutTrustChain
- Purpose: Positions Trust Chain nodes without a graph library. Roots sit in one row. A person with a single next person sits to their right. Several people hanging off one person stack top to bottom (
TRUST_NODE_VGAP) by descending role rank (founder 6, initiator 5, software developer 4, fond 3, moderator 2, then verified 1; same-rank siblings keep edge order), not side by side and not as a pyramid of levels. - Inputs:
TrustChain{ nodes, edges }. - Returns / side effects:
{ nodes, edges, width, height }with pixel positions. Empty input is zero size. - Used by:
TrustChainDiagram.
Function: TrustChainDiagram
- Purpose: SVG diagram of the laid-out Trust Chain (name, role, unlabeled arrow). One next person sits to the right; several hanging off one person stack top to bottom. Drag a person to move them. A plain click loads one hop around that person; modifier-click keeps the
/members/{id}link. Each person is a client-sidenext/link(no prefetch), so withoutonExpanda plain click opens the member without a page load. - Inputs:
chain: TrustChain, optionalexpandingId, optionalonExpand. - Returns / side effects: SVG with
data-testid="trust-node-{id}". Empty chain is not rendered by the parent screen. - Used by:
TrustChainScreen.
Function: TrustChainScreen
- Purpose: Localized
/trust-chainbody: title, lead, loading/error/empty/diagram, and the Verified, Moderator, Fond, Software Developer, Initiator, and Founder explanations, in that rendered order. A hop-load error with nodes already on screen keeps the diagram and shows the catalog error plus Try again above it. App theme tokens (app-fg/app-muted), not marketing display type. - Inputs:
chain,error,loading, optionalexpandingId,onExpand,onRetry. - Returns / side effects: Signed-in screen element.
- Used by:
TrustChainLoader.
Function: TrustChainLoader
- Purpose: Client loader for signed-in
/trust-chain: founder seeds first, then one hop per click, merged into the visible graph. A failed hop keeps the chain. Retry with nodes already on screen re-fetches that?around=hop (does not re-fetch seeds); the banner stays gone only if the hop succeeds. Does not fetch when the session is null. - Inputs: Session from the auth store.
- Returns / side effects: Loading, error+retry, empty, diagram, or diagram-plus-hop-error states, or
nullwithout a session. - Used by:
TrustChainPage.
Function: TrustChainPage
- Purpose: Signed-in page at
/trust-chain. Any logged-in completed account may view (not staff-only). - Inputs: none.
- Returns / side effects: Fill
AppShell(align="start") withProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGate screen="welcome"aroundTrustChainLoader. Graph HTTP is under/trust/graph(noroute.tsbeside this page). - Used by: App Router
src/app/trust-chain/page.tsx.
Function: StaffFunctions
- Purpose: Closed disclosure for actions available to accounts at least moderator. On a member card the children are the verify, propose, and confirm controls available at least moderator, plus the appoint control, which is founder only. On
/statisticsthe only child is the payout link, andStatisticsScreenmounts the disclosure only for an account at least moderator when yesterday's person count is a number. The summary isstaff.functions, a closeddetails/summaryrow. Children mount only while it is open. - Inputs:
children. - Returns / side effects:
data-testid="staff-functions".openwhile expanded. Clicking the summary toggles. Clicks do not propagate. - Used by:
MemberTrustActions,StatisticsScreen.
Function: MemberTrustActions
- Purpose: Staff-only Trust Chain controls on another member's identity card. Verify is a
ButtonLinkto/members/[accountId]/verifyand does not post from this card. Propose, Confirm, and Appoint stay one-click buttons that post from the card. The controls are children of the closedStaffFunctionsdisclosure; they are not painted until it is opened. - Inputs:
profile, optionalonUpdated. Hidden unless the signed-in account is a moderator and not the subject. - Returns / side effects: Propose / Confirm / Appoint POST then re-fetch member;
data-testid="state-members-staff-verify"when shown. The Verify link and the remaining action buttons mount only after the disclosure is opened. - Used by:
MemberProfileScreen.
Function: MemberVerifyPage
- Purpose: Next.js page for
/members/[accountId]/verify. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="profile"aroundMemberVerifyScreen. The card has no back control. There is noroute.tsbeside this page. - Inputs: Dynamic
accountId. - Returns / side effects: The stored-name check inside fill AppShell. Member HTTP stays on the existing
fetchMemberclient. - Used by: Route
/members/[accountId]/verify.
Function: MemberVerifyScreen
- Purpose: Client stored-name check. Heading Verify. Renders
nullwithout a session and does not fetch. An id that is not a UUID shows This profile could not be found. and does not fetch. A viewer below moderator sees You cannot verify this member. and does not fetch. OtherwisefetchMemberruns. A moderator who is not the subject, and a basis member with a stored name that is not only whitespace, sees that exact name as an underlined link to the member card, the question under it, then Yes and No. Yes is the only control that posts. No opens the member card and does not post. Both buttons are the only children ofSundayWritingGate; Sunday hides both. There is no Cancel. Chrome back does not post. - Inputs: Route
accountId; session and account fromuseAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session.postTrustVerify(session, profile.id, identifyingName)only from Yes, with the untrimmed stored name, thenrouter.pushto/members/${profile.id}. No onlyrouter.pushto/members/${profile.id}and does not post. A thrown write stays on this page with Could not update this member. Please try again. - Used by:
MemberVerifyPage.
Function: fetchPostStats
- Purpose: GET
/messages/statsand parse the public post totals. Notes and replies are one count. - Inputs: None.
- Returns / side effects:
PostStats. Throws visitor copy when the api is down or the body is invalid. - Used by:
StatsLoader.
Function: fetchWalletStats
- Purpose: Fetches the public self-reported 21.gifts wallet totals and the UTC-day balance series from same-origin
GET /wallets/stats. - Inputs: None.
- Returns / side effects: Parsed
WalletStats; throws the visitor-facing copy Could not load wallet stats. Please try again. when the response is not ok, the fetch fails, or the body failswalletStatsSchema. - Used by:
StatsLoaderon/stats(inside the samePromise.all, tolerant so a failure only hides the Wallets section) andWalletUsageLoaderon/stats/wallet(a failure there only hides the wallets-per-day chart).
Function: fetchWalletUsage
- Purpose: Fetches aggregate wallet use since the production release from same-origin
GET /wallets/usageand parseswalletUsageSchema. The payload has no person, account, or payment id. - Inputs: None.
- Returns / side effects: Parsed
WalletUsage. Throws Could not load wallet usage. Please try again. when the response is not ok, the fetch fails, or the body fails the schema. - Used by:
WalletUsageLoaderon/stats/wallet.
Function: fetchGiftStats
- Purpose: GET
/gifts/statsand parse the public gift totals payload. - Inputs: None.
- Returns / side effects:
GiftStats. Throws visitor copy when the api is down or the body is invalid. - Used by:
StatsLoaderandStatisticsScreen. Live amounts usefetchFxSpot, not this.
Function: fetchAccountActivity
- Purpose: GET
/me/activitywith Bearer and parseaccountActivitySchema(given + received, house gifts + forum zaps). - Inputs:
sessionToken. - Returns / side effects:
AccountActivity. Throws visitor copyCould not load gift stats. Please try again.on non-2xx, network, or schema failure. - Used by:
useAccountTotals.
Function: fetchMemberActivity
- Purpose: GET
/forum/members/:id/activitywith Bearer and parse activity for a member card. - Inputs:
sessionToken,accountId. - Returns / side effects:
AccountActivity. 409missing_requirements→MissingRequirementsError. Other non-2xx / schema → visitor copy. - Used by:
MemberProfileLoader,ProfileScreen, andViewProfileLoaderafter a successful signed-in refetch.
Function: fetchViewActivity
- Purpose: GET
/view-key/:viewKey/activitywith no auth and parse public activity. - Inputs:
viewKey(64 hex). - Returns / side effects:
AccountActivity. Throws visitor copy on failure; the loader catches the error, keeps the card, and the chart showsprofile.chartError. - Used by:
ViewProfileLoader.
Function: fetchMe
- Purpose: GET
/mewith the bearer session. - Inputs:
sessionToken. - Returns / side effects:
Accountornullon 401. ThrowsWrongAccountErroron 403 with the duplicate-account api string. Other non-2xx throw the generic fetch-account error. - Used by:
useHydrateSession,renewPasskey.
Function: fetchPublicForumMessages
- Purpose:
GET /forum/messages?mode=activewith no Authorization header. Same page size (20) and cursor as the signed-in feed. HTTP 401 throwsPublicForumUnauthorizedError. - Inputs: Optional
limitandcursor. - Returns / side effects:
{ messages, nextCursor }. Rows are parsed one by one (forumMessageRowsSchema): a note that failsforumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in oneconsole.warnwithout its content, and the other rows still render; only an invalid envelope fails the list.nextCursoris kept even when every row of a page was dropped;ForumBoardthen puts the scroll sentinel on the empty-feed line soForumLoaderloads that next page. - Used by:
ForumLoaderwhen the living room has no session.
Function: PublicForumUnauthorizedError
- Purpose: Error for a 401 from the public active page. The first page shows the existing load error. A later page sends the visitor to
/login. - Inputs: None.
- Returns / side effects: An
Errorwhose name isPublicForumUnauthorizedError. - Used by:
fetchPublicForumMessages,ForumLoader.
Function: fetchMessages
- Purpose: GET
/forum/messageswith the bearer session, parseforumListSchema, and return the newest-first feed page as{ messages, nextCursor }(including defaultedreplyCount). - Inputs:
sessionToken; optional{ mode, limit, cursor, hashtag, country }. Always sendslimit(default 20), sendsmodewhen supplied, sendshashtagwhen non-empty, sendscountry(ISO 3166-1 alpha-2; only notes pinned in that country) when non-empty, and omits a null or empty cursor and an empty/''hashtag or country. - Returns / side effects:
ForumFeedPagewithnextCursor: nullwhen the response omits it. In every mode (Active, No gifts yet, All, Most popular, and the shops hashtag) rows are parsed one by one (forumMessageRowsSchema): a note that failsforumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in oneconsole.warnwithout its content, and the other rows still render; only an invalid envelope fails the list.nextCursoris kept even when every row of a page was dropped; on the forum listForumBoardthen puts the scroll sentinel on the empty-feed line, soForumLoaderloads that next page, while the shops table keeps its own Show more. Throws visitor copy (Could not load messages. Please try again.) on a non-ok response, a network failure, or an invalid envelope (messagesnot an array, or an emptynextCursor). - Used by:
ForumLoader,ShopTable.
Function: fetchExternalAuthorProfile
- Purpose: GET
/public-messages/:id/external-profilewith no Authorization and parseexternalAuthorProfileSchema. - Inputs: Forum message
id. - Returns / side effects:
{ name, npub, nip05?, lud16? }, plus optionalpostCount,replyCount,shopCount, andcreditCount, ornullon 404, any other non-OK response, network failure, JSON failure, or schema mismatch. Credits are not prefetched. Does not throw. - Used by:
ExternalAuthorProfile.
Function: fetchExternalAuthorPosts
- Purpose: GET
/public-messages/:id/external-postswith no Authorization. After HTTP OK, require{ messages: array }, parse the items withforumMessageRowsSchema(each item throughforumMessageSchema; invalid items are skipped and counted in oneconsole.warnwithout content). - Inputs: Forum message
id. - Returns / side effects:
ForumMessage[](empty if none survive or the list is empty). Throws visitor copy (Could not load messages. Please try again.) on non-OK including 404, network, non-JSON, or a body that is not{ messages: array }. Does not throwMissingRequirementsError. No Bearer. - Used by:
ExternalAuthorProfile.
Function: fetchExternalAuthorShops
- Purpose: GET
/public-messages/:id/external-shopswith no Authorization. After HTTP OK, require{ messages: array },safeParseeach item withforumMessageSchema, skip invalid items. - Inputs: Forum message
id. - Returns / side effects:
ForumMessage[](empty if none survive or the list is empty). Throws visitor copy (Could not load messages. Please try again.) on non-OK including 404, network, non-JSON, or a body that is not{ messages: array }. Does not throwMissingRequirementsError. No Bearer. - Used by:
ExternalAuthorProfile.
Function: fetchExternalAuthorCredits
- Purpose: GET
/public-messages/:id/external-creditswith no Authorization. After HTTP OK, require{ messages: array },safeParseeach item withforumMessageSchema, skip invalid items. - Inputs: Forum message
id. - Returns / side effects:
ForumMessage[](empty if none survive or the list is empty). Throws visitor copy (Could not load messages. Please try again.) on non-OK including 404, network, non-JSON, or a body that is not{ messages: array }. Does not throwMissingRequirementsError. No Bearer. - Used by:
ExternalAuthorProfile.
Function: fetchExternalAuthorReplies
- Purpose: GET
/public-messages/:id/external-replieswith no Authorization. After HTTP OK, require{ messages: array }, parse the items withforumMessageRowsSchema(each item throughforumMessageSchema; invalid items are skipped and counted in oneconsole.warnwithout content). - Inputs: Forum message
id. - Returns / side effects:
ForumMessage[](empty if none survive or the list is empty). Throws visitor copy (Could not load messages. Please try again.) on non-OK including 404, network, non-JSON, or a body that is not{ messages: array }. Does not throwMissingRequirementsError. No Bearer. - Used by:
ExternalAuthorProfile.
Function: fetchPublicMessage
- Purpose: GET
/public-messages/:idwithout a session, parseforumMessageSchema, and return one public forum note for the HTML note page. OptionalsinceSatsappends?sinceSats=so the api can wait until the note has more sats (pay poll on a top-level note). OptionalsinceReceivedSatsappends?sinceReceivedSats=so the api can wait until a reply has more received sats. A non-integer, NaN, Infinity, or negative value is omitted for either query. When both are valid,sinceSatscomes first. - Inputs: Forum message
id(UUID string). OptionaloptswithsinceSatsandsinceReceivedSats(each a finite integer ≥ 0; omitted / NaN / Infinity / negatives / non-integers skip that query) andsignal(AbortSignalpassed tofetchwhen provided). - Returns / side effects:
ForumMessage, ornullon 404 or abort (AbortError/ already-aborted signal). Throws visitor copy (Could not load messages. Please try again.) on other non-ok, network, or zod failures. - Used by:
PublicMessageLoader,ForumLoader.
Function: fetchShortLink
- Purpose: GET
/links/<code>without a session. An invalid code, a non-OK response (400, 404, 409, or anything else), and an unexpected body returnnull. Network and JSON failures returnnulland do not throw. - Inputs:
codestring. Only^[0-9a-f]{8}$(case-insensitive) is fetched; other strings returnnullwithout a request. - Returns / side effects:
{ kind: 'message' | 'member', id }withidlowercased, ornull. - Used by:
ForumQuotedBody.
Function: fetchForumMessage
- Purpose: GET
/forum/messages/:idwith a bearer session, parseforumMessageSchema, and return one forum note. Staff sessions receive soft-hidden rows (deletedAt/deletedBy); others get 404. - Inputs:
sessionTokenand forum messageid(UUID string). - Returns / side effects:
ForumMessage, ornullon 404. Throws visitor copy (Could not load messages. Please try again.) on other non-ok, network, or zod failures. - Used by:
PublicMessageLoader.
Function: fetchPublicReplies
- Purpose: GET
/public-messages/:id/replieswithout a session. After HTTP OK, require{ messages: array }, parse the items withforumMessageRowsSchema(each item throughforumMessageSchema; invalid items are skipped and counted in oneconsole.warnwithout content), and return the survivors oldest-first. Aheartsarray, when present, is parsed withheartSenderSchemaand kept newest first, including the frozen fiat strings. - Inputs: Parent forum message
id. - Returns / side effects:
ForumMessage[](empty if none survive or HTTP 200{ messages: [] }) with a non-enumerableheartsproperty (HeartSender[];[]when the field is missing). Throws visitor copy (Could not load messages. Please try again.) on HTTP 404 (not empty), other non-ok, network, non-JSON, or a body that is not{ messages: array }. - Used by:
PublicMessageLoader.
Function: fetchPublicMessagePhoto
- Purpose: GET
/messages/:id/photowith no Authorization when the index is 0 or ≤0, and GET/messages/:id/photo/{index}.jpgfor indices 1–9. The blob is forMemberProfileScreenwhen that screen has no session. Public forum stills useforumPhotoSrcinstead. Throws visitor copy on failure. - Inputs: Forum message
id, optional zero-basedindex(default 0). - Returns / side effects:
Blob. Index 0 (and ≤0) uses the legacy photo route; indices 1–9 request{index}.jpg. Throws visitor copy (Could not load messages. Please try again.) on non-ok, empty body, or network failure — does not leak status codes. - Used by:
MemberProfileScreen(unsigned About me photo).
Function: fetchReplies
- Purpose: GET
/forum/messages/:id/replieswith the bearer session. After HTTP OK, require{ messages: array }, parse the items withforumMessageRowsSchema(each item throughforumMessageSchema; invalid items are skipped and counted in oneconsole.warnwithout content), and return the survivors oldest-first. Aheartsarray, when present, is parsed withheartSenderSchemaand kept newest first. - Inputs:
sessionToken, parent messageid. - Returns / side effects:
ForumMessage[](empty if none survive) with a non-enumerableheartsproperty (HeartSender[];[]when the field is missing). Throws visitor copy (Could not load messages. Please try again.) when the api is unavailable, the body is not JSON, or the body is not{ messages: array }. Damus authors may omitrole(schema defaults tobasis). An optionalvia: 'nostr'field is accepted (present only on replies from a Nostr user with no 21.gifts account). - Used by:
ForumLoader,PublicMessageThread,PublicMessageLoader,MemberProfileScreen.
Function: fetchMessagePhoto
- Purpose: GET
/messages/:id/photo(index 0) or/messages/:id/photo/{index}.jpg(indices 1–9) with the bearer session and return the raw image bytes as aBlobforURL.createObjectURLrendering. - Inputs:
sessionToken, messageid, optional zero-basedindex(default 0). - Returns / side effects:
Blob. Throws visitor copy (Could not load messages. Please try again.) on non-ok, empty body, or network failure — does not leak status codes. - Used by:
MemberProfileScreen(About me / profile picture),PublicMessageThread(deleted staff row),ShopNoteEditControlwhenexistingPhotosis shorter thanphotoCount.
Function: postMessage
- Purpose: POST
/forum/messageswith bearer +{ text, photo?, photos?, inReplyTo?, goalCurrency?, goalAmount?, place?, shopUsername? }, parseforumMessageSchema, and return the created message or reply (text and/or up to ten photos). Non-emptyphotosdual-sendsphotoas the first still plusphotos. A non-blank stringtakenAton a still is included; a blank or missing time is omitted. OptionalgoalCurrencyandgoalAmountgo together on a top-level note, never asgoalSats; omitted on replies and when either is missing.goalSatsremains a field of the read note. Optionalplaceis{ lat, lng, label, address? }on a top-level note, whereaddresscontains street, house number, postal code, city, and country; omitted when unset. Replies must not send it. OptionalshopUsernameis sent only when the trimmed value without a leading@is non-blank. - Inputs:
sessionToken,inputwithtext, optional{ contentType, data, takenAt? }photo, optionalphotosarray (max 10), optionalinReplyToparent id (thread composer only), optionalgoalCurrencyandgoalAmount(together, nevergoalSats), optionalplace(ForumPlacePin, top-level only), and optionalshopUsername(leading@stripped; omitted when blank). - Returns / side effects:
ForumMessage. OmitsinReplyTo,goalCurrency/goalAmount,place, andshopUsernamefrom the JSON body when absent; omits both Ask fields on replies even if passed. On 400 or 429 uses the api error string when present; otherwise throwsCould not post your message. On 403 throwsPostFeeRequiredErrorwith the api error string when present, otherwiseA reply needs a Bitcoin payment. On 404 whose api error is exactlyNo account with that usernamethrows that string; any other 404 throwsNoteDeletedError. - Interaction log: A created top-level note is recorded as
post_createdwith its id, the number of photos, and whether it is an Ask; a reply asreply_createdwith its id and the parent id. The text is never recorded. - Used by:
ForumLoader,MemberProfileScreen.
Function: postContact
- Purpose: POST
/contact/submitwith bearer +{ text }, parsecontactSchema, and return the created message. - Inputs:
sessionToken,text. - Returns / side effects:
ContactMessage. On 400 uses the api error string when present; otherwise throwsCould not send your message. - Used by:
ContactLoader.
Function: isForumPhotoFile
- Purpose: True when a browser
Filehas mime type JPEG, PNG, WebP, HEIC, or HEIF, or has no mime type and a file name ending in one of those extensions. A phone camera can hand over HEIC or a file without a type. The browser decodes it andprepareForumPhotoorWideImageCropperturns it into a JPEG. A browser that cannot decode it shows the same unsupported-photo sentence as any other unusable file; the photo is never dropped without a sentence. - Inputs:
filefrom<input type="file">(camera or gallery). - Returns / side effects: Boolean. No side effects.
- Used by:
prepareForumPhoto, and the wide-image pick inAboutMeSectionandProfileScreen.
Function: prepareForumPhoto
- Purpose: Client-side resize/JPEG-encode a picked forum photo (max edge 1280, quality 0.8, max 1 MiB) into raw base64 plus a preview data URL. A file whose bytes are a JPEG keeps
takenAtfrom Exif before the canvas encode, also when the camera handed it over without a mime type; PNG, WebP, HEIC, and HEIF settakenAtnull. HEIC and HEIF become a JPEG when the browser can decode them. - Inputs:
fileaccepted byisForumPhotoFile. - Returns / side effects:
{ ok: true, photo }(photo.takenAtis a civil string or null) or{ ok: false, error: 'unsupported' | 'tooLarge' }. Throws when the browser cannot decode the file; every caller shows that as the unsupported-photo sentence. Revokes temporary object URLs it creates. The wide profile image is not prepared here;WideImageCropperframes that JPEG. - Used by:
ForumLoader,AboutMeSection,InboxLoader,ModeratorGroupScreen,ProfileScreen.
Function: initialBannerCrop
- Purpose: Largest 5:2 rectangle centered in a source image, used as the opening frame when a member picks a wide profile image.
- Inputs:
imageWidthandimageHeightin source pixels. - Returns / side effects:
{ x, y, width, height }, ornullwhen either dimension is not a finite number greater than 0. A panorama is full height. Every other shape, including a square and a 4:3, is full width. No network. - Used by:
WideImageCropper.
Function: panBannerCrop
- Purpose: Move a 5:2 crop window by a source-pixel delta and keep it inside the image.
- Inputs:
imageWidth,imageHeight, the currentcrop, anddx/dyin source pixels. - Returns / side effects: A new crop with the same width and height.
xandyare clamped to the image. No network. - Used by:
WideImageCropper,zoomBannerCrop.
Function: zoomBannerCrop
- Purpose: Scale a 5:2 crop around its center. A factor greater than 1 zooms in by shrinking the window.
- Inputs:
imageWidth,imageHeight, the currentcrop, andfactor. - Returns / side effects: The zoomed crop, or the same crop when the image has no fitting window. The window cannot grow past
initialBannerCropand cannot shrink below a height of 32, unless the fitting window is already shorter. Width stays height times 5/2. No network. - Used by:
WideImageCropper.
Function: outputBannerSize
- Purpose: Encoded pixel size for a chosen wide-image crop. The result is what the profile API measures.
- Inputs:
cropWidthin source pixels. - Returns / side effects:
{ width, height }. Width ismin(1280, max(640, round(cropWidth))). Height ismax(1, round(width * 2 / 5)). No network. - Used by:
encodeWideBanner.
Function: encodeWideBanner
- Purpose: Draw a 5:2 crop into a JPEG the wide-image API accepts.
- Inputs:
sourcecanvas image,imageWidth,imageHeight, and thecropwindow. - Returns / side effects:
{ ok: true, photo }withcontentType: 'image/jpeg', raw base64data, and apreviewUrldata URL. Quality tries 0.8, then 0.6, then 0.4.{ ok: false, error: 'tooLarge' }when the decoded JPEG is still over 1 MiB.'unsupported'when the crop is not finite and positive, the canvas has no 2d context, ortoDataURLis not a JPEG. Does not throw for those failures. - Used by:
WideImageCropper.
Function: WideImageCropper
- Purpose: In-app 5:2 frame for a picked wide profile image. The member drags, pinches, or scrolls the wheel, then confirms or cancels. A portrait, square, or 4:3 is framed here instead of rejected.
- Inputs:
file(any fileisForumPhotoFileaccepts, from the camera or the gallery), optionalbusy,onConfirmwith{ contentType: 'image/jpeg', data },onCancel, andonError('unsupported'or'tooLarge'). - Returns / side effects: The frame (
profile.about.bannerCropHintDrag the photo to choose the wide image), labeled Use this crop, and an X IconButton whose accessible name is Cancel crop (no visible cancel sentence). Confirm callsencodeWideBannerandonConfirm. Cancel callsonCanceland uploads nothing. A file that cannot be decoded callsonError('unsupported'). No network by itself. - Used by:
ProfileScreen(empty wide-image slot, from the camera or the gallery; the cropper replaces the camera and Add a wide image and leaves Add a profile photo),AboutMeSection(editor, full width above the small wide-image preview).
Function: parseNumberFormat
- Purpose: Returns
valueif it is exactly one ofNUMBER_FORMATS(ch/us/de); otherwise Swissch. Case-sensitive;'CH'and'de-CH'are invalid and fall back to the default. - Inputs: Raw cookie or option
valuestring, orundefinedwhen absent. - Returns / side effects: A supported
NumberFormatStyle. Missing or unknown values becomeDEFAULT_NUMBER_FORMAT(ch). Never writes a cookie. - Used by:
getRequestNumberFormat(server cookie) and any caller that must coerce a rawnumberFormatstring.
Function: separatorsFor
- Purpose: Returns the grouping and decimal characters for one
NumberFormatStylewithoutIntl.NumberFormat. Swiss uses'+., US uses,+., German uses.+,. - Inputs:
style(ch/us/de). - Returns / side effects:
{ grouping, decimal }for that style. Exhaustive switch overNumberFormatStyle. - Used by:
formatGroupedNumberandformatUsdTick(under-10 values swap the decimal separator).
Function: formatGroupedNumber
- Purpose: Groups the integer part of
valuein threes from the right and emitsfractionDigitsdecimal digits usingseparatorsFor. Non-finite values are treated as 0. Rounding usesMath.roundatfractionDigits. - Inputs:
valuenumber,styleNumberFormatStyle,fractionDigits(0 omits the decimal part). - Returns / side effects: Grouped numeric string without a currency or ₿ prefix (for example
1'500or10'000.23). Negative values keep a leading minus. - Used by:
formatBitcoin,formatUsdDisplay,formatUsdTick,NumberFormatSwitchersample labels,DayLoader,GiftDayTable, andStatsDashboard.
Function: formatBitcoin
- Purpose: Formats a whole-sat amount as BIP-177 ₿-only display (leading ₿, grouping from
style, no fraction, no “sats” unit). - Inputs:
satsnon-negative number (APIsats/totalSats; chart mid-ticks may be fractional and are rounded); optionalstyleNumberFormatStyle(defaultch). No locale argument. - Returns / side effects: Display string such as
₿1'500or₿0. - Used by:
ForumBoard,AccountActivityChart,StatsDashboard,GiftDayTable,DayLoader,WalletBalance,WalletPay,WalletSend,LoansCard,LoanRepayScreen,MenuAccountHeader.
Function: isLocalSunday
- Purpose: True when
nowMsfalls on Sunday in an IANA zone, or in the runtime zone whentimeZoneis omitted. An invalid zone returns false. Does not use one fixed zone for every visitor. - Inputs:
nowMsepoch milliseconds and optionaltimeZone. - Returns / side effects: boolean. No I/O.
- Used by: tests. The painted Sunday flag comes from
SUNDAY_BOOTSTRAP_SCRIPT, which uses the clock; only a Playwright build rendersmeta[name=e2e-now], and only then does the script honour that meta or a sessionStoragee2e-nowpin.
Function: useLocalSunday
- Purpose: Reads
documentElement.dataset.localSundayafter the head script sets it. Server render, and the client before that flag, are false, so weekday tests keep their fields. - Inputs: none.
- Returns / side effects: boolean. Subscribes to attribute changes on
documentElement. - Used by:
SundayWritingGate,ModeratorGroupScreen,PlaceField, andPlacePinChip.
Function: CannotReceiveLabel
- Purpose: Small muted label Can't receive yet (
member.cannotReceive) next to a pay, gift, heart, Lend, or amount control that is disabled because the member it targets cannot receive yet. Text only; the caller disables the control. On the member card and on/viewit stands in place of the gifts block (address, QR and, on the member card, Shop sticker) instead of next to a control. Used wherever the api sendsauthorCanReceive: false,canReceive: false,lightningAddress: null(member card), orlightningAddressVerified: false(/view). - Inputs: None.
- Returns / side effects: A
<span class="text-xs text-app-muted" data-cannot-receive>with the catalog text. No network. - Used by:
ForumBoard(note and reply action rows),InboxScreen(amount field),HabitComments(comment gift),MemberProfileScreenandViewProfileScreen(gifts block).
Function: SundayWritingGate
- Purpose: On the device's local Sunday, replaces public write controls or a forum zap control with a sentence. Otherwise renders the children. The rules in
globals.csshide the field before paint oncedata-local-sunday="1"is set. Weekday wrappers usedisplay: contents. - Inputs:
children, and optionalnotice(writeorzap). - Returns / side effects: The sentence or the children. No network.
- Used by: forum composers, profile editors, grant and trust actions, and forum pay controls.
Function: deviceTimeZoneHeader
- Purpose: Returns a
Time-Zoneheader for the runtime IANA zone so the API can apply the same Sunday rule. Empty in Node (nowindow), when the zone is blank, or whenIntlthrows. - Inputs: none.
- Returns / side effects:
{ 'Time-Zone': zone }or{}. No I/O. - Used by: public write and forum-invoice fetches in
api.ts.
Function: formatForumTime
- Purpose: Formats a forum message timestamp as medium date + short time in the runtime local timezone via
Intl.DateTimeFormat, or returns the original ISO string when the instant is invalid. - Inputs:
isostring,localeBCP 47 tag. - Returns / side effects: Display string. Uses the runtime default timezone (visitor system timezone), not UTC.
- Used by:
ForumBoard,InboxScreen,ModerateScreen,NotificationsScreen,PublicMessageLoader,FundingApplicationDetailScreen,formatForumTimeFromMs.
Function: formatForumTimeFromMs
- Purpose: Formats an epoch-ms timestamp the same way as
formatForumTime(medium date + short time in the runtime local timezone), orString(ms)when the instant is invalid. - Inputs:
msepoch milliseconds,localeBCP 47 tag. - Returns / side effects: Display string. Delegates to
formatForumTimeaftertoISOString. - Used by:
FundingStatusCard,FundingApplicationsScreen,FundingApplicationDetailScreen,MemberProfileScreen.
Function: shortResourceUrl
- Purpose: Build the absolute URL handed to a person for a note, a reply, or a member profile. A UUID becomes
origin+/l/+ the first 8 hex characters, lowercased. Any other id keepsoriginplus the long path (/messages/<id>or/members/<id>). - Inputs:
originwithout a trailing slash, resourceid, andlongPathused whenidis not a UUID. - Returns / side effects: Absolute URL string. No I/O.
- Used by:
copyMessageLinkinForumBoard, the member profile copy control, andpublicMessageOgMetadata.
Function: shortLinkPath
- Purpose: Map a
GET /links/:codeJSON body to the long app path.kind: "message"becomes/messages/<uuid>andkind: "member"becomes/members/<uuid>, with the id lowercased. Anything else, including a non-UUID id, isnull. - Inputs: Parsed JSON
body(unknown). - Returns / side effects: Path string or
null. No I/O. - Used by:
fetchShortLinkand theGET /l/[code]redirect route.
Function: splitForumMessageQuotes
- Purpose: Parse HTTP(S)
/messages/<uuid>URLs from a forum body. Returns lowercased unique first-seen ids and displayText with resolved URLs removed (all URLs when resolvedIds omitted). Does not linkify other URLs. - Inputs:
textstring, optionalresolvedIdsReadonlySet<string>. - Returns / side effects:
{ displayText, ids }. No I/O. - Used by:
ForumQuotedBody.
Function: splitShortLinks
- Purpose: Parse HTTP(S)
/l/<8 hex>URLs from a forum body using the same host and punctuation rules assplitForumMessageQuotes. Codes are lowercased, unique, and first-seen. WhenresolvedCodesis omitted, every matched short link is stripped. When it is passed, only those codes are stripped (case-insensitive)./messages/<uuid>URLs are left untouched. - Inputs:
textstring, optionalresolvedCodesReadonlySet<string>. - Returns / side effects:
{ displayText, codes }. No I/O. - Used by:
ForumQuotedBody.
Function: ForumQuotedBody
- Purpose: Remaining body text plus nested post cards for resolved
/messages/<uuid>URLs and forhttp(s)://<host>/l/<8 hex>codes thatfetchShortLinkresolves to a shown message (a member, a null lookup, the containing id, and a failed load stay in the text). Fills from knownNotes first; otherwise fetchPublicMessage (catch, never throw). 404/null leaves the URL, whichLinkedTextthen autolinks as an internal/messages/<uuid>path. Nested card is an outer frame with one empty stretched permalink (absolute inset-0, aria-labelforum.quotedNote, orforum.quotedNoteExternalwhen the quoted note hasvia === 'nostr') that covers the card, including the caption, timestamp, role pill, optional photo, and ₿ amount, and points at/messages/<id>. That permalink is not an ancestor of the caption, so Show more stays outside any anchor. Card content ispointer-events-nonewith[&_*]:pointer-events-none,[&_a]:pointer-events-auto, and[&_button]:pointer-events-auto, so a click on caption text, photo, timestamp, role pill, or amount hits the permalink, while the author profile link, Translate, Show more, and links inside the caption keep their own targets. When the quoted note hasvia === 'nostr', the name is a link to/messages/<id>/author, not a dialog.[&_[role=dialog]]:pointer-events-autoand[&_[role=dialog]_*]:pointer-events-autokeep the external-link confirm dialog and everything inside it clickable, because that dialog is a descendant of the card and is not portaled. The photoimgisdraggable={false}and is not inside the permalink. Caption rendering is unchanged (TranslatableNoteBodywhentranslateis true,plainonly whenvia === 'nostr'; whentranslateis false,ForumNoteTextwhen truncate, elseLinkedText; no nested unfurl).TranslatableNoteBodyon stripped display text only (a successful translation replaces that original after the same quote/short-link strip; optionalformatTranslatedruns after that strip). Feed remaining text and nested captions go throughForumNoteText(280-character preview, Show more only above 560, bodies autolinked) until replaced. Permalink passestruncate={false}so the original stays full (LinkedText). Callers skip this component forvia === 'nostr'rows (plain text and the External badge are handled by the caller). A nested card whose quoted note hasvia === 'nostr'shows in the role-pill slot the label of the api role when that role is tagged (founder,moderator,fond,software_developer,initiator,verified); only when the api role is untagged (such asbasis) does it show the non-interactive External span instead. A software developer shows one Software Developer pill because the api sendsrole: 'software_developer'. Nested nostr captions useTranslatableNoteBodyplainonly whentranslateis true (a URL in a quoted external reply is never a link). Whentranslateis false, nested cards useForumNoteText/LinkedTextand neverTranslatableNoteBody. - Inputs: text, knownNotes, excludeId, rateDay, fiat, optional truncate (default true), optional className (default
whitespace-pre-wrap text-sm text-app-fg;text-app-btn-fgselects NoteTranslatetone="onButton"(viaTranslatableNoteBody)), optionaltranslate(default true;falserenders remaining text and nested quoted cards — includingvia === 'nostr'— throughForumNoteText/LinkedTextwithoutTranslatableNoteBody; forwarded to nestedQuotedForumNote), optionalconversationId(when set, the remainder translates as that conversation message; nested cards stay forum notes), optionalformatTranslated(applied only to the visible remainder translation, after the quote/short-link strip), optionalcontrolSlotId(forwarded toTranslatableNoteBodyfor the footer icon row), optional onActivate. - Returns / side effects: React element or null when text==='' and no resolved quotes. Unknown quote ids load via
fetchForumMessagewhen a session exists, otherwisefetchPublicMessage(catch, never throw). Optionalmentionsare passed only when the quoted author is already the member link. Each nested card has one stretched permalink to/messages/<id>covering the caption, photo, time, and amount; the author link, Translate, Show more, and links inside the caption stay outside that permalink. UsesuseActiveSession: while a login is still opening its wallet, a missing quote loads through the public fetch. - Used by:
ForumBoard,PublicMessageLoader,InboxScreen.
Function: splitNoteLinks
- Purpose: Split a note body into plain-text runs and http(s) URLs. Trailing prose punctuation is not part of the URL.
javascript:/data:and scheme-less text are not links. Each URL is classified internal vs external. Internalpathcollapses extra leading slashes sohttps://21.gifts//…stays a same-origin/…href, not protocol-relative. - Inputs:
textstring, optionalcurrentOrigin(page origin; that hostname is also internal). - Returns / side effects:
NoteLinkSegment[]coveringtextin order. No I/O. - Used by:
LinkedText.
Function: isInternalAppUrl
- Purpose: True when an absolute http(s) URL is an in-app 21.gifts page (
21.gifts,www.21.gifts, or the current origin hostname).api.21.giftsand other subdomains are external. Userinfo does not change the hostname check. - Inputs:
hrefstring, optionalcurrentOrigin. - Returns / side effects: Boolean. No I/O.
- Used by:
splitNoteLinks.
Function: LinkedText
- Purpose: Render a note/About-me/inbox body with clickable http(s) URLs. Internal URLs are Next.js
Links topathname+search+hash(no warning). External URLs are<a href>thatpreventDefaulton a primary click and openExternalLinkWarning. Click and Enter/SpacestopPropagationso a forum card does not toggle; Enter/Space on an external URL opens the warning. Optionalsuffixsits in the same<p>after the runs (Show more). Optionalmentionsturn a resolved@usernameinto the member button (forum.authorProfile). A click opens/members/<accountId>. Optionalplain(default false) renderstextas a single span with no autolinking (no<a>/Link, noExternalLinkWarning), used for Nostr-zapper (via: 'nostr') rows. - Inputs:
text,classNamefor the wrapping<p>, optionallinkClassName(default underline, inherit colour), optionalcurrentOrigin, optionalsuffix, optionalplain(default false), optionalmentions({ username, accountId }[]). - Returns / side effects: Fragment:
<p>plus optional overlay. Confirm onhttps:callsopenInSystemBrowser; other http useswindow.open. - Used by:
ForumNoteText,ForumQuotedBody(whentruncateis false),AboutMeSection.
Function: ExternalAuthorProfile
- Purpose: Profile card for a forum author with no 21.gifts account. Same fields and hide rules as the member card: heading
profile.title, name with the External span, optional checked Nostr address, payment address only when it differs ignoring case, the npub with a centered secondary IconButton copy control. It is not a dialog. Rendered byExternalAuthorPageinsidePublicMessageChrome. No profile image and no outbound link. Copy uses the clipboard, then a hidden textarea. When bothpostCountandreplyCountare numbers, the same count buttons as a member open a read-only feed under the card (no pay, no composer, no react). It shows no heart, because a read-only card without a viewer cannot send one. If either count is absent, no buttons, the npub with the shared centeredNpubCopyButton. - Shop activity: The posts/reactions gate remains unchanged; the preceding absent-count rule applies to those two buttons. Independently,
profile.shopCountappears after reactions only when optionalshopCount > 0, so Shops can appear alone; it loads a read-only external shops feed and a shop note opens/messages/{id}like a post. - Credit activity: The posts/reactions gate is unchanged. Independently,
profile.creditCountappears after shops only when optionalcreditCount > 0, including whenshopCountis 0 or post and reply counts are absent. The feed is read-only; a credit note opens/messages/{id}like a post. No composer and no shop-note edit. Credits are not prefetched. - Inputs:
messageId,fallbackName. EmptyfallbackNameshowsview.unnameduntil a profile loads, and when the fetch returns null. - Returns / side effects: The card. No
onClose. Loading and a null fetch show the title, the fallback name (or Unnamed), and the External span, and omit the address sections. No overlay, portal, hint paragraph, or close control. Count buttons and the read-only feed render when both counts are numbers; a post click opens/messages/{id}; a reply click opens/messages/{parentId}; a shorter list showsprofile.activityLatest; loading usesforum.loading; failure usesforum.errorandview.retry. - Used by:
ExternalAuthorPage.
Function: ExternalAuthorPage
- Purpose: Next.js page for
/messages/[id]/author— the external author profile card for a forum note whose author has no 21.gifts account. Not a member page and not a dialog. Readsparams.idandsearchParams.name(a string or the first array entry, trimmed; blank becomes''). RendersExternalAuthorProfileinsidePublicMessageChrome. NoOnboardingGate. The note id is not validated as a UUID. - Inputs: Dynamic route params (
id) and optionalnamequery (stringorstring[]). - Returns / side effects:
ExternalAuthorProfileinsidePublicMessageChrome(unsigned wordmark href/plusLanguageSwitcher, or signed-inProfileChromeLeftplusSignedInChrome). NogenerateMetadata. - Used by: Route
/messages/[id]/author.ForumBoard(name click).QuotedForumNote(quoted name).PublicMessageLoader(PublicThreadCardname).
Function: ExternalLinkWarning
- Purpose: Confirm overlay before leaving 21.gifts for an external http(s) URL. Same overlay chrome as
IntroduceYourselfOverlay(bg-app-overlay,Card maxWidth="sm", icon-only Close, labeled Open link). The destination URL is shown as user content, not a catalog string. No Skip. - Inputs:
url,onCancel,onConfirm. - Returns / side effects: Dialog. Close/
onCanceldoes not open the URL. Open link callsonConfirm. Dialog click and keydownstopPropagationso a parent forum card does not toggle. - Used by:
LinkedText.
Function: ShopStickerOverlay
- Purpose: Shop-sticker overlay on a member profile. Same overlay chrome as
ExternalLinkWarning(role="dialog",bg-app-overlay, icon-only Close) withCard maxWidth="xl": title Shop sticker, lead Print it for a shop window. The QR code pays {handle}., a Second language combobox, a preview<img>ofbuildShopStickerSvg(alt Shop sticker preview for {handle}), a neutralSegmentedControlFile format PDF | PNG | JPG | SVG (PDF first), and a labeled Download. - Inputs:
qrValue(the profile'sopenCryptoPayQrValue),handle(giftsLightningAddress),onClose. The text language is not a prop.shopStickerLangInitialsets the first selection from the visitor's UI language (en→ English only,de→ German,es→ Spanish,fil→ Filipino), unless the pagelangquery names a sticker language. The combobox then drives the preview and the download. Choosing a language does not write the URL. Options, in order: None (English only), Spanish, German, French, Filipino, Kikamba. The closed control stays in the card flow above the preview; the list opens downward over the preview. - Returns / side effects: Dialog. Download disables itself while
shopStickerBlobruns, then saves the blob through a temporary<a download>named byshopStickerFileNameand revokes the object URL a second later; a failure showsrole="alert"Could not create the file. Please try again. until the next try. Focus moves into the dialog on open and returns to the element that opened it on close. Close callsonClose. Escape closes the open language list first and leaves the dialog up; the next Escape callsonClose. The dialog's own keydown handles Escape from inside it, and adocumentlistener (removed on unmount) closes only on Escape from outside the dialog, so one key press never closes twice even with the app root ondocument. Dialog click and keydownstopPropagation. A press outside the list closes the list only. - Used by:
MemberProfileScreen— only where the profile shows its QR (username set), including on a smartphone.
Function: visibleForumMessages
- Purpose: Client-side filter and sort of the already-loaded forum thread for the Active / No gifts yet / All / Most popular selector. Does not call the api; ranking is among the messages the loader already holds.
- Inputs:
messages(newest-first list from the api / loader merge) andmode(active|unpaid|all|popular). - Returns / side effects: A new array.
allkeeps input order including unpaid (sats === 0) notes.activekeeps paid notes (sats > 0) and unpaid notes without an ask (goalSatsundefined) whose api role is at leastmoderator, so an unpaid note withrole: 'software_developer'counts as a software developer, newest-first. A zero-sat ask is not active.popularkeeps only paid notes, ordered by sats descending, thencreatedAtdescending, theniddescending. Never mutates the input array. - Used by:
ForumBoard,ForumLoader.
The No gifts yet mode keeps only loaded messages with exactly zero sats, including notes without a wallet, preserving input order. The board displays them newest first (same as Active/All). Active remains the default.
Function: hasUnseenForumPosts
- Purpose: True when a fetched forum list contains at least one message id that the currently loaded list does not.
nullcurrent is not unseen so the first load applies instead of showing New posts. A loaded empty list ([]) with new ids is unseen. - Inputs:
current(ForumMessage[]ornull) andfetched(newest-first GET payload). - Returns / side effects: Boolean. Compares ids only; sat changes on existing ids are not unseen.
- Used by:
ForumLoader.
Function: unpaidNewCount
- Purpose: Counts loaded zero-sat notes created after the visitor last opened No gifts yet. Pure: no I/O and does not mutate
messages. A missing or invalidseenAtis a first visit and returns0even when unpaid notes exist. - Inputs:
messages(newest-first list from the api / loader merge) andseenAt(ISO last-visit stamp, ornullwhen never opened). - Returns / side effects: How many currently loaded unpaid notes are strictly newer than
seenAt. No network. - Used by:
ForumLoader.
Function: requestMoveFunds
- Purpose: Asks for the move-funds flow: remembers the request and its source for this tab in
sessionStorage(21gifts.moveFunds, also in memory when storage refuses), so it survives a sign-in, an onboarding redirect, and a reload, and dispatchesMOVE_FUNDS_EVENTso an open signed-in screen opens it at once. - Inputs:
source:'receive'(the Receive view's button) or'link'(a?move=1link). - Returns / side effects: void. Writes the tab flag and dispatches the event. Never stores the recovery phrase or any secret.
- Used by:
MoveFundsLink,WalletReceive.
Function: takeMoveFundsRequest
- Purpose: Takes a waiting move-funds request and clears it, so the flow opens once per request.
- Inputs: None.
- Returns / side effects: The source (
'receive'|'link') of the requestrequestMoveFundsleft, ornullwhen there is none or it was taken already; clears the stored and the in-memory copy. A failed read drops only the stored value; the in-memory copy of this document still counts. A failed remove keeps the value already read, and this document does not take that stored copy a second time (a newrequestMoveFundsclears that). A stored value that is not a source counts as none. - Used by:
MoveFundsSheet.
Function: requestForumCompose
- Purpose: Ask the welcome new-post composer to take focus (on the forum home its writer opens first) and skip
IntroduceYourselfOverlayon the next SignedInChrome mount (whatever screen that is). Used by Write an introduction on/welcome. - Inputs: none.
- Returns / side effects: Sets skip-introduce-once and pending-compose module flags that survive Next.js client navigations until consumed. When
windowexists, dispatchesFORUM_COMPOSE_EVENT(21gifts:forum-compose). - Used by:
IntroduceYourselfOverlay.
Function: consumePendingForumCompose
- Purpose: One-shot read of the pending-compose flag from
requestForumCompose. - Inputs: none.
- Returns / side effects:
truewhen compose focus is still pending, then clears the flag.falseon a second call.ForumBoardconsumes only after the new-post textarea is present; acomposerHiddenboard does not clear the flag. - Used by:
ForumBoard.
Function: consumeSkipIntroduceOverlay
- Purpose: One-shot read of the skip-introduce-once flag from
requestForumCompose: the nextSignedInChromemount after Write an introduction starts with the overlay dismissed. That mount uses up the flag, so a later visit to/welcomeasks again while the member still has not posted. - Inputs: none.
- Returns / side effects:
truewhen this mount should start with the overlay dismissed, then clears the flag. Close (X) does not set the flag. - Used by:
SignedInChrome.
Function: fiatPrefix
- Purpose: Amount prefix for a fiat code.
$and₱sit tight against the number, the same way₿does. CHF and EUR keep the code and a trailing space (CHF,EUR). - Inputs:
code(FiatCode: CHF, EUR, USD, or PHP). - Returns / side effects:
'$','₱','CHF ', or'EUR '. No grouping and no network. - Used by:
formatFiatDisplay,formatFiatTick, andformatDefinedGoalAmount.
Function: formatFiatDisplay
- Purpose: Formats an API fiat amount string for stats display using the visitor grouping style.
nullbecomes—(U+2014). USD uses$and PHP uses₱; CHF and EUR prefix the code (CHF 1'425.00). - Inputs:
amount(string | null),code(FiatCode), and optionalstyleNumberFormatStyle(defaultch). - Returns / side effects: Display string such as
$1'425.00/CHF 1'425.00. NoIntl.NumberFormat. No network. - Used by:
StatsDashboard,GiftDayTable,DayLoader,WalletSend,LoansCard,LoanRepayScreen,MenuAccountHeader.
Function: formatFiatTick
- Purpose: Formats a parsed fiat chart-axis value with grouping and a currency prefix. USD uses
$(same asformatUsdTick) and PHP uses₱; CHF and EUR keep the code (CHF 0/CHF 1.43/CHF 1'425). - Inputs:
amountnumber (layout scale only),code(FiatCode), and optionalstyleNumberFormatStyle(defaultch). - Returns / side effects: Axis label. Values under 10 keep trimmed decimals and use the style decimal separator. Does not itself map a null series to
——StatsDashboarddoes that when every selected cumulative isnull.AccountActivityChartmaps all-null CHF/EUR/PHP to—itself. - Used by:
StatsDashboardover-time fiat scale,AccountActivityChart(profile fiat scale).
Function: defaultFiatForLocale
- Purpose: Picks the locale default for preferred fiat when the
fiatcookie is absent:de→ CHF,fil→ PHP,es→ EUR,en→ USD. - Inputs:
locale(Locale). - Returns / side effects: A
FiatCode. No network. - Used by:
getRequestFiat.
Function: formatUsdDisplay
- Purpose: Formats an API USD amount string (
"1425.00") as grouped currency (wrapper aroundformatFiatDisplay(..., 'USD', style)). - Inputs:
usdstring fromGET /gifts/stats; optionalstyleNumberFormatStyle(defaultch). - Returns / side effects: Dollar string such as
$1'425.00. - Used by:
StatsDashboardKPI when USD is selected.
Function: formatUsdTick
- Purpose: Formats a parsed USD chart-axis value as a grouped dollar label.
- Inputs:
usdnumber (layout scale only); optionalstyleNumberFormatStyle(defaultch). - Returns / side effects: Label such as
$1'425. Values under 10 keep trimmed decimals and use the style decimal separator (.forch/us,,forde). - Used by:
AccountActivityChartwhen USD is selected. Stats over-time usesformatFiatTick.
Function: spotRateDay
- Purpose: Turns the
GET /fx/spotprices of 1 BTC into the rate every live amount uses: 100'000'000 sats priced at each code the api priced. A code the api left out has no rate. - Inputs:
rates—Partial<Record<FiatCode, string>>fromfetchFxSpot. - Returns / side effects:
FiatRateDaywithsats: 100000000andusd/chf/eur/phpset to that price ornull, ornullwhen no code has a usable price (missing,"0", or not a number). No I/O. - Used by:
useSpotRate.
Function: useSpotRateState
- Purpose: The current spot rate together with whether its first read has settled.
useSpotRatereturns itsrateDay. A shop or till charge is not priced from this hook:WalletPaymentDetailsandWalletHistorycalluseShopChargeFigureand do not calluseSpotRateState. FetchesGET /fx/spotviafetchFxSpoton mount and every five minutes (SPOT_REFRESH_MS); an answer with a usable price replaces the rate, and an answer without any price or a failed request keeps the last one. A refresh does not start while the previous request is open. Never throws. Drops answers after unmount. - Inputs: Optional
enabled(defaulttrue); while false nothing is fetched,rateDayisnull, andloadingistrue. - Returns / side effects:
{ rateDay, loading }:rateDayisspotRateDayof the latest usable answer (ornull), andloadingturns false once the first read settles, whatever its result. CallsfetchFxSpoton mount and on the refresh timer while enabled; clears the timer on unmount. - Used by:
useSpotRate,MemberHabits.
Function: useSpotRate
- Purpose: The current price of 1 BTC for every amount that is entered or converted live: the amount field (₿ ↔ fiat), the point-of-sale keypad while digits are still being typed, gift and reaction amounts, the wallet and payment fiat suffixes, the self-reported wallet totals and point tooltips on
/stats, and the fiat stored with a new payment that is not a till charge. A committed till charge is not priced from this rate. FetchesGET /fx/spotviafetchFxSpoton mount and again every five minutes (SPOT_REFRESH_MS) while mounted, and resolvesspotRateDayof its rates. An answer with a usable price replaces the rate. An answer without any price (the api has no quote) and a failed request keep the last rate, as the api keeps its last good quote. A refresh does not start while the previous request is still open. Never throws into the caller. Drops answers after unmount. There is no fallback to a gift day: the statistics pages keep each day's own rate fromGET /gifts/stats, and nothing else uses it. - Inputs: Optional
enabled(default true). When false, the fetch is skipped and the hook returnsnull, also after a rate was loaded. - Returns / side effects:
FiatRateDay | null. CallsfetchFxSpoton mount and on the refresh timer while enabled; clears the timer on unmount. - Used by:
ForumLoader,InboxLoader,ModeratorGroupScreen,PayLinkScreen,PosTill(the shared till state still loads this rate for the amount page; the open and paid charge usecommittedFiatFigure, not this rate),PosAmount,MenuAccountHeader,WalletBalance,WalletSend,ExternalAuthorProfile,MemberProfileScreen,PublicMessageLoader,PublicMessageThread,StatsDashboard(only while wallet stats are present),LoansCard,LoanRepayScreen, andRemainingBalanceScreen(the synced balance of a previous wallet).
Function: shownFiatForSats
- Purpose: The four fiat amounts stored for a sat amount the visitor is about to pay, using the same spot rate as the preview. A typed fiat figure replaces that currency's spot with the typed amount at two decimals. The other three currencies stay the spot captured at the same moment. A bitcoin entry stores the spot for every currency.
- Inputs: Whole
sats,rateDay(FiatRateDay | null), and optionaltyped({ code, amount }ornull). Omitted ornullstores only the spot. - Returns / side effects:
{ amountUsd, amountChf, amountEur, amountPhp }, each a two-decimal string ornull. No I/O. - Used by:
ForumLoader,InboxLoader,MemberProfileScreen,PublicMessageThread.
Function: satsToFiatAmount
- Purpose: Scales whole sats into a two-decimal fiat string using one rate (
Math.roundon cents): the spot rate fromuseSpotRate, or one gift day's totals on the statistics pages. - Inputs:
sats,day(FiatRateDay | null),code(FiatCode). - Returns / side effects:
"0.02"-style string, ornullwhen the day or that fiat is missing or that price is"0.00"(not a usable rate). - Used by:
ForumBoard,preferredFiatSuffix,WalletSend,LoanRepayScreen,MenuAccountHeader.
Function: preferredFiatSuffix
- Purpose: Preferred-fiat suffix next to a ₿ amount (
·plus the visitor's default fiat), shared
by the forum, public thread, and inbox/moderator-group threads. Bitcoin is not the visitor's default fiat, so the suffix is required whenever a figure exists. A stored string for that currency is shown as-is and is not recomputed. A passed stored object whose field for the visitor's currency is a string shows that string as-is. A null or missing field, and an omitted stored, show the current spot. The suffix is absent only when neither a stored string nor a usable rate exists.
- Inputs: Whole sats, latest
FiatRateDayornull, visitorFiatCode, number-format
style, optional stored { amountUsd?, amountChf?, amountEur?, amountPhp? } (string | null). A present string for the visitor's currency is formatted as-is (rateDay ignored). A null or missing field, and an omitted stored, show the current spot.
- Returns / side effects:
ReactElement | null. No side effects. - Used by:
ForumBoard,InboxScreen,QuotedForumNote,PublicMessageLoader,WalletBalance,WalletPay,WalletSend.
Function: ThemeProvider
- Purpose: Client provider that reads the
themecookie and OSprefers-color-scheme, exposes preference / resolved theme, and keepshtml.darkin sync after hydration (does not wipe the bootstrap class on the first paint). - Inputs: React
children. - Returns / side effects: Context value with
preference,resolved,setPreference. Writinglight/darksets the cookie (Path=/,Max-Age=31536000,SameSite=Lax,Secureon https);systemdeletes it. Listens tomatchMediawhile preference issystem. - Used by:
RootLayout(wraps the app),ThemeSwitcher,useTheme.
Function: ThemeSwitcher
- Purpose: Settings Display row: uppercase
theme.labelkicker andSegmentedControl tone="neutral"for System / Light / Dark, then the muted line Saved on this device (settings.deviceOnly). Always visible on the signed-in/settingspage. Not page chrome, not a Menu disclosure. - Inputs: None. Reads
preference/setPreferencefromuseTheme. Catalog keystheme.label,theme.system,theme.light,theme.dark,aria.theme. - Returns / side effects: Settings row matching
PushTogglechrome. Pressing an option callssetPreference(cookie write viaThemeProvider); the choice stays on this device. - Used by:
SettingsScreen.
Function: useTheme
- Purpose: Reads theme preference and setters from the nearest
ThemeProvider. - Inputs: None (React context).
- Returns / side effects:
ThemeContextValue. Throws when used outsideThemeProvider. - Used by:
ThemeSwitcherand any client chrome that needs the resolved theme.
Function: parseThemePreference
- Purpose: Parses a cookie / stored theme preference.
- Inputs: Raw cookie value, or
undefinedwhen missing. - Returns / side effects:
'light'/'dark'when valid; otherwise'system'. - Used by:
ThemeProvider,THEME_BOOTSTRAP_SCRIPT(inline equivalent).
Function: resolveTheme
- Purpose: Resolves a preference against the OS color-scheme media query.
- Inputs:
preference(system|light|dark),prefersDarkboolean. - Returns / side effects: Concrete
'light'or'dark'. - Used by:
ThemeProvider.
Function: THEME_BOOTSTRAP_SCRIPT
- Purpose: Blocking bootstrap IIFE string injected as a raw head script before paint. Reads the theme cookie and
matchMedia('(prefers-color-scheme: dark)'), toggleshtml.dark, and has no dependencies. - Inputs: None (constant string).
- Returns / side effects: Non-empty IIFE source mentioning
theme=andclassList. - Used by:
RootLayout<head>script.
Function: THEME_COOKIE
- Purpose: Cookie name for a persisted theme override (
light|dark). Absent means system. - Inputs: None (constant
'theme'). - Returns / side effects: Cookie key string.
- Used by:
ThemeProvider, theme tests.
Function: getApiUrl
- Purpose: Reads
NEXT_PUBLIC_API_URLvia the typed config accessor. - Inputs: None.
- Returns / side effects: Origin string. Throws if unset/empty (entrypoint must substitute).
- Used by:
proxyApiRequest(server-side upstream origin),ShopPage(api base forGET /shops/:npuband for the shop photo URLs),loadPublicMessageForOg(api base forGET /messages/:id), and theGET /l/[code]route handler (api base forGET /links/:code).
Function: getAppVersion
- Purpose: Typed accessor for the baked Menu version (
NEXT_PUBLIC_APP_VERSION). - Inputs: None.
- Returns / side effects: Decimal deploy run number string, or
dev. Throws if unset/empty. Does not go throughentrypoint.sh. Does not truncate. - Used by:
SignedInChrome.
Function: getE2eNow
- Purpose: Reads the optional Playwright clock
NEXT_PUBLIC_E2E_NOW. Production leaves it unset. - Inputs: None.
- Returns / side effects: The pinned instant, or
nullwhen unset or empty. Does not throw and does not invent a time. The head script then uses the device clock. - Used by:
RootLayoutfor thee2e-nowmeta tag;useWallet,useWalletPay, anduseWalletSend, which honour their fixture pins only when it is set.
Function: getBreezApiKey
- Purpose: Reads the optional
NEXT_PUBLIC_BREEZ_API_KEY. Unset or empty disables the in-app wallet (no SDK import, no network call, no balance block). - Inputs: None. Literal
process.env.NEXT_PUBLIC_BREEZ_API_KEYaccess. - Returns / side effects: The key string, or
nullwhen unset or''. Never throws. - Used by:
useWalletStore,connectWallet,listenForWalletPhrase,rememberPhraseFromPrf,usePasskeyLogin.
Function: getPlatformUsername
- Purpose: Reads the optional
NEXT_PUBLIC_PLATFORM_USERNAME, the username of the 21.gifts platform account, set per deployment. In the Docker image it is an optionalentrypoint.shplaceholder: an unset value is substituted with an empty string and the container still starts. Donations to the project go to that account's in-app wallet address<username>@<app host>. Unset, empty, or blank means the landing page shows no donation address. - Inputs: None. Literal
process.env.NEXT_PUBLIC_PLATFORM_USERNAMEaccess (dot access, so the build inlines the value). The blank check is a regular expression so the minifier cannot fold it against the placeholder. - Returns / side effects: The trimmed username, or
nullwhen unset or blank. Never throws. - Used by:
projectDonateAddress.
Function: getSentryDsn
- Purpose: Reads the optional error-reporting DSN
NEXT_PUBLIC_SENTRY_DSN, set per deployment. An optionalentrypoint.shplaceholder likeNEXT_PUBLIC_PLATFORM_USERNAME. Unset, empty, or blank turns error reporting off. - Inputs: None. Literal
process.env.NEXT_PUBLIC_SENTRY_DSNaccess; regular-expression blank check, as ingetPlatformUsername. - Returns / side effects: The trimmed DSN, or
nullwhen unset or blank. Never throws. - Used by:
sentryOptions,forwardSentryEnvelope.
Function: getSentryEnvironment
- Purpose: Reads the optional error-reporting environment name
NEXT_PUBLIC_SENTRY_ENVIRONMENT(for examplestaging), set per deployment. An optionalentrypoint.shplaceholder. - Inputs: None. Literal
process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENTaccess; regular-expression blank check. - Returns / side effects: The trimmed name, or
nullwhen unset or blank (reports then use the SDK default,production). Never throws. - Used by:
sentryOptions.
Function: getSentryTracesSampleRate
- Purpose: Reads the optional share of browser traces
NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE, a number from 0 to 1 such as0.25, set per deployment. An optionalentrypoint.shplaceholder, so an unset value does not stop the container. It only matters while error reporting is on. - Inputs: None. Literal
process.env.NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATEaccess. The value is read with a regular expression (0,1,0.25,.5,1.0, surrounding blanks allowed) instead ofNumber, so the minifier cannot fold it against the placeholder. - Returns / side effects: The rate, or
nullwhen unset, empty, blank, or anything else (1.5,-1,1e-2,10%, text).sentryOptionsthen uses 0.1. Never throws. - Used by:
sentryOptions.
Function: sentryOptions
- Purpose: Builds the error-reporting init options for the browser or the server and edge runtimes, or
nullwhenNEXT_PUBLIC_SENTRY_DSNis unset, empty, or not a DSN (then nothing starts and nothing is sent). - Inputs:
'browser'or'server'. ReadsgetSentryDsn,getSentryEnvironment,getSentryTracesSampleRate, andgetAppVersion(the release). - Returns / side effects: Errors, plus performance traces from the browser only. The browser samples
getSentryTracesSampleRate()of its traces, or 0.1 when that isnull; the server samples none (tracesSampleRate: 0).traceLifecycle: 'static'sends each trace as one transaction, sobeforeSendTransactionsees every span.tracePropagationTargets: []: no request carriessentry-traceorbaggageheaders. No sessions, replay, profiling, logs, feedback, or client reports. No user info, IP address, cookies, bodies, query strings, or stack-frame variables (dataCollection). Drops the session, local-variable, and console integrations and keepsBrowserTracing(page loads, navigations, fetch spans). Browser options post to the same-origin tunnel/monitoring.beforeSend,beforeSendTransaction, andbeforeBreadcrumbremove the user, reduce the request to method, path, User-Agent and Referer, and replace recovery-phrase-shaped word runs in any letter case (which also covers a social recovery share and its QR payload), word arrays of a phrase's or a share's length (12, 15, 18, 20, 21, 24, or 33 words),lnbc/lntb/lnurlstrings and BOLT12lno1/lni1strings,spark1/sparkrt1/sp1/sprt1/spt1addresses, Bitcoin base-chain addresses (bech32bc1/tb1/bcrt1, and mixed-case base58 with a digit), Lightning and e-mail addresses (name@host.tld), 64+ hex digits, raw byte arrays (typed arrays such asUint8Array), bearer tokens, the stored session token, URL queries and fragments, and every value under keys such asmnemonic,phrase,words,seed,share,slip39,token,secret,prf,invoice,pr,query, orfragment. In a transaction that covers its name, every span description, and all span data, so/pl/?lightning=…is sent as/pl/. The SDK's own 16- or 32-digit hex ids underevent_id,trace_id,span_id, andparent_span_idare left as they are, because a random id can start withbc1.beforeSendTransactionfirst drops every span that reaches another origin than the page (for example the wallet asking a receiver's Lightning address server, whose path names the receiver), the web-vital element descriptors (lcp.element,lcp.url,lcp.id,lcp.size,cls.source.N: their DOM text can hold a member's name, and the rendered size of a member's own text or image depends on what it holds), the request and response body sizes (http.response.body.size,http.response.size,http.response.body.decoded_size,http.response_content_length,http.response_transfer_size,http.decoded_response_content_length,http.request.body.size,http.request_content_length, andContent-Lengthheader keys, because the exact size of a member's own response depends on what it holds; status and timing stay), and all breadcrumbs (click labels can spell a typed amount). Of the processing metadata only the sampling context and the span count are kept. Console breadcrumbs are dropped; request breadcrumbs keep method, path, and status only. - Used by:
register(src/instrumentation.ts) andsrc/instrumentation-client.ts, which first removes the server'ssentry-traceandbaggagemeta tags (the server samples nothing, so they say "not sampled") so each page load starts its own trace at the configured rate.
Function: forwardSentryEnvelope
- Purpose: Same-origin tunnel behind
POST /monitoring, so content blockers do not drop error reports and transactions. Forwards one browser envelope to the configured DSN's project. - Inputs: Incoming
Requestwhose body is an envelope; its header line must name the configured DSN's host and project, and every item must be an error (event) or atransaction. - Returns / side effects: 404 while error reporting is off, 413 above 1 MiB (the largest event the Sentry server accepts), 400 for another host or project, a broken header, an envelope without items, a broken item header (also a
lengththat is not a whole number of bytes inside the envelope, such as a string,null, or a boolean, or one that does not end at a newline or at the end of the envelope), or any other item type (session, client report, standalone span, replay, profile, log, feedback, attachment), 502 when the Sentry server cannot be reached, otherwise the upstream status with an empty body. Does not pass on the visitor's IP address, cookies, or headers. - Used by: Route POST
/monitoring.
Function: forwardCspReport
- Purpose: Behind
POST /monitoring/csp: forwards Content-Security-Policy violation reports to the security endpoint of the configured DSN's project (/api/<project>/security/?sentry_key=…, withsentry_releaseand, when set,sentry_environment), so policy gaps show up before the policy is enforced. - Inputs: Incoming
Requestwith the legacyreport-uribody{ "csp-report": {…} }or a Reporting API (report-to) array; onlycsp-violationentries count, at most ten per request. - Returns / side effects: Each violation is sent as its own legacy report with only
document-uri(origin and first path segment when it is a route ofsrc/app:https://21.gifts/view, never the key after it; any other segment becomes/),effective-directive,violated-directive(the directive name only, not the policy with its nonce; the effective directive when the first word is not a directive name),blocked-uri(an http(s) origin; otherwise the lowercase word before:, such asinline,eval,wasm-eval,data,blob,wss; anything else is empty),disposition,source-file(origin only), and whole non-negativeline-number,column-number,status-code. Queries, fragments, member paths, script samples, referrers, and the policy text are dropped, and the reduced report goes through the same privacy scrubber as every event (an address, invoice, or key inside a kept origin becomes[Filtered]). 404 while error reporting is off, 413 above 64 KiB (byContent-Length, or while reading), 400 when the body is not JSON or holds no violation with a directive and an http(s) page, 502 when the Sentry server cannot be reached, otherwise 204. Does not pass on the visitor's IP address, cookies, or headers. - Used by: Route POST
/monitoring/csp.
Function: getCspMode
- Purpose: Reads the Content-Security-Policy mode from the runtime variable
CSP_MODE, on every request, so the same image switches from report-only to enforced without a rebuild. - Inputs: None.
process.env.CSP_MODE. - Returns / side effects:
enforceonly whenCSP_MODEis exactlyenforce;report-onlywhen unset, empty, or anything else. - Used by:
middleware.
Function: cspHeaderName
- Purpose: Response header name for a Content-Security-Policy mode.
- Inputs:
report-onlyorenforce. - Returns / side effects:
Content-Security-Policy-Report-OnlyorContent-Security-Policy. - Used by:
middleware.
Function: createCspNonce
- Purpose: A fresh Content-Security-Policy nonce for one response.
- Inputs: None. Uses
crypto.getRandomValues. - Returns / side effects: 16 random bytes in base64 (24 characters).
- Used by:
middleware.
Function: buildCsp
- Purpose: The Content-Security-Policy text of every page: the directives of
CSP_SOURCESin order, the nonce onscript-src, thenreport-uri /monitoring/cspandreport-to csp. Theimg-srcdirective contains only the OpenCryptoPay origin selected for the hostname.docs/csp.mdlists every source and why it is needed. - Inputs: The nonce of this response and the request hostname;
21.giftsandwww.21.giftsselect the production OpenCryptoPay origin, and all other hosts select development. - Returns / side effects: The policy string, directives separated by
;. - Used by:
middleware.
Function: imageCspSources
- Purpose: Select the image sources allowed for a page hostname.
- Inputs: The page or request hostname.
- Returns / side effects: The image source list with exactly one OpenCryptoPay origin selected for the hostname; no side effects.
- Used by:
buildCspand the homepage popup photo filter.
Function: placesOrigin
- Purpose: Select the OpenCryptoPay origin for the page hostname.
- Inputs: A hostname;
21.giftsandwww.21.giftsselect production. - Returns / side effects: The production origin for those hosts, otherwise the development origin; no side effects.
- Used by: The middleware policy, homepage places endpoint, and popup photo filter.
Function: traceWallet
- Purpose: The one helper that times a wallet step as a performance span, so slow steps of the in-app wallet on phones show up. Each step is its own transaction (
op: wallet,parentSpan: null) in the page's trace, so a long connect does not stretch the page load around it, and all steps of one page share its sampling decision. - Inputs: A fixed name (
wallet.sdk.load,wallet.connect,wallet.sync.first,wallet.balance,wallet.prepare,wallet.send,wallet.address.register,wallet.address.transfer,wallet.passkey), the step as an async function, and optionallyroute(spark,lightning, oronchain) orprompt(login,unlock, orrecoveryfor the passkey a social recovery creates and signs in with), and on the login promptheld(whether a held-back session was waiting). The types allow nothing else: no amount, invoice, address, key, recovery word, PRF output, or token. Every span also carries why this document was loaded, fromcapturePageLoad:load(navigate,reload,back_forward,prerender, orunknown) andload_trigger(appfor App Router's fallback to a full page load, otherwiseother), and how the app is displayed:display(standaloneorbrowser, fromisStandaloneDisplay), so passkey prompts can be counted per page load, cause, and display. - Returns / side effects: What the step resolves to; a rejection marks the span as failed and is passed on unchanged. Without a DSN, or when the trace is not sampled, it only runs the step and nothing is sent. The browser never creates a receive invoice: the api issues it, and the browser's request for it is an automatic fetch span.
- Used by:
connectWallet(SDK load, connect, first synced balance read),refreshWallet(balance read),registerWalletAddress,payFromWallet(prepare and send, with the route),usePasskeyLogin(the login passkey prompt that returns the PRF bytes),unlockWalletPhrase(the seed passkey prompt), the recovery flow (createNewPasskeyand its sign-in,wallet.passkeywithprompt: recovery; the address claim,wallet.address.transfer; the balance send,wallet.sendwithroute: spark), andtransferRemainingBalance(wallet.send).
Function: register
- Purpose: Next.js server start hook (
src/instrumentation.ts) for the Node.js and edge runtimes. Starts error reporting withsentryOptions('server'). - Inputs: None.
- Returns / side effects: Calls the SDK
initwhen a DSN is set; otherwise does nothing (no reports, no network traffic). - Used by: Next.js at server start.
Function: onRequestError
- Purpose: Next.js hook in
src/instrumentation.tsfor errors thrown while rendering a page or handling a route on the server. It is the SDK'scaptureRequestError. - Inputs: The error, the request (path, method, headers), and the route context, from Next.js.
- Returns / side effects: Reports the error when error reporting is on; the
sentryOptionsscrubber then keeps only method, path, User-Agent, and Referer of the request. A no-op while error reporting is off. - Used by: Next.js on server request errors.
Function: capturePageLoad
- Purpose: Record once per document why it was loaded, in fixed words for the wallet trace spans:
loadis the browser'sPerformanceNavigationTiming.type(navigate,reload,back_forward,prerender, orunknownwithout an entry), andload_triggerisappwhen anavigateload found the marker a client-side navigation leaves while it runs (App Router fell back to a full page load), otherwiseother. A reload or a history step that finds the marker was the member's. - Inputs: None. Reads the navigation entry and the
21gifts.loadkey ofsessionStorage(storage that cannot be read counts as no marker). - Returns / side effects:
{ load, load_trigger }, the same object on every later call. Removes the marker on the first call. Stores nothing. - Used by: The browser start-up in
src/instrumentation-client.tsandtraceWallet.
Function: markAppNavigation
- Purpose: Leave the one word
appunder21gifts.loadinsessionStoragewhile a client-side navigation runs, so a full page load that App Router falls back to is counted as started by the app. Nothing else is stored: no path, no time, nothing about the wallet. - Inputs: None.
- Returns / side effects: Writes the marker; storage that cannot be written is ignored (the next load then counts as
other). - Used by:
onRouterTransitionStart.
Function: clearAppNavigation
- Purpose: Remove the
appmarker once a client-side navigation has committed, so a later reload or typed address in this tab is not counted as the app's. - Inputs: None.
- Returns / side effects: Removes
21gifts.loadfromsessionStorage; blocked storage is ignored. - Used by: The search recorder of
ViewHistoryRoot, after each committed view.
Function: onRouterTransitionStart
- Purpose: Next.js hook in
src/instrumentation-client.tscalled when an App Router navigation starts. It leaves theappmarker (markAppNavigation) until the navigation commits, so a full page load that App Router falls back to (a new deploy, a failed page-data request) is counted as the app's, and hands the navigation to the SDK'scaptureRouterTransitionStart, so each client-side navigation gets its own navigation transaction named after its route. - Inputs: The target href and the navigation type (
push,replace, ortraverse), from Next.js. - Returns / side effects: Writes the one word
apptosessionStorage(21gifts.load), also while error reporting is off. Starts the navigation transaction while tracing is on; the transaction then passes thesentryOptionsscrubber. Adds no headers to the navigation's requests. The browser start-up in the same file first callscapturePageLoad, before any navigation can write the marker. - Used by: Next.js on App Router navigations.
Function: GlobalError
- Purpose: Last-resort error boundary (
src/app/global-error.tsx) for render errors no other boundary catches, including errors in the root layout. - Inputs:
error— the caught error. - Returns / side effects: Reports the error once (a no-op while error reporting is off) and renders its own
<html lang="en">document with the Next.js error page, because it replaces the root layout. - Used by: Next.js App Router.
Function: getCatalog
- Purpose: Return the message catalog for a supported UI locale without indexed-access gaps.
- Inputs:
locale(en/de/es/fil). - Returns / side effects: The
Messagesobject for that locale. Exhaustive switch overLocale. - Used by:
RootLayout,Home,/login,NotFound,MarketingFooter,HandbookPage,RulesPage,RulesSetupPage, and therenderWithLocaletest helper.
Function: getRequestLocale
- Purpose: Resolve the UI locale for the current request without writing cookies. Order: header
x-21gifts-public-locale(set by middleware for language URLs), then cookielocale, then Accept-Language. - Inputs: Reads
x-21gifts-public-locale, thelocalecookie, and theAccept-Languageheader vianext/headers(async in Next 15). - Returns / side effects: A supported locale (
en/de/es/fil). A valid public-locale header wins; otherwise a valid cookie; otherwiseparseAcceptLanguage; unmatched →en. - Used by:
RootLayout,MarketingLayout,Home,AboutPage,DonatePage,NotFound,MarketingFooter,HandbookPage,HandbookScreensPage,HandbookFunctionsPage,HandbookEndpointsPage,RulesPage, andRulesSetupPage. Lives insrc/lib/request-locale.tsso client components can import locale constants withoutnext/headers.
Function: getRequestNumberFormat
- Purpose: Resolve the visitor number-format style for the current request without writing cookies. Cookie
numberFormatwins when it isch/us/de; otherwise Swissch. - Inputs: Reads the
numberFormatcookie vianext/headers(async in Next 15). - Returns / side effects: A
NumberFormatStyle. Invalid or missing cookie →ch. Lives insrc/lib/request-number-format.tsso client components can importNUMBER_FORMATSfrom@/lib/number-formatwithout pullingnext/headersinto the browser bundle. - Used by:
RootLayout(passesinitialintoNumberFormatProvider).
Function: isSmartphoneUserAgent
- Purpose: Detects a smartphone so the public pay link can hide its invoice QR (
src/lib/payment-link.ts). True for iPhone, iPod, and Android withMobile; false for iPad, Android tablet (noMobile), and desktop. Viewport width is irrelevant. - Inputs:
userAgentstring (navigator.userAgent). - Returns / side effects:
trueiff the UA is a smartphone. No side effects. - Used by:
PayLinkScreenonly, to hide its invoice QR on a smartphone. Member pay sheets show no invoice QR on any device and do not call it.
Function: lightningHref
- Purpose: Builds the generic
lightning:URI for a payment request or an address, so the device opens whichever Bitcoin wallet app handles that scheme. No particular wallet is named (src/lib/payment-link.ts). - Inputs:
request— a BOLT11 payment request or aname@domainaddress, as issued. - Returns / side effects:
lightning:plus the trimmed request, e.g.lightning:lnbc21n1…orlightning:alice@21.gifts. Pure; no casing change, no I/O. - Used by:
PayLinkScreen(Pay on an issued invoice) and the landingHomepage (the project donate address link).
Function: isInAppBrowser
- Purpose: Detects Telegram and other in-app WebViews where a WebAuthn passkey ceremony cannot complete, so
/loginand/view/[viewKey]can show an escape card instead of starting WebAuthn. - Inputs: Optional
InAppBrowserHost(win); defaults toglobalThis.windowwhen present. Missing window (SSR) is treated as not in-app. - Returns / side effects:
truewhen a Telegram JS bridge is present (TelegramWebviewProxy,TelegramWebview, orTelegram.WebApp) or the UA matches a known in-app token list; otherwisefalse. No network and no DOM writes. - Used by:
LoginCardandViewProfileClaim(choose the in-app escape card after mount),usePasskeyLogin(safety net:NotAllowedErrorduring authenticate →unsupported, no register fallback),shouldOfferIosInstall/PwaInstall(hide install when in-app), and the/login//view/[viewKey]in-app handbook / e2e variants.
Function: loadHandbookDocuments
- Purpose: Read the four app handbook markdown files from disk (README, screens, functions, endpoints).
- Inputs: Optional
rootDir; defaults to<cwd>/docs/handbook. - Returns / side effects:
HandbookDocument[]in that order. Throws when the directory or a required file is missing. - Used by:
HandbookScreensPage,HandbookFunctionsPage,HandbookEndpointsPage.
Function: loadSession
- Purpose: Reads the bearer token from
localStorage. - Inputs: None.
- Returns / side effects: Token string or
null. SSR-safe. - Used by:
useHydrateSessionon mount,useUnreadCount,refreshUnreadAppBadge,NotificationsLoader,MenuAccountHeader.
Function: loadUnpaidSeenAt
- Purpose: Reads the persisted No gifts yet last-visit timestamp from
localStoragekey21gifts.forum-unpaid-seen. - Inputs: None.
- Returns / side effects: The stored ISO string, or
nullwhen none is stored, the value is empty/whitespace/Date.parseis not finite, storage access throws, or when running on the server (nowindow). SSR-safe. - Used by:
ForumLoaderon mount.
Function: parseAcceptLanguage
- Purpose: Negotiate a supported UI locale from an RFC 7231
Accept-Languageheader. - Inputs: Raw header string (may be empty). Splits on commas. A missing
qdefaults to 1. A bareq, empty/invalid qvalue, or duplicateqdiscards that language-range. Maps primary subtags (en/de/es/fil, andtl→fil). - Returns / side effects: Among valid mapped ranges with
q > 0, highestq, then earlier header position, thenLOCALESorder. No positive assignment →en. Pure function — no I/O. - Used by:
getRequestLocalewhen no validlocalecookie is present.
Function: parseHandbookMarkdown
- Purpose: Parse handbook markdown into headings, paragraphs, and lists with inline code, strong, links, and images.
- Inputs:
markdownstring andidPrefixfor ids and in-page hashes. - Returns / side effects:
HandbookBlock[]. Drops unsafe hrefs (.., unknown schemes). - Used by:
HandbookMarkdown.
Function: parseSupportedLocale
- Purpose: Accept a string only when it is exactly one of
en/de/es/fil. - Inputs: Raw cookie or option value, or
undefined. - Returns / side effects: That locale, or
null. Pure function — no I/O. - Used by:
getRequestLocale(cookie).
Function: saveSession
- Purpose: Writes the bearer token to
localStorage. - Inputs:
tokenstring. - Returns / side effects: void. SSR no-op.
- Used by:
useAuthStore.setAuth.
Function: saveUnpaidSeenAt
- Purpose: Persists the No gifts yet last-visit timestamp, overwriting any previous value.
- Inputs:
isoISO timestamp to store (new Date().toISOString()). - Returns / side effects: void. SSR no-op. A throwing storage write is also a no-op.
- Used by:
ForumLoaderwhen entering unpaid and while unpaid as the list refreshes.
Function: setName
- Purpose: POST
/me/name. - Inputs:
sessionToken,name, and optionalsundayWrite(enforcedefault, orsetupto omitTime-Zoneduring onboarding). - Returns / side effects: Updated
Account. - Used by:
NameForm.
Function: setLocation
- Purpose: POST
/me/locationwith JSON{ location }. Empty string is a valid clear. - Inputs:
sessionToken,location(may be empty). - Returns / side effects: Updated
Account. Throws the api error string on 400 when present, otherwise'Could not save your location'. - Used by:
LocationForm.
Function: putAboutMe
- Purpose: PUT
/me/aboutwith bearer +{ text, photo? }and return the updated account.photoomitted keeps a stored image;nullclears it;{ contentType, data }replaces it (same JPEG payload as a forum post). - Inputs:
sessionToken,text, optionalphoto({ contentType, data } | null). - Returns / side effects: Updated
AccountincludingaboutMeandaboutMeHasPhoto. ThrowsMissingRequirementsErroron 409missing_requirements. A 400 body with an error string is thrown aftertoUserFacingError(the About me length sentence passes through). A 400 without an error string, a 409 that is notmissing_requirements, or any other non-2xx throws'Could not save. Please try again.'. A 2xx body that failsaccountSchemathrows the schema error. - Used by:
ProfileScreen.
Function: fetchAboutMePhoto
- Purpose: GET
/me/about/photowith the bearer session and return the raw image bytes as aBlobforURL.createObjectURLrendering. - Inputs:
sessionToken. - Returns / side effects:
Blob. Throws visitor copy (Could not load. Please try again.) on non-ok, empty body, or network failure — does not leak status codes. - Used by:
ProfileScreenviaAboutMeSectionloadPhoto.
Function: fetchViewAboutMePhoto
- Purpose: GET
/view-key/:viewKey/about/photowithout Authorization and return the raw image bytes as aBlob. - Inputs:
viewKey(64 lowercase hex). Encoded in the path. - Returns / side effects:
Blob. Throws visitor copy (Could not load. Please try again.) on non-ok, empty body, or network failure. - Used by:
ViewProfileLoaderwhen the share link has an About me photo and no profile-note id, andViewProfileScreenviaAboutMeSectionloadPhoto.
Function: dismissForumLaws
- Purpose: POST
/me/forum-laws-dismissedto permanently dismiss the welcome-forum living-room laws hint. - Inputs:
sessionToken. - Returns / side effects: Updated
AccountwithforumLawsDismissed: true. No request body. - Used by:
ForumLoader.
Function: markWalletIntroSeen
- Purpose: POST
/me/wallet-intro-seento record that the member finished or skipped the one-time wallet tour, so it is not shown again on any device. - Inputs:
sessionToken. - Returns / side effects: Updated
AccountwithwalletIntroSeen: true. No request body. Throws'Could not save the wallet tour'on a non-ok response; a 2xx body that failsaccountSchemathrows the schema error. - Used by:
WalletTour.
Function: postNotificationLevel
- Purpose: POST
/me/notification-levelwith JSON{ level }(all|active|mentions|none) and Bearer session. - Inputs:
session(bearer token),level(NotificationLevel). - Returns / side effects: Updated
Account. Throws'Could not save notification level.'on a non-ok response; a 2xx body that failsaccountSchemathrows the schema error. - Used by:
PushToggle.
Function: postHeartNotifications
- Purpose: POST
/me/heart-notificationswith JSON{ enabled }(boolean) and Bearer session. - Inputs:
session(bearer token),enabled(boolean). - Returns / side effects: Updated
Account. Throws'Could not save the heart setting.'on a non-ok response; a 2xx body that failsaccountSchemathrows the schema error.notifyHeartsis optional on the account so an older api body still parses. - Used by:
PushToggle.
Function: ReplyHeartSenders
- Purpose: Shared paid-hearts section under expanded forum replies. It prints the heading with the heart count, then one row per heart in api order.
- Inputs:
heartsfromGET /messages/:id/replies; each row hasaccountId,name, optionalusername, optionalrole, exactsats,createdAt, and the frozen fiat stringsamountUsd,amountChf,amountEur, andamountPhp(each a two-decimal string ornull). Also receives the current spot rate and the visitor's preferred fiat. - Returns / side effects: Nothing for an empty list. Otherwise each non-empty name links to
/members/{accountId}, tagged roles show the shared {@link ForumRoleTag} pill and hint, a deleted account uses the translated placeholder, and the row showsformatBitcoin(sats)plus the forum timestamp. The one fiat figure beside it is the frozen string for the visitor's preferred currency; only when that string isnullor missing doespreferredFiatSuffixuse the current spot. No I/O. - Used by:
ForumBoardandPublicMessageLoader.
Function: ForumRoleTag
- Purpose: The one clickable role pill used beside a member's name, a forum note or reply author, and a paid-heart sender. It replaces the copies that previously lived in
MemberIdentityPillsandForumBoard. - Inputs:
role(Role),expanded(whether this pill's sentence is open), andonToggle. - Returns / side effects: The pill for the given role, or nothing only for
basis(the one role without a tag). It is abuttonwitharia-expanded. The shown role is thatRolethroughforumTaggedRole. Pressing it callsonToggle; the caller owns which row is open. No network. - Used by:
MemberIdentityPills,ForumBoard, andReplyHeartSenders.
Function: ForumRoleHint
- Purpose: The translated explanation sentence for the shared role pill.
- Inputs:
role(Role). - Returns / side effects: The hint for the given role, or nothing only for
basis(the one role without a tag). No network. - Used by:
MemberIdentityPills,ForumBoard, andReplyHeartSenders.
Function: forumTaggedRole
- Purpose: Narrows a live account role to the six roles that show a forum tag: verified, moderator, fond, software_developer, initiator, and founder.
- Inputs: Role string from the api.
- Returns / side effects:
verified,moderator,fond,software_developer,initiator, orfounder;nullfor basis and unknown roles. No network. - Used by:
ForumRoleTag,ForumRoleHint,MemberIdentityPills, andForumBoardfor notes and replies when deciding whether to reserve the role-hint line.
Function: accountHeartSats
- Purpose: Reads the whole-sat amount one heart sends from an account.
- Inputs: Parsed account or
null. - Returns / side effects:
account.heartSats; a missing field on an older api body is 1. No I/O. - Used by:
useHeartTip,saveHeartSats,SettingsScreen.
Function: accountNotificationLevel
- Purpose: Read
account.notificationLevel ?? 'all'so omitted API fields still mean All. - Inputs: Parsed
Account(the field may be missing). - Returns / side effects:
'all','active','mentions', or'none'. No network. - Used by:
PushToggle.
Function: agreeToRules
- Purpose: POST
/me/rules-agreementwith Bearer and no JSON body. - Inputs:
sessionToken. - Returns / side effects: Updated
AccountwithrulesAgreedAtset. Throws'Could not save your agreement'on a non-ok response. - Used by:
RulesSetup.
Function: setUsername
- Purpose: POST
/me/usernamewith the unique LUD-16 local-part. - Inputs:
sessionToken,username, and optionalsundayWrite(enforcedefault, orsetupto omitTime-Zoneduring onboarding). - Returns / side effects: Updated
Account. ThrowsUsername is already in usewhen a 409 body is that sentence, otherwise'username-taken'on 409. Throws the format sentence when a 400 body is that sentence,'username-invalid'when a 400 body has no error string, and the raw api string for any other 400. Throws'username-request'on other failures. - Used by:
UsernameForm.
Function: giftsLightningAddress
- Purpose: Build the public
username@21.giftsaddress shown on profiles. It is the member's only address: payments to it settle in the member's own in-app wallet, and wallets resolve it at/.well-known/lnurlp/:username. Loopback hosts fall back to21.gifts. - Inputs:
username(nullable), optionalhostname. - Returns / side effects:
local@domainornull. No I/O. - Used by:
MemberProfileScreen,ViewProfileScreen,openCryptoPayQrValue,projectDonateAddress,WalletOwnAddress,ShopScreen,PosTillandPosAmount(viausePosTillState),WalletScreenView.
Function: projectDonateAddress
- Purpose: Address for donations to the 21.gifts project: the platform account's own in-app wallet address,
<platform username>@<app host>, built withgiftsLightningAddressfromgetPlatformUsername. - Inputs:
hostname— the host the page was requested on (21.gifts,dev.21.gifts,localhost); loopback hosts fall back to21.giftsas ingiftsLightningAddress. - Returns / side effects: The address, or
nullwhen the build sets no platform username. No I/O. - Used by: The landing
Homepage, which shows the#projectdonate section only when this is notnull.
Function: encodeLnurl
- Purpose: BIP-173 bech32-encode a cleartext URL with HRP
lnurland return it uppercase, for an Open CryptoPaylightningquery parameter. - Inputs:
urlstring. - Returns / side effects: Uppercase
LNURL1…. No I/O. - Used by:
openCryptoPayQrValue.
Function: openCryptoPayQrValue
- Purpose: Build the Open CryptoPay QR payload for a profile handle. Null when
giftsLightningAddressis null. - Inputs:
username(nullable), optionalhostname. - Returns / side effects:
https://<domain>/pl/?lightning=<LNURL>ornull. No I/O. The browser page for that URL is/pl. - Used by:
MemberProfileScreen,ViewProfileScreen,ShopStickerOverlay(draws the payload it is given as the sticker QR),PosScreen,WalletReceive,WalletOwnAddress,ShopScreen,PosTillandPosAmount(viausePosTillState),WalletScreenView,ShopStickerOverlay(sticker QR payload).
Function: buildShopStickerSvg
- Purpose: Printable shop-window sticker for one member as a standalone SVG document. The fixed artwork (orange band with the Bitcoin mark, ACCEPTED HERE / TINATANGGAP DITO, the English and Filipino scan text, the sari-sari shop with the 21.gifts sign) comes from
src/lib/shop-sticker-artwork.ts, whichscripts/build-shop-sticker-artwork.mjsgenerates with every glyph converted to an outline. Only three colours: orange#F99602, black, white. - Inputs:
qrValue— the member'sopenCryptoPayQrValue. Optionallang— default Filipino (English + Filipino artwork).spanish,german,french, andkikambareplace artwork indices 6–12.englishreplaces those indices with the English scan block only (no second headline). - Returns / side effects: SVG markup,
width="134.4mm",viewBox="0 0 1500 918". The QR is error correction H in byte mode, at least version 10 (57 modules; shorter payloads are padded up so the 4-module quiet zone to the band holds), with an odd-sized centre (13 of 57 modules, 15 of 61, …) cleared for the orange Open CryptoPay mark. No I/O. - Used by:
ShopStickerOverlay(preview<img>data URL),shopStickerBlob(SVG, PNG, JPG).
Function: buildShopStickerPdf
- Purpose: The same sticker as a one-page vector PDF for print, without a PDF library: the artwork paths (absolute M, L, C, Z) become PDF path operators, the QR modules become rectangles.
- Inputs:
qrValue— the member'sopenCryptoPayQrValue. Optionallang— same languages asbuildShopStickerSvg(default Filipino). - Returns / side effects: PDF 1.4 bytes (
Uint8Array), MediaBox 134.4 × 82.25 mm, no fonts, no images, exact xref offsets. No I/O. - Used by:
shopStickerBlob(formatpdf).
Function: shopStickerBlob
- Purpose: The shop-sticker file in the format the visitor picked.
- Inputs:
qrValue,format— one ofSHOP_STICKER_FORMATS(pdf,png,jpg,svg). Optionallang— same languages asbuildShopStickerSvg(default Filipino). - Returns / side effects:
Promise<Blob>:application/pdffrombuildShopStickerPdf;image/svg+xmlfrombuildShopStickerSvg; PNG / JPEG drawn from that SVG on a 3000 × 1836 canvas over white (JPEG quality 0.95). Rejects when the browser cannot load the SVG image, has no 2D canvas, or cannot encode it. The object URL used for the SVG image is always revoked. Nothing is sent to the api. - Used by:
ShopStickerOverlay(Download).
Function: shopStickerFileName
- Purpose: Download name for a member's sticker.
- Inputs:
handle(username@domainor a bare username),format. Optionallang— default Filipino, which keeps the historical unsuffixed name.english,spanish,german,french, andkikambainsert-english,-spanish,-german,-french, or-kikambabefore the extension. - Returns / side effects:
21gifts-shop-sticker-<username>[-language].<format>. The username is lowercased and reduced toa-z 0-9 . _ -(memberwhen nothing is left). No I/O. - Used by:
ShopStickerOverlay.
Function: shopStickerLangFromQuery
- Purpose: Selects the printable shop-sticker text language from a
langquery value. - Inputs:
value— rawlangquery value, or null when the parameter is absent. - Returns / side effects: Trimmed, case-insensitive.
kikamba/kam;filipino/fil; Spanishspanish/spanisch/es/espanol/español; Germangerman/deutsch/de; Frenchfrench/fr/francais/français/französisch/franzosisch; English-onlyenglish/en/none/keine. Null, blank, and unknown stayfilipino. That fallback is not the overlay default. No I/O. - Used by:
shopStickerLangFromLocation.
Function: shopStickerLangFromLocation
- Purpose: Selects the printable shop-sticker text language from the current page URL.
- Inputs: None. Reads the current
langquery viashopStickerLangFromQuery. - Returns / side effects: The language from that query (
english,spanish,german,french,filipino, orkikamba), orfilipinowhen the query is missing, unknown, orwindowis missing. No I/O. A missing query returningfilipinodoes not select the overlay; auto-open stays Kikamba-only. - Used by:
MemberProfileScreen(Kikamba still auto-opens the overlay).
Function: shopStickerLangInitial
- Purpose: First sticker language for the overlay. A known
langquery wins. Otherwise the visitor's UI language: English selects English only, Deutsch selects German, Español selects Spanish, Filipino selects Filipino. French and Kikamba are not UI languages. - Inputs:
locale— one ofen,de,es,fil. Whenwindowexists, also reads the currentlangquery. - Returns / side effects: A known alias (
kikamba/kam,fil/filipino, Spanish, German, French, or English-onlyen/none/keine) wins over the UI language. A missing, blank, or unknown query, and a missingwindow, use the UI language (en→english,de→german,es→spanish,fil→filipino). An explicit Filipino query is not treated as missing. No I/O. - Used by:
ShopStickerOverlay(first selection only).
Function: decodeLnurl
- Purpose: BIP-173 bech32-decode an
lnurlstring back to its cleartext URL. Not bech32m. - Inputs:
valuestring, either uniform case. - Returns / side effects: The URL, or
nullwhen the value is empty, mixed-case, the wrong HRP, or a bad checksum. No I/O. - Used by:
payLinkUsername.
Function: payLinkUsername
- Purpose: Read the username from an Open CryptoPay
lightningquery when it points at this site's/.well-known/lnurlp/path. - Inputs:
lightningLNURL string,pageHost(port and a leadingwww.are ignored; loopback and raw IPs expect21.gifts). - Returns / side effects: The decoded username, or
null. Does not call the network. - Used by:
PayLinkScreen.
Function: lnurlPayAddress
- Purpose: Name the receiver of an LNURL the way a pasted Lightning address is named. An LNURL whose URL is
https://<host>/.well-known/lnurlp/<name>is the address<name>@<host>on any host. - Inputs:
textas pasted or scanned: a bech32 LNURL (an optionallightning:prefix is removed, surrounding space is trimmed) or anhttps/pl/link that carries one in itslightningquery, as in a profile or point-of-sale QR. Only that LNURL names the address; the link's own host, port, and other query keys are not read. A link with another scheme or path givesnull. - Returns / side effects:
<name>@<host>with the name as it stands in the URL, ornullfor other text and for an LNURL that is not https, has a port other than 443, a query, or user info, has another path, or has a name an address cannot carry (only letters, digits,.,_,+,-). Pure; does not call the network. - Used by:
useWalletSend(recipient of the amount and confirm steps, and thesend-confirm-fixedpin).
Function: PayLinkScreen
- Purpose: Public payment card: the person's name, an exact satoshi amount, and one BOLT11 invoice.
- Inputs:
lightningquery string. - Returns / side effects:
PageChromewithProfileChromeLeft(wordmarkHomeWordmark) and a light language switcher. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. Renders the shop sticker's storefront for a real pay link, and the welcome glyph only when the link is not valid. AfterGET /pay/:username, shows the name and amount form, or that open till. Continue opens a shop payment and then shows it, or in the fallback cases mints and shows the active payment (locked sats, the default fiat when the spot rate is usable, and Pay, no amount field). A till's shop payment shows the figure stored on the charge under the bitcoin (committedFiatFigure: a typed pair wins over the visitor snapshot). A missing stored figure shows the current spot beside the bitcoin and is not written back. An amount typed in bitcoin on the opened shop payment shows onlyformatBitcoin. The minted fallback for that amount still shows the current spot beside the bitcoin, and that spot is not stored. An amount typed in fiat shows the trimmed draft and the preferred fiat captured at Continue, formatted byformatDefinedGoalAmount(every typed digit, padded to two decimals, never rounded). docs/fiat-amounts.md requires an open till charge to show the figure the shop operator typed, to the shop and to the payer: typing 12.00 shows 12.00, never 12.01 or 11.99, and the payer's display currency does not replace it. A till charge shown in the minted view (the plain Lightning request, a pay link that cannot be read, or a failed mint) still showsChargeFiat: the stored figure, or the current spot when none was stored. OneuseSpotRatecall, made once the pay profile is loaded, feeds the amount field while the payer is still typing, the minted view'sChargeFiatline, and a till shop payment that has no stored figure, so creating the payment does not ask for the rate again. Pay (aria Pay with a Bitcoin wallet app) is the width of the invoice QR plate, centered, not the page column. With an issued invoice, Pay setswindow.location.hrefto the genericlightning:link fromlightningHref, so the device opens whichever Bitcoin wallet app handles that scheme; no particular wallet is named and there is no wallet icon. Before the invoice exists Pay is disabled, except after a failed create of a shown payment, when it requests that invoice again: a failed mint for a plain-Lightning till mints again, a till whose pay link could not be read reads it again, and a failed Lightning detail is read again; a Lightning-detail load superseded by a newer load is discarded whether it succeeds or fails. Afailedstart shows no Pay: the amount form stays, and Continue callsopenShopPaymentagain with the amount in the field. The page keeps theambiguousAtMsthatopenShopPaymentreturns per username, in a map held for the lifetime of the page, and passes it to every later Continue of the same pay link, so a refusal after an unknown outcome waits for the 20 s rule and reads the pay link instead of minting; only anopenedstart clears it, and switching to anotherlightningvalue and back keeps it. Each Continue has its ownAbortController, which the pay-link load effect aborts when the page leaves the pay link (another link, a reload, or unmount), so the repeat and the 20 s wait stop (the wait is the start-waiting variant); anabortedstart shows nothing, but itsambiguousAtMsis still stored first, so a call that was running when the page left counts as unknown from that moment. The form stays disabled through the wait. Off a smartphone the invoice QR shows above Pay. A smartphone does not show it (isSmartphoneUserAgent, not viewport), before or after the payment is active. A newlightningvalue clears the previous person, including an invoice that is still being created. A positive fiat amount that the spot rate cannot price in the preferred fiat (typed before that fiat changed to one without a price) shows an alert that names that currency. An open till reads the pay link first (fetchShopPayLink): an OpenCryptoPay pay request shows its shop payment with the invoice fromfetchShopInvoiceand never mints; a pay request whoseamountSatsdiffers from the charge'samountSats(the till replaced its charge betweenGET /pay/:usernameand the pay-link read) is not shown with the old sats: the page loads the pay profile again (reloadNonce) once per payment id, and if the pay request still names other sats it shows Could not create the invoice. and Pay reads the pay link again; the time left of a till's shop payment counts down to that charge'sexpiresAtfromGET /pay/:username, because no answer the page reads carries the payment's own window end (quote.expirationis the quote's end, which is the window end only for a Lightning-only quote, andGET /lnurlp/wait/:paymentnames only the BOLT11'sinvoiceExpiresAt), and the charge has no id the page could compare with the payment; so when the till replaced its charge with one for the same sats between that read and the pay-link read, the page shows the new charge's payment with the old charge's time left, which ends earlier than the real window (the payment stays shown and payable; only its time left disappears early); only the plain Lightning request mints the till's amount as before; a pay link that cannot be read shows Could not create the invoice., and Pay reads it again and mints only for the plain Lightning request. Continue opens a shop payment withopenShopPayment:chargeloads the page again,invoicemints withPOST /pay/:username/invoice,failedshows This payment could not be started. Try again. without minting,abortedis dropped, andopenedreads the pay link: only a pay request whosequote.paymentis another payment, or whoseamountSatsdiffers from the entered sats, leaves the locked view and shows the amount form with Another payer entered an amount first. Enter yours again., so the entered sats never show beside an invoice for other sats; on that first read the plain Lightning request counts as replaced too (something else already ended the payment), while a pay link that cannot be read keeps the opened id without minting, follows its status, and reads the pay link again every 2 s until it names that payment (or another one) or the status is no longeropen; a later read that names that payment for other sats counts as replaced the same way; on those later reads the plain Lightning request (also the answer once the payment was accepted or its window passed) keeps the payment and the status tells which. A shown shop payment lists one line per stablecoin method and asset with the quote's time left and the OpenCryptoPay wallet hint, reads the pay link again when the quote runs out (the lines, the quote's time left, and the scan hint are hidden once the quote has run out, until a read returns a new quote; a failed read, or a quote whose expiry has already passed, is read again after 2 s and keeps the payment; another payment or the plain request hides the lines, the quote's time left, and the scan hint but keeps the payment), and followswaitShopPayment(first withoutsince, then withsinceset to the lastpaymentStatus; after a valid answer that is not final it asks again at once, because the api holds a read withsincewhile the status is unchanged, and it pauses 2 s only after a read that failed or could not be read, amissinganswer whose pay-link read failed, or amissinganswer after the one restart; the pause is cleared when the page leaves the payment): Waiting for payment…, On its way, Paid ✓, or Ended (pay.ended). Only On its way, Paid ✓, and Ended (accepted,paid,ended) hide the invoice QR, Pay, and the stablecoin lines; a window that ran out alone hides only its time left while the payment isopen. Whenstatusis notPendingthe page stops the status reads and the quote refetch and keeps Paid ✓ on screen; a finalendedpayment (closed unpaid) is dropped the way an expired minted invoice is, with no alert and the entered amount kept, so the amount form shows again, except that a till still in its window reads its pay link again (mints only for the plain Lightning request; a pay request that still names the closed payment shows Could not create the invoice. and Pay reads again); only a 404 with the api's error body (missing) starts the payment again from the pay link (fetchShopPayLink), at most once per payment id, for a till's payment and an entered amount alike: a pay request that still names that payment for its sats keeps the payment on screen with that pay request, reads its invoice again, and followswaitShopPaymentfrom the start (withoutsince); another payment, other sats, or the plain Lightning request loads the page again for a payment shown for the till's charge (reloadNonce, then the till's flow) and, for a payment the payer opened with Continue, shows the amount form with Another payer entered an amount first. Enter yours again.; which of the two a payment is, is fixed when it is shown, because a till charge that ran out on the page stays in the loaded profile while the payer opens an amount of their own; a pay link that cannot be read keeps the payment, uses up nothing, and the nextmissingreads it again; an answer of that read that arrives after the page left the payment (another link, a reload, or unmount) is dropped. The pay link of an opened payment is read again only while that payment isopen. No forum and no auth gate. - Used by:
PayLinkPage.
Function: PayLinkPage
- Purpose:
/plserver page. Reads thelightningquery and rendersPayLinkScreen. - Inputs:
searchParamspromise with an optionallightningstring or array. - Returns / side effects: The payment screen. Does not 404 when the query is missing.
- Used by: The App Router at
/pl.
Function: fetchShopPayLink
- Purpose: Read the shop's pay link (
GET /.well-known/lnurlp/:usernameon this site, withouttimeout,cache: 'no-store') and tell whether it carries a shop payment. - Inputs:
usernameof the shop. - Returns / side effects:
{ kind: 'payment', request }for an OpenCryptoPay pay request (standardisOpenCryptoPay, orpossibleStandardscontains it) withcallback,quote.id,quote.expiration, andquote.payment;request.amountSatsis the payment's whole sats, read from the pay request itself: the BTC amount of theLightningentry oftransferAmounts, orrequestedAmount(assetBTC) when that entry has no readable one, read as text withjsonAmountTextand converted exactly withscaleDecimalTo8(no float; a JSON number such as2.1e-7counts as0.00000021, while a string in exponent form, a number with more than 8 decimals, zero, or more than a safe integer is unreadable);request.linesholds one entry per method and asset oftransferAmounts, except the Lightning entry and an entry withavailablefalse, with its amount fromjsonAmountText(a string exactly as written, a number as plain decimal text; an asset whose amount it cannot read is left out).{ kind: 'plain' }only for the plain Lightning pay request (LUD-06):tagpayRequest, a stringcallback, safe-integerminSendableandmaxSendablewith 0 <minSendable≤maxSendable, and a stringmetadata.{ kind: 'error' }for a failed request, an error status, an unreadable body, any other readable body (for example{}or an error body with status 200), or an OpenCryptoPay body without a usable quote or without a readable bitcoin amount. Never throws. - Used by:
PayLinkScreen(open till, the check afteropenShopPayment, the refetch when a quote runs out, and the one restart after the wait route'smissing) andopenShopPayment(the read after a refusal in the ambiguous state).
Function: jsonAmountText
- Purpose: Turn an
amountof a pay link's JSON into text without the exponent form thatJSON.parseandStringgive small numbers (0.00000021is parsed as2.1e-7), so 1–99 sats written as a JSON number stay readable. - Inputs:
value, theamountfield as parsed from the body. - Returns / side effects: A string exactly as written. A finite, non-negative number with at most 8 decimals (its
toFixed(8)text reads back as the same number) as plain decimal text without trailing zeros:2.1e-7→0.00000021,12.5→12.5,12→12.nullfor a number with more decimals, a negative,NaN, or infinite number, and any other value. Pure. - Used by:
fetchShopPayLink(the BTC amount of the pay request and the amount of each stablecoin line).
Function: fetchShopInvoice
- Purpose: Read a shop payment's BOLT11 from the callback's Lightning detail, so the page never mints a second invoice for a payment that has one.
- Inputs:
requestfromfetchShopPayLink; the call is<callback>?quote=<quote id>&method=Lightning&asset=BTCwithcache: 'no-store'. - Returns / side effects: The
prstring, ornullfor an error status (for example an expired quote), a missing or emptypr, a failed request, or a callback that is not a URL. Never throws. - Used by:
PayLinkScreen(after showing a shop payment, and Pay after a failed read).
Function: openShopPayment
- Purpose: Open a shop payment for an amount the payer entered (
POST /pay/:username/paymentwith{ amountSats }), and keep the page's ambiguous state of the contract's "Payment page" section. - Inputs:
usernameof the shop, the wholeamountSats, andoptions:ambiguousAtMs(the value the previous call for this pay link returned, ornull) and the page's abortsignal. - Returns / side effects:
{ start, ambiguousAtMs }. A request that takes longer thanSHOP_PAYMENT_START_TIMEOUT_MS(15 s, above the api's 8 s creation budget) is aborted, which the api sees as a disconnect; it, a failed request, a 200 without a usable payment id, a 409 whose body is not a JSON object (not JSON, or JSON such asnull, a string, or an array; it may be a till'spayment_open), and any 5xx other than 503stablecoin_unavailableare unknown, because a payment may have been opened. Fresh (ambiguousAtMsnull): a 200 with a non-empty payment id is{ kind: 'opened', payment, expiresAt }(expiresAtisnullwhen the answer has no readable window end); 409payment_openis{ kind: 'charge' }; 503stablecoin_unavailableor any other 4xx (a 409 only with a readable body of another code) is{ kind: 'invoice' }(mint withPOST /pay/:username/invoice); an unknown outcome setsambiguousAtMsto the time that call ended and repeats the same call once, handled as in the ambiguous state. In the ambiguous state (the repeat and every later call, for any amount):openedclearsambiguousAtMs;chargekeeps it; another unknown outcome is{ kind: 'failed' }and movesambiguousAtMsto its end; a 503stablecoin_unavailableor another 4xx waits untilambiguousAtMsplusSHOP_PAYMENT_RECHECK_DELAY_MS(20 s; no wait when that has passed), then reads the pay link withfetchShopPayLink:plain(no open amount) isinvoice, a pay request orerrorisfailed. Whensignalaborts, the result is{ kind: 'aborted' }: no repeat, no wait, and no pay-link read follow. An abort while a request is running (also one whose answer arrived but was not used) leaves its outcome unknown, soambiguousAtMsbecomes the time of that abort; an abort before a request is sent, or during the wait or the pay-link read, keeps it as it was. Never mints and never throws. - Used by:
PayLinkScreen(Continue).
Function: waitShopPayment
- Purpose: Read a shop payment's status from
GET /lnurlp/wait/:payment, which the api serves without an app route. - Inputs:
paymentid,since(the lastpaymentStatusseen, ornullfor the first read, which answers at once), and an optional abortsignal. - Returns / side effects:
{ status, paymentStatus }, wherestatusis the DFX status (Pendinguntil the payment is paid or closed) andpaymentStatusisopen,accepted,paid, orended;'missing'for a 404 with the api's error body (statusERROR,reasonNot found: the api does not know the payment);nullfor any other 404 (for example a page that did not reach the api) or error status (for example 429), an unknownpaymentStatus, an unreadable body, or a failed or aborted request. Withsince, the api waits while the status still equals it. - Used by:
PayLinkScreen(status line of a shown shop payment).
Function: translate
- Purpose: Look up a catalog key, expand
{count, plural, one {…} other {…}}(one whencountis 1, otherwise other;#in the chosen branch becomes that count), then replace{name}placeholders fromvars. - Inputs:
catalog(Messages),key(MessageKey), optionalvarsmap of string/number values. A plural header needs a finitecount. - Returns / side effects: Interpolated string. A broken plural header is left in place. Throws on a missing key, a plural header without a finite
count, or a missing{name}— no silent English fallback. - Used by: Server pages (
Home, login headings,NotFound,MarketingFooter,HandbookPage) and thethelper fromLocaleProvider/useTranslations.
Function: useAuthStore
- Purpose: Zustand auth store for active
session+account, a valid but held-backlockedSession, andwrongAccount. Hydration is explicit (no module-init storage read). - Inputs: Hook. Methods
setAuth,setAccount,setLockedSession,lockSession,noteLockedPasskeyMissed,dismissLockedPasskeyNotice,clearAuth,setWrongAccount, andclearWrongAccount. - Returns / side effects: Auth state object.
setAuthpersists the token, activates the account, clearslockedSession, and resetswrongAccount.setLockedSessionkeeps the token in storage but makes activesessionandaccountnull, and keeps the account's name, else its username, aslockedNameand its wallet passkey id aslockedCredentialId.lockSessionmoves the current token tolockedSession(and its account's display name tolockedName, its wallet passkey id tolockedCredentialId) without removing it from storage.noteLockedPasskeyMissedkeeps the held-back token aslockedPasskeyMissed, so that session's next Log in offers every passkey, also after the card mounts again, and setslockedPasskeyNotice, whichdismissLockedPasskeyNoticeclears when the next login run starts.setAuthandclearAuthresetlockedName,lockedCredentialId,lockedPasskeyMissed, andlockedPasskeyNotice.clearAuthclears the tab phrase and persisted token, bumps and clears the unread app badge, and drops active and held-back auth; it does not resetwrongAccount.setLockedSessionandlockSessionalso bump the home-screen badge epoch and clear the badge, as for a signed-out visitor. - Used by:
LoginCard,WalletLoginCard,OnboardingGate,NameSetup,RulesSetup,WelcomeScreen,MenuAccountHeader,LoanRepayScreen,LogoutButton,useHydrateSession,usePasskeyLogin,useWalletOpen,useActiveSession,NameForm,useWallet,useMyLoans,useLoanRepay,rememberPhraseFromPrf,unlockWalletPhrase,useWalletPay,useWalletSend,WalletPay,WalletSend,InteractionLog,reportWallet, the interaction log (logInteraction,flushInteractions,logLogout), andpayFromWallet'ssend(the session of a wallet send).
Function: useTranslations
- Purpose: Client hook returning
{ locale, t }from the nearestLocaleProvider. - Inputs: None (React context).
- Returns / side effects: Active locale and a
t(key, vars?)bound to that catalog. Throws if used outsideLocaleProvider. - Used by:
MarketingHeader,LanguageSwitcher,LoginCard,ForumBoard,NameForm,HandbookCopyLink,NameSetup,RulesSetup,WelcomeScreen,LoansCard,LoanRepayScreen,MenuAccountHeader,WalletOwnAddress,LogoutButton,WalletBalance,WalletPay,PaySheet,AddBitcoinButton,WalletSend.
Function: useNumberFormat
- Purpose: Client hook returning
{ numberFormat, setNumberFormat }from the nearestNumberFormatProvider. Call sites that format counts or money take this hook's style, not UI locale. - Inputs: None (React context).
- Returns / side effects: Active
NumberFormatStyleand a setter that writes thenumberFormatcookie. ThrowsuseNumberFormat must be used within NumberFormatProviderwhen used outside the provider. - Used by:
NumberFormatSwitcher,ForumBoard,StatsDashboard,DayLoader,AccountActivityChart,PublicMessageLoader,WalletBalance,WalletPay,WalletSend,LoansCard,LoanRepayScreen,MenuAccountHeader.
Function: DELETE
- Purpose: Shared App Router DELETE export name.
/me/push-subscriptionsre-exportsproxyMePushSubscriptionsDelete;/forum/messages/[id]re-exportsproxyMessagesDelete;/pos/chargere-exportsproxyPosDelete;/me/previous-wallets/[sparkPubkey]callsproxyMePreviousWalletDeletewith the asyncsparkPubkey;/me/held-shares/[id]callsproxyMeHeldShareDeletewith the asyncid. - Inputs: Incoming
Request. For/forum/messages/[id], also async routeparamswith the message id; for/me/previous-wallets/[sparkPubkey], the wallet key; for/me/held-shares/[id], the box id. - Returns / side effects: Upstream api
Response. - Used by: Same-origin
deletePushSubscription/disablePush, same-origin forum moderation delete (deleteMessage), dropping a previous wallet (deletePreviousWallet), and deleting a held-share box (deleteHeldShareBox).
Function: PATCH
- Purpose: Shared App Router PATCH export name.
/forum/messages/[id]/placere-exportsproxyMessagesPlacePatch./forum/messages/[id]/shop-accountre-exportsproxyMessagesShopAccountPatch./forum/messages/[id]/textre-exportsproxyMessagesTextPatch./forum/messages/[id]/photosre-exportsproxyMessagesPhotosPatch. - Inputs: Incoming
Request. For/forum/messages/[id]/place,/forum/messages/[id]/shop-account,/forum/messages/[id]/text, and/forum/messages/[id]/photos, also async routeparamswith the message id. - Returns / side effects: Upstream api
Response. - Used by: Same-origin forum staff place save (
setMessagePlace), shop-account save (setMessageShopAccount), shop-note text save (setMessageShopText), and shop-note photo save (setMessageShopPhotos).
Function: AboutPage
- Purpose: Next.js page for
/about,/en/about,/de/about,/es/about, and/fil/about. What 21.gifts stands for, Matthew 10:8, 1 John 3:18, and a CTA into/welcome. - Inputs: None. Calls
getRequestLocale()and reads copy from the catalog viatranslate. - Returns / side effects: The about screen with a link to
/welcome. - Used by: Routes
/about,/en/about,/de/about,/es/about, and/fil/about.
Function: LegalPage
- Purpose: Next.js page for
/legal(imprint and privacy). No published email — contact is in-app via/contact. The Privacy Policy states what is true about the website (no advertising, no analytics scripts, the cookies it sets, the session token inlocalStorage, that recovery words and shares stay in the open tab's memory while an account is recovered or a balance moved, and that a Social Recovery part kept for another member is encrypted in the browser with a key from the keeping member's own 12 words and stored with their account, unreadable to 21.gifts, until they delete it) and its Wallet and payment data paragraph points to the Wallet and data section of the Terms of Use instead of promising the opposite. - Inputs: None.
- Returns / side effects: The legal screen with links to
/contact,/terms, and/terms#wallet-and-data. - Used by: Route
/legal.
Function: TermsPage
- Purpose: Next.js page for
/terms: the Terms of Use with the Wallet and data section (anchor#wallet-and-data) and five numbered clauses, each with a short heading, plus the last-updated date 6 October 2026. - Inputs: None. Calls
getRequestLocale()and reads every string from the catalog viatranslate(terms.title,terms.lastUpdated,terms.heading,terms.clause1Title…terms.clause5Title,terms.clause1…terms.clause5), so the page renders in German, English, Spanish, or Filipino. Englishtitle/descriptionmetadata is the documented exception. - Returns / side effects: The terms screen: an
h1, the date line, anh2, and an ordered list of the five clauses. No links, no state. - Used by: Route
/terms; linked fromLegalPage,MarketingFooter, andRulesSetup(last chapter).
Function: MarketingFooter
- Purpose: Footer for marketing pages: wordmark, localized section links including About, legal, Terms of Use (
/terms), living-room rules, GitHub, and a quiet Matthew 10:8 verse. - Inputs: None. Resolves locale via
getRequestLocaleand reads copy from the catalog viatranslate. - Returns / side effects: Footer element.
- Used by:
MarketingLayout,NotFound.
Function: MarketingHeader
- Purpose: Sticky marketing header with one top-left arrow (
ProfileChromeLefttone="dark") besideHomeWordmark(tone="dark"). The wordmarkpublicHrefis/on the unprefixed root and the language home otherwise; a hydrated session sends the wordmark to/welcome. The arrow returns to the previous in-app view, or/welcomewhen this tab has none. The wordmark is not that control. On/and on the language home the header passeshideHistoryArrowandhideOverride, so it shows no back arrow at all. Section nav is How, Happyland, Why, FAQ, About 21.gifts, Stats, and Handbook, plus accent Log in,PwaInstalltone="dark"placement="header", an always-visibleLanguageSwitcher(tone="dark"), and a mobile menu toggle. Happyland links to the language home plus#happyland. ThemeSwitcher and NumberFormatSwitcher are not mounted here. - Inputs: None. Internal open state. Reads copy via
useTranslationsand the path viausePathname. - Returns / side effects: Header element; toggles nav on small screens.
LanguageSwitcherstays visible when the hamburger is closed. Install control staysnulluntil after mount when an offer applies. - Used by:
MarketingLayout,NotFound(no extra props).
Function: MarketingLayout
- Purpose: Async dark full-page shell for
/,/about,/legal,/terms,/handbook, and/stats. - Inputs:
children. AwaitsMarketingFooter()(does not render it as a JSX child). - Returns / side effects: Wrapper div with header, page, and awaited footer.
- Used by: Marketing route group.
Function: NotFound
- Purpose: Async app-wide 404 screen with marketing chrome and localized body copy.
- Inputs: None. Calls
getRequestLocale()for body copy; awaitsMarketingFooter(). - Returns / side effects: 404 element with
MarketingHeader(the only back control is that header arrow) and awaited footer (not rendered as JSX child). No Back home button. - Used by: Next.js
not-found.tsx.
Function: POST
The /me/wallet/counterparties route re-exports proxyMeWalletCounterpartiesPost for the payment counterparty lookup.
- Purpose: Shared App Router POST export name.
/me/namere-exportsproxyMeNamePost;/me/locationre-exportsproxyMeLocationPost;/me/forum-laws-dismissedre-exportsproxyMeForumLawsDismissedPost;/me/wallet-intro-seenre-exportsproxyMeWalletIntroSeenPost;/me/notification-levelre-exportsproxyMeNotificationLevelPost;/me/heart-notificationsre-exportsproxyMeHeartNotificationsPost;/me/rules-agreementre-exportsproxyMeRulesAgreementPost;/me/push-subscriptionsre-exportsproxyMePushSubscriptionsPost;/me/wallet-backup-seenre-exportsproxyMeWalletBackupSeenPost;/me/wallet/reportre-exportsproxyMeWalletReportPost;/me/wallet/heartsre-exportsproxyMeWalletHeartsPost;/me/eventsre-exportsproxyMeEventsPost;/lnurlpay/[pubkey]callsproxyLnurlpayRegisterPostand/lnurlpay/[pubkey]/recovercallsproxyLnurlpayRecoverPostwith the asyncpubkey;/me/passkey-renew/reportre-exportsproxyMePasskeyRenewReportPost;/me/passkey-renew/ackre-exportsproxyMePasskeyRenewAckPost;/auth/passkey/{register,authenticate,replace,seed,recovery}/{begin,finish}re-export the ten passkey proxy POSTs;/lnurlpay/[pubkey]/transfercallsproxyLnurlpayTransferPostwith the asyncpubkey;/forum/messagesre-exportsproxyMessagesPost;/messages/[id]/invoicere-exportsproxyMessagesInvoicePost;/messages/[id]/repaymentre-exportsproxyMessagesRepaymentPostfor both no-body and{ amount }requests;/messages/[id]/repayment/dueand/closere-export their matching repayment proxy helpers;/conversationsre-exportsproxyConversationsPost;/conversations/[id]re-exportsproxyConversationPost;/conversations/[id]/invoicere-exportsproxyConversationInvoicePost;/conversations/[id]/readre-exportsproxyConversationReadPost;/forum/notifications/read-allre-exportsproxyNotificationsReadAllPost;/forum/notifications/read-by-messagere-exportsproxyNotificationsReadByMessagePost;/forum/notifications/read-visiblere-exportsproxyNotificationsReadVisiblePost;/forum/notifications/[id]/readre-exportsproxyNotificationReadPost;/contact/submitre-exportsproxyContactPost;/lnurl/pay-requestre-exportsproxyLnurlPayRequestPost;/lnurl/invoicere-exportsproxyLnurlInvoicePost;/translatere-exportsproxyTranslateNotePostwith JSON{ messageId, target };/conversations/[id]/messages/[messageId]/translatere-exportsproxyTranslateConversationMessagePostwith JSON{ target };/trust/verifyre-exportsproxyTrustVerifyPost;/trust/propose-moderatorre-exportsproxyTrustProposeModeratorPost;/trust/confirm-moderatorre-exportsproxyTrustConfirmModeratorPost;/trust/reject-moderatorre-exportsproxyTrustRejectModeratorPost;/trust/appoint-moderatorre-exportsproxyTrustAppointModeratorPost;/funding/applyre-exportsproxyFundingApplyPost;/funding/withdrawre-exportsproxyFundingWithdrawPost;/funding/trialre-exportsproxyFundingTrialPost;/funding/admitre-exportsproxyFundingAdmitPost;/funding/rejectre-exportsproxyFundingRejectPost;/funding/daily-roster/commentre-exportsproxyFundingDailyRosterCommentPost;/funding/daily-roster/paymentsre-exportsproxyFundingDailyRosterPaymentsPost;/funding/daily-roster/recipientsre-exportsproxyFundingDailyRosterRecipientsPost;/funding/daily-roster/recipients/updatere-exportsproxyFundingDailyRosterRecipientsUpdatePost;/funding/daily-roster/recipients/deletere-exportsproxyFundingDailyRosterRecipientsDeletePost./pos/chargere-exportsproxyPosPost. HTML/posis the till page, not a POST proxy. HTML/messagesis the inbox page, not a POST proxy. - Inputs: Incoming
Request. - Returns / side effects: Upstream api
Responseon api proxies;/translatereturns{ translatedText, cached }or 400/404/503/502 from the 21.gifts api. - Used by: Same-origin name save, location save (
POST /me/location), forum laws dismiss, wallet tour seen (POST /me/wallet-intro-seen), notification-level save (POST /me/notification-level), heart-notification save (POST /me/heart-notifications), living-room rules agreement (POST /me/rules-agreement), Web Push subscribe (POST /me/push-subscriptions), recovery-phrase backup-seen (POST /me/wallet-backup-seen), wallet data report (POST /me/wallet/report), heart lookup (POST /me/wallet/hearts), interaction log batch (POST /me/events), renew report (POST /me/passkey-renew/report), renew acknowledgement (POST /me/passkey-renew/ack), passkey begin/finish (register, authenticate, replace, seed, and social recovery), forum message create (POST /forum/messages), payable-reply invoice (POST /messages/[id]/invoice),postRepaymentDue(POST /messages/[id]/repayment/due),prepayLoan(POST /messages/[id]/repayment),closeLoan(POST /messages/[id]/repayment/close), inbox open (POST /conversations) and reply (POST /conversations/[id]), inbox invoice (POST /conversations/[id]/invoice), mark-one conversation (POST /conversations/[id]/read), mark-all notifications (POST /forum/notifications/read-all), mark-by-message (POST /forum/notifications/read-by-message), mark-visible (POST /forum/notifications/read-visible), and mark-one (POST /forum/notifications/[id]/read), in-app contact (POST /contact/submit), the outside-address pay request and invoice of the wallet send flow (POST /lnurl/pay-request,POST /lnurl/invoice),translateNoteviaPOST /translate,translateConversationMessageviaPOST /conversations/[id]/messages/[messageId]/translate, staff Trust Chain actions (POST /trust/verify,POST /trust/propose-moderator,POST /trust/confirm-moderator,POST /trust/reject-moderator,POST /trust/appoint-moderator), grant apply (POST /funding/apply), leaving the grant (POST /funding/withdraw), staff funding decisions (POST /funding/trial,POST /funding/admit,POST /funding/reject), and daily-roster saves (POST /funding/daily-roster/comment,POST /funding/daily-roster/payments,POST /funding/daily-roster/recipients,POST /funding/daily-roster/recipients/update,POST /funding/daily-roster/recipients/delete). The in-app wallet's address registration (POST /lnurlpay/[pubkey], asyncpubkey,proxyLnurlpayRegisterPost) and address lookup (POST /lnurlpay/[pubkey]/recover,proxyLnurlpayRecoverPost) forward its signed JSON body and signature headers; the new wallet's address claim during a social recovery (POST /lnurlpay/[pubkey]/transfer,proxyLnurlpayTransferPost) forwards its JSON body signed by both wallets.
Function: PUT
- Purpose: Shared App Router PUT export name.
/me/aboutre-exportsproxyMeAboutPut;/me/walletre-exportsproxyMeWalletPut;/me/recovery-sharere-exportsproxyMeRecoverySharePut;/me/held-shares/[id]callsproxyMeHeldSharePutwith the asyncid;/fond/deposit-addressre-exportsproxyFondDepositAddressPut. - Inputs: Incoming
Requestwith Bearer session and JSON{ text }(/me/about),{ sparkPubkey }(/me/wallet),{ sparkPubkey, share }(/me/recovery-share),{ ciphertext }with the async boxid(/me/held-shares/[id]), or{ address }(/fond/deposit-address, Bearer session of the Fond account). - Returns / side effects: Upstream api
Response. - Used by: Same-origin About me save (
PUT /me/about/putAboutMe), the wallet key claim (PUT /me/wallet/putWallet), the social recovery share upload (PUT /me/recovery-share/putRecoveryShare), a held-share box (PUT /me/held-shares/[id]/putHeldShareBox), and the Fond wallet's deposit address (PUT /fond/deposit-address/putFondDepositAddressthroughFondDepositSync).
Function: proxyApiRequest
- Purpose: Forwards an App Router request to
getApiUrl()+ path. Copies query, authorization / content-type / time-zone / content-length / user-agent / origin / range headers, and the in-app wallet'sx-breez-signature/x-breez-timestamp. Multipart POST/PUT/PATCH/DELETE bodies stream withduplex: 'half'whenrequest.bodyis non-null andContent-Lengthis not0; JSON and other bodies are buffered (arrayBuffer) so Node fetch does not throw. Empty POSTs omit body and duplex. Copies content-type / content-length / content-range / accept-ranges / cache-control / content-disposition from the upstream response. Also passes the browser'sx-app-build(the bundle's build id on passkey begin and finish) through unchanged; the proxy never sets it, so an outdated tab cannot hide behind the server's newer build. - Inputs:
request,apiPathbeginning with/, and optionaloptions.forwardAbort: whentrue, the upstream fetch getsrequest.signal, so a client that disconnects aborts the api request (the api then sees the disconnect); off by default, so every other route keeps running its upstream request as before. - Returns / side effects: Upstream
Response(status + selected headers + streamed body), or 502 JSON if fetch throws (also when a forwarded abort ends it). - Used by: All same-origin api proxy route handlers; only
POST /pay/[username]/paymentpassesforwardAbort.
Function: proxyTrustChainGet
- Purpose: Same-origin Bearer proxy helper for api
GET /trust-chain. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/trust/graph.
Function: proxyTrustProposalsGet
- Purpose: Same-origin Bearer proxy helper for api
GET /trust/proposals. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/trust/proposals.
Function: proxyFundingApplyPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/apply. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/apply.
Function: proxyFundingWithdrawPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/withdraw, the same proxy asproxyFundingApplyPost. - Inputs: Incoming
Request(Bearer session, no body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest, status and body unchanged (200{ funding }, 401, 403, 409, 503, or 404 while the api does not have the endpoint). - Used by: Route POST
/funding/withdraw.
Function: proxyShopActivityShopsGet
- Purpose: Same-origin Bearer proxy helper for api
GET /shops/activity/shops. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/shops/activity/shops.
Function: proxyFundingPayoutDaysGet
- Purpose: Same-origin Bearer proxy helper for api
GET /funding/payout-days. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/funding/payout-days.
Function: proxyFundingApplicationsGet
- Purpose: Same-origin Bearer proxy helper for api
GET /funding/applications. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/funding/applications.
Function: proxyFundingDailyRosterGet
- Purpose: Same-origin Bearer proxy helper for api
GET /funding/daily-roster. Forwards the incoming Authorization header. - Inputs: Incoming
Request(Bearer session). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/funding/daily-roster.
Function: proxyFundingDailyRosterCommentPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/commentwith JSON{ comment }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/comment.
Function: proxyFundingDailyRosterPaymentsPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/paymentswith JSON{ enabled }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/payments.
Function: proxyFundingDailyRosterRecipientsPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/recipientswith JSON{ accountId, amountUsd }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/recipients.
Function: proxyFundingDailyRosterRecipientsUpdatePost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/recipients/updatewith JSON{ address, amountUsd }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/recipients/update.
Function: proxyFundingDailyRosterRecipientsDeletePost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/recipients/deletewith JSON{ address }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/recipients/delete.
Function: proxyFundingDailyRosterModeratorsPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/moderatorswith JSON{ accountId, amountUsd }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/moderators.
Function: proxyFundingDailyRosterModeratorsUpdatePost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/moderators/updatewith JSON{ address, amountUsd }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/moderators/update.
Function: proxyFundingDailyRosterModeratorsDeletePost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/moderators/deletewith JSON{ address }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/moderators/delete.
Function: proxyFundingDailyRosterModeratorsPaymentsPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/daily-roster/moderators/paymentswith JSON{ enabled }. - Inputs: Incoming
Request(Bearer session and JSON body). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/funding/daily-roster/moderators/payments.
Function: proxyFundingApplicationGet
- Purpose: Same-origin Bearer proxy helper for api
GET /funding/applications/:accountId. - Inputs: Incoming
Request(Bearer session) andaccountId. - Returns / side effects: Upstream
ResponseviaproxyApiRequest(id encoded). - Used by: Route GET
/funding/applications/[accountId].
Function: proxyFundingTrialPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/trial. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/funding/trial.
Function: proxyFundingAdmitPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/admit. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/funding/admit.
Function: proxyFundingRejectPost
- Purpose: Same-origin Bearer proxy helper for api
POST /funding/reject. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/funding/reject.
Function: proxyTrustVerifyPost
- Purpose: Same-origin Bearer proxy helper for api
POST /trust/verify. - Inputs: Incoming
Request(JSON{ accountId, confirmedName }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/trust/verify.
Function: proxyTrustProposeModeratorPost
- Purpose: Same-origin Bearer proxy helper for api
POST /trust/propose-moderator. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/trust/propose-moderator.
Function: proxyTrustConfirmModeratorPost
- Purpose: Same-origin Bearer proxy helper for api
POST /trust/confirm-moderator. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/trust/confirm-moderator.
Function: proxyTrustRejectModeratorPost
- Purpose: Same-origin Bearer proxy helper for api
POST /trust/reject-moderator. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/trust/reject-moderator.
Function: proxyTrustAppointModeratorPost
- Purpose: Same-origin Bearer proxy helper for api
POST /trust/appoint-moderator. - Inputs: Incoming
Request(JSON{ accountId }). - Returns / side effects: Upstream
Response. - Used by: Route POST
/trust/appoint-moderator.
Function: proxyMessagesStatsGet
- Purpose: Same-origin proxy helper for api
GET /messages/stats. - Inputs: Incoming
Request. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/messages/stats.
Function: proxyWalletStatsGet
- Purpose: Same-origin proxy helper for api
GET /wallets/stats. - Inputs: Incoming
Request(no bearer). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/wallets/stats;fetchWalletStatsreads that route on/statsand/stats/wallet.
Function: proxyWalletUsageGet
- Purpose: Same-origin proxy helper for api
GET /wallets/usage. - Inputs: Incoming
Request(no bearer). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/wallets/usage;fetchWalletUsagereads that route on/stats/wallet.
Function: proxyGiftsStatsGet
- Purpose: Same-origin proxy helper for api
GET /gifts/stats(forwardsrecipientquery). - Inputs: Incoming
Request(optionalrecipientsearch param). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/gifts/stats.
Function: proxyMeActivityGet
- Purpose: Same-origin proxy helper for api
GET /me/activity. - Inputs: Incoming
Request(Bearer). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/me/activity.
Function: proxyMembersActivityGet
- Purpose: Same-origin proxy helper for api
GET /members/:accountId/activity. - Inputs: Incoming
Request(Bearer) andaccountId. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/forum/members/[accountId]/activity.
Function: proxyViewActivityGet
- Purpose: Same-origin proxy helper for api
GET /view/:viewKey/activity(public). - Inputs: Incoming
RequestandviewKey. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/view-key/[viewKey]/activity.
Function: proxyViewListGet
- Purpose: Same-origin proxy helper for public api
GET /view/:viewKey/posts|shops|credits|replies. - Inputs: Incoming
Request,viewKey, andkind(posts,shops,credits, orreplies). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. No auth header is added by this helper. - Used by: Routes GET
/view-key/[viewKey]/posts,/shops,/credits, and/replies.
Function: fetchViewForumList
- Purpose: GET
/view-key/:viewKey/:kindwith no auth and parse one public profile list. - Inputs:
viewKey(64 hex) andkind(posts,replies,shops, orcredits). - Returns / side effects:
ForumMessage[]. Throws visitor copyCould not load messages. Please try again.on a non-2xx status, a network failure, or an invalid envelope. - Used by:
ViewProfileLoaderwhen the card stays on the public payload.
Function: ProfileImages
- Purpose: Resting header for the signed-in profile. The round photo (
GET /pictures/me) and the wide image (GET /banners/me) are different pictures, and neither is the About me note photo. A missing slot is an icon-only camera, then Add a profile photo or Add a wide image. - Inputs:
loadPicture,loadBanner,onSavePicture,onSaveBanner, andimageEpoch. A rejected load means that slot is empty. - Returns / side effects: The header. Choosing a wide image opens a 5:2 cropper. Use this crop stores the framed JPEG. Cancel stores nothing.
imageEpochreloads the stored pictures without remounting the header. - Used by:
MemberProfileScreenwhen the signed-in account id matches the profile.
Function: proxyMeNamePost
- Purpose: Proxies POST
/me/name. - Inputs:
Requestwith JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/name.
Function: proxyMeUsernamePost
- Purpose: Proxies POST
/me/username. - Inputs:
Requestwith JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/username.
Function: proxyMeLocationPost
- Purpose: Proxies POST
/me/location. - Inputs:
Requestwith JSON{ location }and Bearer session. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/location.
Function: proxyMeAboutPut
- Purpose: Same-origin Bearer proxy of api
PUT /me/about. - Inputs: Incoming
Requestwith Bearer session and JSON{ text, photo? }. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: App Router
PUTon/me/about.
Function: putProfilePhoto
- Purpose:
PUT /pictures/mewith{ photo }for the signed-in account.nullclears the profile photo. Does not change the wide image or the About me note. - Inputs: Session token, JPEG payload or
null. - Returns / side effects: Resolves on 2xx. Throws the save error otherwise.
- Used by:
MemberProfileScreen(ProfileImagesand the owner About me editor).
Function: fetchProfilePhoto
- Purpose:
GET /pictures/mebytes for the signed-in account. - Inputs: Session token.
- Returns / side effects: Blob. Throws the load error on failure or an empty body.
- Used by:
ProfileScreen(resting headerProfileImagesandAboutMeSectionloadPicture),MenuAccountHeader.
Function: proxyProfilePhotoGet
- Purpose: Same-origin Bearer proxy of api
GET /pictures/me. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: App Router
GETon/pictures/me.
Function: proxyProfilePhotoPut
- Purpose: Same-origin Bearer proxy of api
PUT /pictures/me. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: App Router
PUTon/pictures/me.
Function: putWideBanner
- Purpose:
PUT /banners/mewith{ photo }for the signed-in account.nullclears the wide image. Does not change the About me photo. - Inputs: Session token, JPEG payload or
null. - Returns / side effects: Resolves on 2xx. Throws the save error otherwise.
- Used by:
ProfileScreenviaAboutMeSectiononSaveBanner.
Function: fetchWideBanner
- Purpose:
GET /banners/mebytes for the signed-in account. - Inputs: Session token.
- Returns / side effects: Blob. Throws the load error on failure or an empty body.
- Used by:
ProfileScreen(resting headerProfileImagesandAboutMeSectionloadBanner).
Function: proxyWideBannerGet
- Purpose: Same-origin Bearer proxy of api
GET /banners/me. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: App Router
GETon/banners/me.
Function: proxyWideBannerPut
- Purpose: Same-origin Bearer proxy of api
PUT /banners/me. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: App Router
PUTon/banners/me.
Function: proxyPublicProfileSlotGet
- Purpose: Same-origin public proxy of a profile photo or wide image. Tries api
GET /{slot}/{accountId}.jpg, then.png, then.webp, and returns the firstimage/*200. No bearer. Not the About me note photo. - Inputs: Incoming
Request, slotpicturesorbanners, andaccountId. An id outside[0-9A-Za-z_-]{1,80}is 404 and does not call the api. - Returns / side effects: The image response, or 404 JSON when none of the three files match. Skipped bodies are cancelled.
- Used by: App Router
GETon/pictures/[accountId]and/banners/[accountId].
Function: MemberIdentityPills
- Purpose: Role pill and funding-program icon that sit beside a member's name, plus the sentences those controls reveal. The role pill and its sentence come from the shared {@link ForumRoleTag} / {@link ForumRoleHint} element, so the member card, forum rows, and paid-heart senders cannot drift. The pill shows the account's api role, so a software developer shows one Software Developer pill because the api sends
role: 'software_developer'. The same marks are what a visitor sees and what the account owner sees on/profile. A null profile renders the children with no marks, while the owner card is still loading. - Inputs:
profile(MemberProfileor null) andchildren(marks, hints). - Returns / side effects: Whatever
childrenreturns. No network. The pill is exactly the api role, so a software developer shows one Software Developer pill because the api sendsrole: 'software_developer'. Pressing a role pill or the funding icon reveals that one sentence. - Used by:
MemberProfileScreen.
Function: proxyMeAboutPhotoGet
- Purpose: Same-origin Bearer proxy of api
GET /me/about/photo(raw profile-note photo bytes). - Inputs: Incoming
Requestwith Bearer session. - Returns / side effects: Upstream
ResponseviaproxyApiRequestto/me/about/photo. - Used by: App Router
GETon/me/about/photo.
Function: proxyViewAboutPhotoGet
- Purpose: Same-origin public proxy of api
GET /view/:viewKey/about/photo(raw profile-note photo bytes). Browser path is/view-key/:viewKey/about/photo; upstream is/view/:viewKey/about/photo. - Inputs: Incoming
Request, plusviewKeyfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: App Router
GETon/view-key/[viewKey]/about/photo.
Function: proxyMeForumLawsDismissedPost
- Purpose: Proxies POST
/me/forum-laws-dismissed. - Inputs:
Requestwith Bearer session (no body). - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/forum-laws-dismissed.
Function: proxyMeWalletIntroSeenPost
- Purpose: Proxies POST
/me/wallet-intro-seen. - Inputs:
Requestwith Bearer session (no body). - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/wallet-intro-seen.
Function: proxyMeNotificationLevelPost
- Purpose: Same-origin Bearer proxy of api POST
/me/notification-levelwith JSON{ level }. - Inputs: Incoming
Requestwith Bearer session and JSON{ level }. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/notification-level.
Function: proxyMeHeartNotificationsPost
- Purpose: Same-origin Bearer proxy of api POST
/me/heart-notificationswith JSON{ enabled }. - Inputs: Incoming
Requestwith Bearer session and JSON{ enabled }. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/heart-notifications.
Function: proxyMeRulesAgreementPost
- Purpose: Proxies POST
/me/rules-agreement. - Inputs: Incoming
Requestwith Bearer session (no JSON body required by the client). - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/rules-agreement.
Function: proxyMeGet
- Purpose: Proxies GET
/me. - Inputs:
Requestwith Bearer token. - Returns / side effects: Upstream
Response. - Used by: Route GET
/me.
Function: proxyMessagesGet
- Purpose: Bearer proxy GET
/messagesto the 21.gifts api (public forum list). App route is GET/forum/messages. - Inputs: Incoming
Requestwith Bearer session. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/forum/messages.
Function: proxyMessagesHiddenGet
- Purpose: Same-origin Bearer proxy of api GET
/messages/hidden(hidden living-room notes for moderators). App route is GET/forum/messages/hidden. - Inputs: Incoming
Requestwith Bearer session. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by:
src/app/forum/messages/hidden/route.ts.
Function: proxyMessagesPost
- Purpose: Bearer proxy POST
/messagesto the 21.gifts api (create a public forum message or reply). App route is POST/forum/messages. - Inputs: Incoming
Requestwith Bearer session and JSON body. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/forum/messages.
Function: proxyMessagesRepliesGet
- Purpose: Bearer proxy GET
/messages/:id/repliesto the 21.gifts api (oldest-first replies). App route is GET/forum/messages/[id]/replies. - Inputs: Incoming
Requestwith Bearer session, plus parent messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/forum/messages/[id]/replies.
Function: proxyExternalAuthorProfileGet
- Purpose: Public proxy GET
/messages/:id/external-profileto the 21.gifts api (no auth). App path is/public-messages/[id]/external-profile. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Does not add a Bearer header. - Used by: Route GET
/public-messages/[id]/external-profile.
Function: proxyExternalAuthorPostsGet
- Purpose: Public proxy GET
/messages/:id/external-poststo the 21.gifts api (no auth). App path is/public-messages/[id]/external-posts. Returns the upstream response viaproxyApiRequest. Does not add a Bearer header. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Does not add a Bearer header. - Used by: Route GET
/public-messages/[id]/external-posts.
Function: proxyExternalAuthorShopsGet
- Purpose: Public proxy GET
/messages/:id/external-shopsto the 21.gifts api (no auth). App path is/public-messages/[id]/external-shops. Returns the upstream response viaproxyApiRequest. Does not add a Bearer header. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Does not add a Bearer header. - Used by: Route GET
/public-messages/[id]/external-shops.
Function: proxyExternalAuthorCreditsGet
- Purpose: Public proxy GET
/messages/:id/external-creditsto the 21.gifts api (no auth). App path is/public-messages/[id]/external-credits. Returns the upstream response viaproxyApiRequest. Does not add a Bearer header. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Does not add a Bearer header. - Used by: Route GET
/public-messages/[id]/external-credits.
Function: proxyExternalAuthorRepliesGet
- Purpose: Public proxy GET
/messages/:id/external-repliesto the 21.gifts api (no auth). App path is/public-messages/[id]/external-replies. Returns the upstream response viaproxyApiRequest. Does not add a Bearer header. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Does not add a Bearer header. - Used by: Route GET
/public-messages/[id]/external-replies.
Function: proxyPublicMessageGet
- Purpose: Public proxy GET
/messages/:idto the 21.gifts api (one note as JSON, no auth). App path is/public-messages/[id]so/messages/[id]can serve HTML. - Inputs: Incoming
Request, plus messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/public-messages/[id].
Function: proxyShortLinkGet
- Purpose: Public proxy GET
/links/:codeto the 21.gifts api (JSON{ kind, id }, no auth). App path is/links/[code]. Forwards the code withencodeURIComponent. The visitor-facing redirect is/l/[code], not this JSON route. - Inputs: Incoming
Request, plus short-linkcodefrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest(status and JSON body, or 502 when the api is unreachable). - Used by: Route GET
/links/[code], whichfetchShortLinkcalls.
Function: proxyPublicMessageRepliesGet
- Purpose: Public proxy GET
/messages/:id/repliesto the 21.gifts api (oldest-first live replies, no auth). App path is/public-messages/[id]/repliesso/messages/[id]can serve HTML. - Inputs: Incoming
Request, plus parent messageidfrom the App Router segment. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/public-messages/[id]/replies.
Function: proxyLnurlPayRequestPost
- Purpose: Bearer proxy POST
/lnurl/pay-requestto the 21.gifts api (pay request of a Lightning address or LNURL on another host). - Inputs: Incoming
Requestwith Bearer session and{ target }JSON. - Returns / side effects: Upstream
ResponseviaproxyApiRequest(502 JSON when the api is unreachable). - Used by: Route POST
/lnurl/pay-request.
Function: proxyLnurlInvoicePost
- Purpose: Bearer proxy POST
/lnurl/invoiceto the 21.gifts api (invoice from a Lightning address or LNURL on another host). - Inputs: Incoming
Requestwith Bearer session and{ target, amountMsat, comment? }JSON. - Returns / side effects: Upstream
ResponseviaproxyApiRequest(502 JSON when the api is unreachable). - Used by: Route POST
/lnurl/invoice.
Function: proxyContactPost
- Purpose: Bearer proxy POST
/contactto the 21.gifts api (create an in-app contact message). Same-origin path is/contact/submitso it does not collide with the/contactpage. - Inputs: Incoming
Requestwith Bearer session and JSON body. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/contact/submit.
Function: proxyMessagesPhotoGet
- Purpose: Same-origin proxy GET
/messages/:id/photoor/messages/:id/photo/{file}to the 21.gifts api (raw forum photo bytes). Public; no bearer required (api photo is public; proxy forwards Authorization if present but does not require it). RuntimegetApiUrl()viaproxyApiRequest(not next.config rewrites). - Inputs: Incoming
Request, messageidfrom the App Router segment, and optional indexedfilesuch as1.jpg. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/messages/[id]/photoand GET/messages/[id]/photo/[file].
Function: proxyMessagesPhotoExtGet
- Purpose: Same-origin proxy GET
/messages/:id/photo.jpgto the 21.gifts api. Deletesauthorizationon the incoming request so the edge can cache the public still for a day. - Inputs: Incoming
Request, messageidfrom the App Router segment, andext'jpg'. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. Query string is copied. No extraCache-Control. - Used by: Route GET
/messages/[id]/photo.jpg.
Function: proxyMessagesVideoGet
- Purpose: Same-origin proxy GET
/messages/:id/video.{mp4,webm,mov}to the 21.gifts api (raw forum video bytes). Public; no bearer required. RuntimegetApiUrl()viaproxyApiRequest(not next.config rewrites). - Inputs: Incoming
Request, messageidfrom the route, andext'mp4' | 'webm' | 'mov'. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route GET
/messages/[id]/[file]whenfileisvideo.mp4|video.webm|video.mov.
Function: base64UrlToBytes
- Purpose: Decode a base64url string to bytes for WebAuthn options.
- Inputs: Base64url string (padding optional).
- Returns / side effects:
Uint8Array. No network. - Used by:
creationOptionsFromJSON,requestOptionsFromJSON,unlockWalletPhrase.
Function: bytesToBase64Url
- Purpose: Encode bytes as unpadded base64url for WebAuthn JSON.
- Inputs:
Uint8Array. - Returns / side effects: Base64url string. No network.
- Used by:
credentialToJSON,usePasskeyLogin(login PRF salt check).
Function: creationOptionsFromJSON
- Purpose: Turn api creation-options JSON into
navigator.credentials.createinput, includingexcludeCredentialswhen present and clientextensions(PRFeval.firstas base64url) viaapplyClientExtensions. - Inputs: Record from
POST /auth/passkey/register/beginorPOST /auth/passkey/seed/begin. - Returns / side effects:
PublicKeyCredentialCreationOptions. Uses native parse when present. Throws if a descriptor list is present but not an array, or is non-empty but has no validpublic-keyentries (invalid type or id is skipped; all skipped → TypeError), including before native parse. - Used by:
usePasskeyLogin.register,renewPasskey, andcreateNewPasskey(the new passkey of a social recovery).
Function: credentialToJSON
- Purpose: Serialise a
PublicKeyCredentialfor the api finish body. DropsclientExtensionResults.prfso PRF bytes never leave the tab. - Inputs: Browser credential from create/get.
- Returns / side effects: JSON record without
prfresults. Uses nativetoJSONwhen present, then stripsprf. - Used by:
usePasskeyLogin,renewPasskey, and the recovery flow (createNewPasskey,transfer).
Function: finishPasskeyAuthentication
- Purpose: POST
/auth/passkey/authenticate/finishand parse the session. - Inputs:
challengeIdand credential JSON. - Returns / side effects:
{ token, account }. A 409 withcoderecovery_pendingthrowsRecoveryPendingErrorbefore any other check. ThrowsWrongAccountErroron 403 with the duplicate-account api string. A 400 body exactlyUnknown credentialthrowsUnknownCredentialError. Other non-2xx stay status fallbacks. SendsX-App-Build(getBuildId). 503codelogins_closedthrowsLoginsClosedError; 403codeapp_outdatedthrowsAppOutdatedError(checked before the wrong-account 403). - Used by:
usePasskeyLogin.authenticate, and the recovery flow's sign-in with the new passkey.
Function: finishPasskeyRegistration
- Purpose: POST
/auth/passkey/register/finishand parse the session. - Inputs:
challengeIdand credential JSON. - Returns / side effects:
{ token, account }withlinkingKeynull. ThrowsWrongAccountErroron 403 with the duplicate-account api string. A 409 whose error is exactlyUsername is already in usethrowsErrorwith that string. Other non-2xx stay status fallbacks. SendsX-App-Build(getBuildId). 503codelogins_closedthrowsLoginsClosedError; 403codeapp_outdatedthrowsAppOutdatedError(checked before the wrong-account 403). - Used by:
usePasskeyLogin.submitNamefor a new account, andusePasskeyLogin.registeronly with a view key.
Function: proxyAuthPasskeyAuthenticateBeginPost
- Purpose: Proxies POST
/auth/passkey/authenticate/begin. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/authenticate/begin.
Function: proxyAuthPasskeyAuthenticateFinishPost
- Purpose: Proxies POST
/auth/passkey/authenticate/finish. - Inputs: Incoming
Requestwith JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/authenticate/finish.
Function: DiagnosticsListener
- Purpose: Subscribe to window
errorandunhandledrejectionand forward the error name and message to the diagnostic log. - Inputs: None. Reads
window.location.pathnamewhen the event fires, plus the event'serrororreason. - Returns / side effects: Renders null. Posts
client.unhandledthroughreportDiagnostic. Removes both listeners on unmount. - Used by: Root layout, mounted once for every page.
Function: proxyDiagnosticsPost
- Purpose: Proxies POST
/diagnosticsso the browser can store an allowlisted client event. - Inputs: Incoming
Requestwith a JSON body. - Returns / side effects: Upstream
Response(204 when accepted). Does not read or log the body itself. - Used by: Route POST
/diagnostics.
Function: reportDiagnostic
- Purpose: POST one allowlisted client diagnostic to
/diagnostics. Drops fields that fail the pattern instead of shortening them. - Inputs: Event name plus optional name, message, stage, status, path, challenge id, account id, and whether a PRF output was present.
- Returns / side effects: void. Fire-and-forget
fetchwithkeepalive. Never throws. Never sends PRF bytes, the recovery phrase, or a session token. - Used by:
DiagnosticsListener,usePasskeyLogin,renewPasskey, anduseWalletPhrase.
Function: proxyAuthPasskeyRegisterBeginPost
- Purpose: Proxies POST
/auth/passkey/register/begin. - Inputs: Incoming
Request. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/register/begin.
Function: proxyAuthPasskeyRegisterFinishPost
- Purpose: Proxies POST
/auth/passkey/register/finish. - Inputs: Incoming
Requestwith JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/register/finish.
Function: requestOptionsFromJSON
- Purpose: Turn api request-options JSON into
navigator.credentials.getinput. EmptyallowCredentialsis omitted (discoverable credentials). When discoverable, setshints: ['client-device']. Copies clientextensions(PRFeval.firstas base64url) viaapplyClientExtensions. - Inputs: Record from
POST /auth/passkey/authenticate/begin. - Returns / side effects:
PublicKeyCredentialRequestOptions. Uses native parse when present. Throws if a descriptor list is present but not an array, or is non-empty but has no validpublic-keyentries (invalid type or id is skipped; all skipped → TypeError), including before native parse. - Used by:
usePasskeyLogin.authenticate, and the recovery flow's sign-in with the new passkey (transfer).
Function: startPasskeyAuthentication
- Purpose: POST
/auth/passkey/authenticate/beginand parse options. - Inputs: None.
- Returns / side effects:
{ challengeId, options }. Throws on non-2xx. SendsX-App-Build(getBuildId). 403codeapp_outdatedthrowsAppOutdatedError; the api checks closed logins on authenticate finish, not here. - Used by:
usePasskeyLogin.authenticate, and the recovery flow's sign-in with the new passkey (transfer).
Function: startPasskeyRecovery
- Purpose: POST
/auth/passkey/recovery/beginto start the social recovery of the account the old wallet belongs to, and parse the answer withrecoveryBeginSchema. - Inputs:
{ sparkPubkey, lookup: { signature, timestamp } }: the old wallet's identity key and its signed address lookup (lowercase DER hex, timestamp in seconds). Only these fields are sent, whatever else the object holds. - Returns / side effects:
{ challengeId, options, accountId, username }. SendsX-App-Build(getBuildId). 503codelogins_closedthrowsLoginsClosedError; 403codeapp_outdatedthrowsAppOutdatedError; 403 with the duplicate-account api string throwsWrongAccountError. ThenRecoveryError:not_foundon 404,doneoroperatoron 409 withcoderecovery_doneorrecovery_operator,unavailableon 5xx or 429,invalidon any other non-2xx. A body that fails the schema throws. - Used by: The recovery flow on
/recover, for its first begin and every begin again.
Function: finishPasskeyRecovery
- Purpose: POST
/auth/passkey/recovery/finishto store the new passkey and the new wallet key as the account's pending social recovery, signed by the old wallet. A repeat of the same finish after a lost answer succeeds again and changes nothing. - Inputs:
{ challengeId, credential, newSparkPubkey, signature: { pubkey, signature } }: the begin's challenge id, the new passkey's attestation JSON (without PRF output), the new wallet key, and the old wallet's signature over the recovery message. Only these fields are sent. - Returns / side effects: Resolves on any 2xx. Sends
X-App-Build(getBuildId). Login refusals and the wrong account throw as instartPasskeyRecovery. ThenRecoveryError:challengeon 400Unknown or expired challenge,Challenge expired, orChallenge already used(the account did not move);pendingon 409A recovery is already pending;key_in_useon 409Wallet key is already in use;unavailableon 5xx or 429;invalidon any other non-2xx, including a known text with another status. - Used by:
transferon/recover, as the first part of the move (the account).
Function: startPasskeyReplace
- Purpose: POST
/auth/passkey/replace/beginwith Bearer. The client helper is removed. Replace routes and proxies remain so an old client can still reach the API; the API rejects replace. Nothing in the app calls this for the phrase. - Inputs: Session token.
- Returns / side effects:
{ challengeId, options }. Throws on non-2xx. - Used by: None. The client helper is removed.
Function: finishPasskeyReplace
- Purpose: POST
/auth/passkey/replace/finishwith Bearer. Does not mint a session. The client helper is removed. Replace routes and proxies remain so an old client can still reach the API; the API rejects replace. Nothing in the app calls this for the phrase. - Inputs: Session token, challenge id, credential JSON.
- Returns / side effects: Owner
Accountfrom{ account }. Throws on non-2xx. - Used by: None. The client helper is removed.
Function: startPasskeySeed
- Purpose: POST
/auth/passkey/seed/beginwith Bearer and an empty body. - Inputs: Session token.
- Returns / side effects:
{ challengeId, options }. Throws on non-2xx, including 409. - Used by:
renewPasskey.
Function: finishPasskeySeed
- Purpose: POST
/auth/passkey/seed/finishwith Bearer and{ challengeId, credential }. - Inputs: Session token, challenge id, credential JSON.
- Returns / side effects: The owner account (
accountSchema), includingpasskeyCredentialId. A 200 body is that account, or the same account under oneaccountkey when the body has no top-levelid.accountonly holds when it is the only top-level field; a further field is not an account. No new token. Login is a different call. Throws on non-2xx or a body that is not an account. - Used by:
renewPasskey.
Function: postWalletBackupSeen
- Purpose: POST
/me/wallet-backup-seenwith Bearer. - Inputs: Session token.
- Returns / side effects: Owner
Account. Throws on non-2xx. - Used by: The helper remains.
useWalletPhrasedoes not call it.
Function: postWalletReport
- Purpose:
POST /me/wallet/reportwith bearer +{ balanceSats, syncedAt, payments }. - Inputs:
sessionTokenand aWalletReportBody(balance in whole sats, ISO 8601 read time, at mostWALLET_REPORT_PAGE_SIZEpayments). - Returns / side effects: The
acknowledgedIdsof the response. Sends only those three fields, whatever else the body object holds. ThrowsCould not report wallet data: <status>on a non-2xx status, and throws when the response has noacknowledgedIdslist. - Used by:
reportWallet.
Function: passkeyRenewDebug
- Purpose: Read public authenticator facts from a created passkey. PRF bytes, the credential id, and the attestation object are not copied.
- Inputs: The browser credential, or null when create threw, and a known
prfPresentboolean or null. - Returns / side effects: Attachment, transports, AAGUID, PRF flags, extension names, the WebAuthn flags byte, the COSE algorithm, resident key, hmac-secret, and credProtect. Missing methods and throws become null. No I/O.
- Used by:
renewPasskeybefore it reports a ceremony failure or cancel.
Function: passkeyRenewDebugFields
- Purpose: Drop null debug fields so a report that learned nothing keeps the original six-field body. Zero and false stay.
- Inputs: Facts from
passkeyRenewDebug, or null. - Returns / side effects: A partial object of only the known facts. No I/O.
- Used by:
renewPasskeywhen it builds the renew report.
Function: passkeyRenewClientCapabilities
- Purpose: Read browser capability names that are strictly true, such as
prfandhybridTransport. This describes the browser, not the passkey. - Inputs: None. Calls
PublicKeyCredential.getClientCapabilitieswhen the browser has it. - Returns / side effects: A sorted comma-separated list, capped at 24 names, or null. Objects, false, and odd keys are dropped. No I/O besides that browser call.
- Used by:
renewPasskeyon every stored failure or cancel, including when create itself threw.
Function: postPasskeyRenewReport
- Purpose: POST
/me/passkey-renew/reportwith Bearer, the six safe fields, and optional public authenticator facts. - Inputs: Session token and
{ stage, outcome, errorName, errorCode, httpStatus, message }plus, when known,authenticatorAttachment,transports,aaguid,prfEnabled,prfPresent,extensions,authenticatorFlags,publicKeyAlgorithm,residentKey,hmacSecret,credProtect, andclientCapabilities. - Returns / side effects: Owner
Account. ThrowsCould not report passkey renewon non-2xx. Never sends a phrase, PRF bytes, credential, challenge, or token in the body. - Used by:
renewPasskeyfor browser-only ceremony failures and cancels.
Function: postPasskeyRenewAck
- Purpose: POST
/me/passkey-renew/ackwith Bearer. - Inputs: Session token.
- Returns / side effects: Owner
Account. ThrowsCould not acknowledge passkey renewon non-2xx. - Used by:
PasskeyRenewNoticeOK button.
Function: renewPasskey
- Purpose: Runs the seed-passkey ceremony for a member who has no seed yet.
- Inputs: Session token.
- Returns / side effects:
okwith the account and in-memory PRF bytes,cancelled,storedwhen reload already shows a seed, orfailedwith a wallet error kind.failedincludes the owner account when that account has an open renew failure. HTTP seed failures are not reported again. The new passkey's PRF output comes fromobtainPrfFirstunder the seed options'rp.id;nulliswallet.prfUnsupportedbefore finish. A stored failure or cancel also sends the public authenticator facts and the browser capability names. Posts allowlisted seed diagnostics and never sends PRF bytes, the phrase, or the session token. After a successful finish it startsrememberPhraseFromPrfand does not wait for it. Does not persist the phrase (tab memory only). - Used by:
useWalletPhrase.activateandPasskeyRenewNotice.
Function: mergePrfExtension
- Purpose: Adds the PRF request to passkey creation options:
prf.eval.firstis the PRF salt (prfEvalFirstSalt), so the new passkey yields the bytes behind a recovery phrase. - Inputs:
PublicKeyCredentialCreationOptionsas decoded from the api (creationOptionsFromJSON). - Returns / side effects: A copy with the PRF extension; other options and extensions stay as they are, and the input is not changed.
- Used by:
renewPasskey(the seed passkey) and the recovery flow on/recover(the new passkey of a social recovery).
Function: PasskeyRenewNotice
- Purpose: Guided blocking renew while
walletRequiredis false: explain, confirm, device passkey prompt, then a success or failure confirmation. - Inputs: None. Reads the auth store and translations.
?visual=renew-passkeyand?visual=renew-okforce those steps for screenshots, only in a Playwright build (getE2eNow()set); a production build ignores them. - Returns / side effects: No dismiss control on the explanation. Continue starts the ceremony. Cancelling the device prompt returns to the explanation and is not a logged failure. Success stores the account only after OK. A failed ceremony stores the returned account and stays on the failure step only when that account has an open failure and the session is unchanged, so a remount stays there. When that account has
passkeyRenewPrfUnsupported, the failure step showswallet.prfUnsupported(This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.). An HTTP seed error that did not record a failure returns to the explanation. Failure OK stores the acknowledged account only while that same session is still current, then the dialog closes and does not start again. Null once success is confirmed, a failure was acknowledged, orpasskeyRenewClosedis true. - Used by:
AppShellwhenwalletRequired === falseandpasskeyRenewClosedis not true.
Function: DailyPayoutStoppedNotice
- Purpose: Non-dismissible info banner for signed-in members whose owner funding JSON has
dailyPayoutStoppedNotice === true. The title is Daily payout stopped, thenfunding.stoppedDaily.bodyand the large Apply for the 21 gifts grant link to/grants/apply. Applications are open, so every account with the flag sees Apply. Nothing shows while the account wallet is not open in this tab (useWalletOpen). - Inputs: None. Reads the auth store and translations.
- Returns / side effects: A
role="region"banner with the body and the Apply link, ornullwhen the flag is missing, false, or funding is null, or the wallet is not open. No close control, no localStorage, no extra API call. - Used by:
AppShell.
Function: proxyMePasskeyRenewReportPost
- Purpose: Proxies POST
/me/passkey-renew/report. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/passkey-renew/report.
Function: proxyMePasskeyRenewAckPost
- Purpose: Proxies POST
/me/passkey-renew/ack. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/passkey-renew/ack.
Function: proxyAuthPasskeyReplaceBeginPost
- Purpose: Proxies POST
/auth/passkey/replace/begin. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/replace/begin.
Function: proxyAuthPasskeyReplaceFinishPost
- Purpose: Proxies POST
/auth/passkey/replace/finish. - Inputs: Incoming
Requestwith Bearer and JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/replace/finish.
Function: proxyAuthPasskeySeedBeginPost
- Purpose: Proxies POST
/auth/passkey/seed/begin. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/seed/begin.
Function: proxyAuthPasskeySeedFinishPost
- Purpose: Proxies POST
/auth/passkey/seed/finish. - Inputs: Incoming
Requestwith Bearer and JSON body. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/seed/finish.
Function: proxyAuthPasskeyRecoveryBeginPost
- Purpose: Proxies POST
/auth/passkey/recovery/begin(social recovery) to the api. - Inputs: Incoming
Requestwith JSON{ sparkPubkey, lookup }; no session.X-App-Buildis passed through unchanged. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/recovery/begin.
Function: proxyAuthPasskeyRecoveryFinishPost
- Purpose: Proxies POST
/auth/passkey/recovery/finish(social recovery) to the api. - Inputs: Incoming
Requestwith JSON{ challengeId, credential, newSparkPubkey, signature }; no session.X-App-BuildandOriginare passed through unchanged. - Returns / side effects: Upstream
Response. - Used by: Route POST
/auth/passkey/recovery/finish.
Function: proxyMeWalletBackupSeenPost
- Purpose: Proxies POST
/me/wallet-backup-seen. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route POST
/me/wallet-backup-seen.
Function: proxyMeWalletReportPost
- Purpose: Proxies
POST /me/wallet/reportto the api withproxyApiRequest(Bearer and JSON body forwarded). - Inputs: The App Router request.
- Returns / side effects: The upstream response, or 502 when the api cannot be reached.
- Used by:
src/app/me/wallet/report/route.ts.
Function: proxyMeWalletHeartsPost
- Purpose: Proxies
POST /me/wallet/heartsto the api withproxyApiRequest(Bearer and JSON body forwarded). - Inputs: The App Router request with
{ hashes }. - Returns / side effects: The upstream response, or 502 when the api cannot be reached.
- Used by:
src/app/me/wallet/hearts/route.ts.
Function: proxyMeEventsPost
- Purpose: Proxies
POST /me/eventsto the api withproxyApiRequest(Bearer and JSON body forwarded). - Inputs: The App Router request.
- Returns / side effects: The upstream response, or 502 when the api cannot be reached.
- Used by:
src/app/me/events/route.ts.
Function: prfEvalFirstSalt
- Purpose: SHA-256 of UTF-8
21gifts-nostr-v1(PRF_EVAL_FIRST_SALT_UTF8). Existing wallets are derived from this salt: it must never change.src/__tests__/lib/prf-mnemonic.test.tspins the text and the 32 salt bytes. - Inputs: None.
- Returns / side effects: 32-byte
Uint8Array. - Used by:
obtainPrfFirst,obtainPrfFirstFromGet,usePasskeyLogin(register, and the login PRF salt check),renewPasskey.
Function: readPrfFirst
- Purpose: Read
prf.results.firstfrom a credential. - Inputs:
PublicKeyCredential. - Returns / side effects: Bytes or
undefined. - Used by:
obtainPrfFirst,obtainPrfFirstFromGet,usePasskeyLogin(login, when the wallet is configured).
Function: mnemonicFromPrfFirst
- Purpose: HKDF-SHA-256 (salt
21gifts-seed-derivation, infomnemonic-v1, 128 bits) then BIP-39 English 12 words. Existing wallets are derived from these values: the salt, info, and length must never change.src/__tests__/lib/prf-mnemonic.test.tspins them with a known-answer vector (PRF bytes00 01 … 1fgiveaccess under chronic decline attitude industry sure uncle sauce secret minute frost). - Inputs: PRF eval.first bytes.
- Returns / side effects: Space-separated mnemonic. Never sent to the api.
- Used by:
useWalletPhrase,rememberPhraseFromPrf, andcreateNewPasskey(the new wallet's words of a social recovery).
Function: obtainPrfFirst
- Purpose: Confirms the PRF output of a new passkey with one get() under the relying-party id of the creation options (
allowCredentials= the new credential, eval.first salt,userVerification: 'required') and uses the get() output, so the words can be derived again later. - Inputs: The new
PublicKeyCredential; the relying-party id the api sent (rp.id, read withrememberCeremonyRpId), ornull. - Returns / side effects: Bytes, or
nullwhen the id isnull(no prompt), the get() gives no PRF output, or create() gave PRF output that differs from the get() output. Callers treatnullas no PRF (wallet.prfUnsupported) before the account, the seed, or the new wallet is finished. One extra prompt after create(). Never uses the page host name as the relying-party id. - Used by:
usePasskeyLogin.register,renewPasskey, andcreateNewPasskey(the new passkey of a social recovery).
Function: obtainPrfFirstFromGet
- Purpose: get() with PRF eval.first bound to this account's current credential (
allowCredentials) to re-derive the phrase, under the relying-party id of this tab's latest api passkey ceremony (rememberCeremonyRpId). - Inputs: Current credential id bytes (WebAuthn
rawId). - Returns / side effects: Bytes or
null. When no api ceremony ran in this tab (a session restored from storage), first runsstartPasskeyAuthenticationonly to read itsrpIdand keeps it; that begin is never finished and no assertion is forwarded.nullwithout a prompt when the api sent no relying-party id. A failed begin rejects. Never uses the page host name. Does not pick a leftover credential after replace. - Used by:
useWalletPhrase.showPhrase,unlockWalletPhrase.
Function: rememberCeremonyRpId
- Purpose: Reads the relying-party id from api WebAuthn options and keeps it in tab memory for later PRF prompts in this tab.
- Inputs: WebAuthn options JSON from an api begin:
rpIdof assertion options, elserp.idof creation options. - Returns / side effects: The id, or
nullwhen it is missing or empty. Thatnullis stored too and counts as no ceremony in this tab, so a laterobtainPrfFirstFromGetasks a fresh authentication begin and fails as no PRF only when that begin carries no id either. Not persisted. - Used by:
usePasskeyLogin(register, and a finished login),renewPasskey,createNewPasskey, the social recovery sign-in, andobtainPrfFirstFromGet.
Function: classifyWebAuthnError
- Purpose: Map WebAuthn failures to timeout / cancel / generic.
- Inputs: Unknown rejection.
- Returns / side effects: Discriminant string.
- Used by:
useWalletPhrase,renewPasskey,unlockWalletPhrase, andcreateNewPasskey.
Function: rememberSessionPhrase
- Purpose: Store 12 words in tab RAM.
- Inputs: Mnemonic string.
- Returns / side effects: Module-level variable. Never localStorage. Dispatches
SESSION_PHRASE_EVENT, which connects the wallet when a key is configured. - Used by:
rememberPhraseFromPrf, which is its only production caller; tests; re-exported fromuseWalletPhrase. Implemented intab-phrase.
Function: peekSessionPhrase
- Purpose: Read tab-RAM mnemonic.
- Inputs: None.
- Returns / side effects: String or
null. - Used by:
connectWallet,listenForWalletPhrase,useWallet.retry,unlockWalletPhrase,useWalletPhrase.showPhrase,useSocialRecoverySetup(the words split on Secure my account, without a passkey prompt); re-exported fromuseWalletPhrase. Implemented intab-phrase.
Function: clearSessionPhrase
- Purpose: Drop tab-RAM mnemonic.
- Inputs: None.
- Returns / side effects: Clears the module variable. Dispatches
SESSION_PHRASE_EVENT, which disconnects the wallet. - Used by:
clearAuth,login,authenticate, and the recovery flow's sign-in with the new passkey (transfer). Implemented intab-phrase.
Function: sessionPhraseGeneration
- Purpose: Counter that changes whenever the tab phrase is remembered or cleared. Lets an asynchronous derivation detect that it was overtaken.
- Inputs: None.
- Returns / side effects: A number.
- Used by:
rememberPhraseFromPrf. Implemented intab-phrase.
Function: Slip39Error
- Purpose: Typed refusal of a SLIP-39 share or set of shares, so the social recovery screens choose catalog copy by its code and never read a text.
- Inputs:
code:empty(no share),word(a word not in the list),length(fewer than 20 words, a word count no secret fits, or a wrong secret length),checksum,padding(non-zero padding bits),params(group threshold above group count),set(shares of different sets or owners),groups(not the groups the set needs),members(not the shares a group needs, or one share twice),digest(shares that do not fit together), orpassphrase(not printable ASCII). - Returns / side effects: Error named
Slip39Errorwith a readonlycodeand the messageslip39_<code>. Neither ever holds a share word or a byte. - Used by:
parseShare,splitRecoverySecret,combineShares,phraseFromShareCodes, andOldWordsInput(the same code twice).
Function: parseShare
- Purpose: Reads the fields of one SLIP-39 share from its words, without any cryptography. In the order of the reference implementation (trezor/python-shamir-mnemonic) it checks that every word is in the pinned 1024-word list (
slip39-wordlist.ts, looked up in aMap, soconstructoris no word), that there are at least 20 words in a count a secret fits, the RS1024 checksum with the customization string of the share's extendable flag, that the group threshold is not above the group count, and that the padding bits are zero. - Inputs: The share's words, separated by whitespace, in any letter case.
- Returns / side effects:
Slip39Share:identifier(15 bits),extendable,iterationExponent,groupIndex,groupThreshold,groupCount,memberIndex,memberThreshold, and thevaluebytes. ThrowsSlip39Errorword,length,checksum,params, orpadding. Pure. - Used by:
parseShareCode,combineShares.
Function: isRecoveryShare
- Purpose: Whether a share has the shape of a social recovery share, so a scanned code of another SLIP-39 backup is not taken as one.
- Inputs: A
Slip39SharefromparseShare. - Returns / side effects:
truefor one group (group threshold 1, group count 1), member threshold 2, a 16-byte value, member index 0, 1, or 2, the extendable flag, and iteration exponent 1 — the shape the app mints, so a hostile share with a larger exponent cannot raise the combine cost. Pure. - Used by:
parseShareCode.
Function: splitRecoverySecret
- Purpose: Splits the 16 bytes behind 12 words into a social recovery set with WebCrypto only: the SLIP-39 four-round Feistel cipher (PBKDF2-HMAC-SHA-256; extendable, so the identifier is not in the salt; iteration exponent 1; empty passphrase), one group of threshold 1, then a 2-of-3 Shamir split in GF(256) through the 4-byte HMAC-SHA-256 digest share and the secret.
- Inputs: The 16 bytes, and optionally a random source (
crypto.getRandomValuesby default; tests inject a fixed one). - Returns / side effects:
{ identifier, shares }: the random 15-bit set identifier and three 20-word shares with member index 0 (person 1), 1 (person 2), and 2 (21.gifts). Word 3 is alwaysacademic; word 4 isacid,agency, oralways. The shares are standard SLIP-39, so any SLIP-39 tool combines two of them to the same 16 bytes. ThrowsSlip39Errorlengthfor any other byte count. No network, no storage. - Used by:
splitPhrase.
Function: combineShares
- Purpose: Rebuilds the master secret from the shares of one SLIP-39 set. It reads every valid set (every group shape, both cipher salts), so the 45 official test vectors (a SHA-256-pinned fixture of the reference implementation) pass against it. Identical shares count once.
- Inputs: The shares' words, and optionally a printable-ASCII passphrase (empty by default, as social recovery uses it; the vectors use
TREZOR). - Returns / side effects: The master secret bytes. Throws
Slip39Errorempty,passphrase, any code ofparseShare,setfor shares of different sets,lengthfor values of different lengths,membersorgroupsfor the wrong number of shares (one share alone and the same share twice aremembers), ordigestwhen the shares do not fit together. No network, no storage. - Used by:
splitPhrase(the pair check) andphraseFromShareCodes.
Function: encodeShareCode
- Purpose: Builds the QR payload of one social recovery share:
21gifts-share:v1:<owner account id>:<owner username>:<20 share words>(SHARE_CODE_PREFIXplus the fields). The payload is shown phone to phone and reaches the api only encrypted, in a holder's box. - Inputs: Owner account id, owner username, and the share's 20 words.
- Returns / side effects: The payload text. Throws
Invalid share codewhen the result would not read back withparseShareCode, so no QR is shown that a holder's app refuses. - Used by:
useSocialRecoverySetup(the QR codes of shares 1 and 2 on/settings/social-recovery) andkeepHeldShare.
Function: parseShareCode
- Purpose: Reads a scanned or pasted share payload. The text is trimmed and read only up to 400 characters; it must match the payload format (owner id of up to 64 letters, digits,
_or-; a username as the app allows it; exactly 20 lower-case words separated by single spaces), and its words must be a valid recovery share (parseShare, thenisRecoveryShare). - Inputs: Scanned or pasted text.
- Returns / side effects:
ShareCode(ownerAccountId,ownerUsername,share,identifier,memberIndex), ornullfor anything else. Pure. - Used by:
encodeShareCode,loadHeldShares,keepHeldShare,useHeldShares(the owner's username of a scanned code), andOldWordsInput(the codes scanned on/recoverand/settings/previous-wallets/[sparkPubkey]).
Function: splitPhrase
- Purpose: Splits the owner's 12 words into the three shares of a new social recovery set, and checks before any share leaves the phone that each pair (shares 1 and 2, 1 and 3, 2 and 3) gives the same 16 bytes back.
- Inputs: The 12-word recovery phrase from tab memory, and optionally a random source for
splitRecoverySecret(crypto.getRandomValuesby default; tests and the Playwright screenshot fixture ofuseSocialRecoverySetuppass a fixed one). - Returns / side effects:
{ identifier, shares }fromsplitRecoverySecret. Throws the BIP-39 error ofmnemonicToEntropyfor words that are not a valid phrase,Slip39Errorlengthfor a phrase longer than 12 words, andRecovery split check failedwhen a pair does not give the bytes back. The words and bytes stay in memory. - Used by:
useSocialRecoverySetupon/settings/social-recovery, for Continue and for Start again with new codes (a new set when a holder's app refused the code because that person already keeps a share of the same setup).
Function: phraseFromShareCodes
- Purpose: Rebuilds the old 12 words from two scanned shares of one set. The 16 bytes go back through BIP-39 (
entropyToMnemonic) and the wallet opens with those words, never with the bytes as raw entropy, which would open a different wallet. - Inputs: Two
ShareCodes. - Returns / side effects: The 12 words, in memory only. Throws
Slip39Errorsetfor shares of another owner or identifier,membersfor the same share twice,digestwhen they do not fit together, andlengthwhen they do not give 16 bytes. - Used by:
OldWordsInput(two scanned codes rebuild the old 12 words on/recoverand/settings/previous-wallets/[sparkPubkey]).
Function: heldShareBoxKey
- Purpose: The key a holder's share boxes are encrypted with: HKDF-SHA256 over the 16 bytes behind the holder's own 12 words (salt
21gifts-held-share-box, infobox-key-v1, 32 bytes), imported into WebCrypto as a non-extractable AES-256-GCM key. The key comes from the words, not from the passkey, so the holder's own Social Recovery can move the boxes to the new words while the old ones are rebuilt. - Inputs: The holder's 12 words (from tab memory, the passkey prompt of Open my shares, or the old and new words of a recovery).
- Returns / side effects: The
CryptoKey(encrypt and decrypt only). Throws the BIP-39 error ofmnemonicToEntropyfor words that are not a valid phrase, and theDOMExceptionofcrypto.subtle.importKeyorderiveKeywhen the browser cannot import or derive the key. The words and bytes stay in memory. - Used by:
useHeldShares(the key of the open page) andrelockHeldShares.
Function: newHeldShareBoxId
- Purpose: A new box id: 16 bytes from
crypto.getRandomValuesas 32 lower-case hex digits, the formPUT /me/held-shares/:idaccepts. The app draws the id; the api only stores it. - Inputs: None.
- Returns / side effects: The id. No network.
- Used by:
keepHeldShare.
Function: sealHeldShare
- Purpose: Encrypts one share code into a box:
0x01(version), a fresh 12-byte random IV, and the AES-256-GCM ciphertext with its tag, with the additional data21gifts-held-share-v1, the holder's account id, and the box id on three lines, so a box only opens under its own holder and id. - Inputs: The holder's box key, the holder's account id, the box id, and the share code.
- Returns / side effects: The box as base64url without padding. Throws the
DOMExceptionofcrypto.getRandomValuesorcrypto.subtle.encryptwhen the browser cannot make the IV or encrypt with the key. No network. - Used by:
keepHeldShare(a new box) andrelockHeldShares(a box sealed again with the new words).
Function: openHeldShare
- Purpose: Decrypts one box sealed by
sealHeldShare. - Inputs: The holder's box key, the holder's account id, the box id, and the box (base64url).
- Returns / side effects: The share code, or
nullwhen the box does not open: another version byte, another key (for example the holder's words before a recovery of their own), another account or id, changed bytes, text that is not base64url, or plaintext that is not UTF-8. Never throws. No network. - Used by:
loadHeldSharesandrelockHeldShares.
Function: loadHeldShares
- Purpose: Reads the shares the signed-in member keeps for other members' Social Recovery: every box of
GET /me/held-shares(fetchHeldShareBoxes) is opened with the key of the member's current words (openHeldShare) and its code read withparseShareCode. - Inputs: Session token, the signed-in member's account id, and the box key of the member's current words.
- Returns / side effects:
{ shares, lockedIds }:HeldShare[](boxId,code,ownerAccountId,ownerUsername,identifier,memberIndex) sorted by owner username, and the ids of the boxes that did not open or hold no share code. Nothing is deleted. Throws the errors offetchHeldShareBoxeswhen the boxes cannot be read. - Used by:
useHeldShareson/settings/held-shares, andkeepHeldShare(the boxes read again before a keep).
Function: keepHeldShare
- Purpose: Keeps a scanned share for another member. It refuses text that is not a share and a share of the member's own account, then reads the member's boxes again (
loadHeldShares): a box that already holds this share code is the kept share, so a scan repeated after a lost answer never makes a second box; another share whose owner account id and SLIP-39 identifier are among the opened boxes is refused, so one member never keeps two shares of one set. Otherwise it seals the code (sealHeldShare) under a new random id (newHeldShareBoxId) and stores it (putHeldShareBox). - Inputs: Session token, the signed-in member's account id, the box key of the member's current words, and the scanned text.
- Returns / side effects:
{ ok: true, share }with the box that already held the code or the new box once the api stored it, or{ ok: false, reason }withinvalid,own,duplicate, orsave(the boxes could not be read, the new box could not be sealed, or the api did not store it). The code reaches the api only encrypted. Two devices that keep the same share at the same moment can each store a box: both read the boxes before either stores, and the api cannot refuse the second because it never learns whose share a box holds. - Used by:
useHeldShares(Keep a share on/settings/held-shares).
Function: relockHeldShares
- Purpose: After the member's own Social Recovery, moves the boxes they keep for others from their previous 12 words to their current ones: every box that opens with the previous words is sealed again with the current words and written back under the same id (
putHeldShareBox). A box that does not open with the previous words is left as it is. A box deleted while it runs is not brought back: a write the api answers withcreated(the box was gone) is deleted again (deleteHeldShareBox, once; a failed delete leaves it under the current words) and not counted. A write whose answer is lost is not known to have created the box, so a box deleted between the read and such a write can come back. - Inputs: Session token, the member's account id, the previous 12 words, and the current 12 words, or
nullwhile the tab holds none. - Returns / side effects: How many boxes moved. It reads the boxes first (
fetchHeldShareBoxes), so a member who keeps none derives no key. Never throws: no boxes, no current words, same words, words that are not a phrase, or boxes that cannot be read move nothing, and a box whose write fails is not counted and moves on the next call whenever the api did not store it (moved boxes no longer open with the previous words, so a repeat is safe). - Used by: The sign-in with the new passkey in
recovery-flow.ts(with the old words still in memory) anduseRemainingBalance(old words entered on/settings/previous-wallets/[sparkPubkey], with the signed-in wallet's words from tab memory once the running phrase derivations have settled, ornullwhen the tab holds none). Neither waits for it, so it never holds up the recovery or the balance move.
Function: derSignatureHex
- Purpose: Encodes a compact ECDSA signature as strict minimal DER, the only form the wallet's address server reads: r and s each lose their leading zero bytes (one byte stays for zero) and gain a zero byte when their high bit is set, then
30 <length>wraps both. - Inputs: 64 bytes: r then s.
- Returns / side effects: Lower-case hex. Throws
Expected a 64-byte signaturefor any other length. Pure. - Used by:
loadWalletSdk(signAddressLookup).
Function: lnurlRecoverMessage
- Purpose: The address lookup message a wallet signs to read back the address it holds, byte for byte as the wallet SDK builds it:
breez-lnurl:v2,recover, the domain, the identity key, and the timestamp in decimal seconds, joined by line feeds. - Inputs: Domain (the app's host), identity public key (lower-case hex), Unix time in seconds.
- Returns / side effects: The message text. Pure.
- Used by:
loadWalletSdk(signAddressLookup).
Function: recoveryMessage
- Purpose: The recovery message the old wallet signs to hand its account to the new passkey and wallet, identical to the api's:
21gifts-account-recovery-v1, the account id, the challenge as issued, the new credential id, and the new wallet key, joined by line feeds, with no line feed at the end. - Inputs:
{ accountId, challenge, credentialId, newSparkPubkey }. - Returns / side effects: The message text. Pure.
- Used by:
transferon/recover, which signs it with the old wallet'ssignMessagebeforefinishPasskeyRecovery.
Function: resetWalletCeremonyLock
- Purpose: Drop the tab-wide wallet WebAuthn lock so a later ceremony can start.
- Inputs: None.
- Returns / side effects: Sets the module lock to idle. Tests call this between cases; production uses
finallyon activate / showPhrase. - Used by:
useWalletPhrasetests.
Function: useWalletPhrase
- Purpose: Add or show the recovery phrase.
/walletdoes not render the words./wallet/phrasedoes. There is no confirm view, no auto-reveal, and no Continue on the words. - Inputs: Auth store session and account.
- Returns / side effects: View
'activate' | 'reveal' | 'phrase', status, error, words,activate,showPhrase,hidePhrase,retry.'activate'only without a non-emptypasskeyCredentialId(Add recovery phrase:renewPasskey, thenmnemonicFromPrfFirston the in-memory PRF bytes, store the account, 12 words only in component state).'reveal'when the id is set:showPhraseshows the phrase already in tab memory (the open wallet's, also after waiting for a login derivation still running) without a passkey prompt; otherwise it runsobtainPrfFirstFromGetof that id, no create and no seed begin (only the authentication begin that gives the relying-party id when no api ceremony ran in this tab), and passes the same PRF bytes torememberPhraseFromPrf, so that one prompt also opens the wallet.walletBackupSeenAtis not read. The hook itself does not callrememberSessionPhrase;activatereaches it throughrenewPasskeywhen the wallet is configured.hidePhrasehides the words and keeps the tab phrase, so the wallet stays open. No Confirm, no Continue. A passkey without PRF output sets errorprfUnsupported, shown aswallet.prfUnsupported(This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.).?visual=phrase(fixture wordsWALLET_VISUAL_FIXTURE_MNEMONIC),?visual=error,?visual=timeout, and?visual=prf-unsupportedpin a screenshot state only in a Playwright build (getE2eNow()set); a production build ignores them and never shows the fixture words. - Used by:
WalletScreen,WalletPhraseScreen.
Function: WalletScreenView
- Purpose: Wallet views, and the header Back. The visible Back is this
ProfileChromeLeftviaAppShellTopLeft, not the pageWalletChromeLeft.surface="entry"is/walletwith its home, Send, and Receive views.surface="phrase"is/wallet/phrase. - Inputs:
account.passkeyCredentialIdfromuseAuthStore,UseWalletPhraseResultplus optionalsurface(entrydefault, orphrase), optionalwalletprop for the balance block, and optionalsendprop for the send flow. - Returns / side effects: On
entry, one of three views; the heading Wallet is screen-reader only in each. Home: the balance block fromWalletBalancelarge in the centre (when the wallet prop is present and notdisabled), thenLoansCard place="wallet"and theWalletHistorypayments card while the wallet isready, followed byWalletFooterActions(Receive on the left and Send on the right, both enabled whatever the wallet status; Send opens only with a send prop). The loan card is absent without current loans and shows its wallet-only muted waiting-lender line when needed. Nothing sits under them: the recovery phrase is reached from/security. While the account has no recovery phrase yet (nopasskeyCredentialId), the home card ends with a small muted underlined Back up your wallet link (wallet.backupLink) to/security; with a phrase there is none. Receive and Send areWalletPanelView(WalletReceive, orWalletSendwith the manual-entry sheet), driven byuseWalletPanel, the same hook as/welcome. The Send view is kept regardless of the chosen view while a send is in flight, its Sent line shows, or an input alert is up. A chosen view stays when the wallet stops beingready; when the Sent line closes (Done or Back), the view returns home. No word grid and no recovery error. Onphrase, only the ceremony: Add recovery phrase, Show recovery phrase, the 12-word grid and the warningwallet.phraseWarningthat whoever has the words can take over the whole account (no Continue), or an error with Try again. No QR and no balance block. Header Back onentry: in the Send view it first closes the manual-entry sheet, then askssend.cancel()to close an open step; when nothing closed and nothing is being read or sent, it clears the field (send.setText(''), which also clears an input alert) and returns home. In the Receive view it returns home. On home it returns to the previous in-app view in this tab, or opens/welcomewhen this tab has none. Onphraseit hides the words, then does the same. It does not leave the site, and it does not open/walletas a parent. Opened as/wallet?receive=1(Add Bitcoin in a pay sheet away from the forum home),useReceiveLinkopens the Receive view once and removesreceivefrom the address; the top-left arrow then closes Receive first. - Used by:
WalletScreen,WalletPhraseScreen.
Function: WalletScreen
- Purpose: Signed-in
/walletbody: the balance, thenLoansCardwhen there is a current loan, then the payments list (WalletHistory) while the wallet is ready, with Receive and Send below. The recovery entry is on/security(SecurityScreen). - Inputs: None.
- Returns / side effects: Renders
WalletScreenViewwithuseWalletPhrase(), thewalletprop fromuseWallet(), and thesendprop fromuseWalletSend(). The view owns the loan-card placement; this wrapper does not render the 12 words. - Used by:
WalletPage.
Function: useWalletStore
- Purpose: Zustand store for the in-app wallet:
status(disabled,locked,connecting,ready,error),balanceSats,identityPubkey,syncCount(advanced by everysetReady, that is after connect and after each SDK sync; the payment list reloads when it changes),setupFailedSession(the session whose background setup exhausted its retries, ornull),retrying(true while the wallet is aterrorand the wallet service opens it again automatically, between and during its retries), anddownloading(true while the wallet isconnectingand the wallet code is still being downloaded for the first time in this page). - Inputs: Hook. Actions
setConnecting,setReady,setError,setRetrying(retrying),setDownloading(downloading),reset, andsetSetupFailedSession(session).setConnecting,setReady, andresetclearretrying;setReady,setError, andresetcleardownloading. - Returns / side effects: Wallet state object. Resting status is
disabledwithout a key, elselocked.setSetupFailedSessionrecords or clears the session independently of the wallet connection fields so money screens can show the setup note until an explicit retry. - Used by: The wallet service, background wallet setup,
useWallet,useWalletSetup,useWalletHistory,useWalletPay,useWalletSend,useLoanRepay,WalletSync, andreportWallet.
Function: loadWalletSdk
- Purpose: The only module that imports
@breeztech/breez-sdk-spark: its/webentry, by dynamic import, then itsinit(). The download and initialisation are shared: calls while they run wait on the same promise, and a successful start is kept for the page. A failed import or initialisation is dropped, so the next call starts again in the same page without a reload (the package's/ssrentry keeps a rejected initialisation for the life of the page, which is why it is not used; the bundler retries a failed chunk import, and the wasm code keeps no state until its module has been instantiated). Returns the narrowWalletSdk(connect→getInfo,getUserSettings,updateUserSettings,addEventListener,registerAddress,listPayments,getPayment(one payment by id through the SDK'sgetPayment({ paymentId }), mapped withtoWalletPayment; atokenpayment, whose amount is not in satoshis, rejects like an unknown id, as the Bitcoin-only list leaves it out),listReportPayments,parse,prepare, the social recovery methods below,disconnect; plusidentityPubkeyandsignAddressLookup);getInfocan request a synchronized read withensureSynced. The settings surface exposes onlysparkPrivateModeEnabledandsparkMasterIdentityPublicKey; its update type can only enable private mode or set a viewer key, never disable privacy or unset the viewer.registerAddressregisters only the given username (no availability check is exposed);listPaymentsasks for one page of Bitcoin payments newest first (assetFilterbitcoin, so token payments whose amounts are not satoshis are left out) and maps each row withtoWalletPayment.parsemaps the SDK'sparseresult to aWalletTarget: a payment request or address it pays from text (BOLT11, Spark address, Spark invoice; a BIP21 URI uses its first payable method, and its amount when that method has none, markedamountFromUriso it is passed toprepare; its recipient is the shortened request or address, never the issuer's description), an LNURL-pay receiver or Lightning address with its sat bounds (at least 1 sat; bounds that leave no whole sat make itunsupported) and comment limit,onchainfor a Bitcoin mainnet address on the base chain (itsaddress, the shortenedrecipient, andamountSatsfrom a BIP21 URI that offers only that address, otherwisenull; a BIP21 URI with a Lightning or Spark method uses that method instead), orunsupported(token invoices, a BIP21 URI that names an asset, a BOLT11 request for less than one whole sat, an address of a test network, and everything else).preparecallsprepareSendPayment({ paymentRequest: { type: 'input', input } })(withamountwhen the text has none; a base-chain address always gets one) orprepareLnurlPay, reads amount and fee, refuses a prepared payment that would send a token rather than Bitcoin, and returnssend, which callssendPayment(a BOLT11 request withpreferSpark: false, so the Lightning fee shown is the fee paid) orlnurlPaywith that prepare response. For a base-chain address (SendPaymentMethodbitcoinAddress) it reads thefeeQuoteintoonchain: the fee of each speed (fast,medium,slow) isuserFeeSatplusl1BroadcastFeeSat, andexpiresAtMsis the quote'sexpiresAt(epoch seconds) in ms;feeSatsis the medium fee, andsend(speed)callssendPaymentwith{ type: 'bitcoinAddress', confirmationSpeed: speed }(defaultmedium).listReportPaymentsasks for the same page of Bitcoin payments (sameassetFilter) and maps each row withtoWalletReportPayment, for the wallet data report. For social recovery the connection also hassignMessage(message)(the SDK'ssignMessagewithcompact: true: ECDSA over one SHA-256 of the text with the identity key, returned as{ pubkey, signature }hex and nothing else),hasAddress()(whethergetLightningAddressfinds an address, which looks it up once when it was never read),authorizeAddressTransfer(transfereePubkey)(authorizeLightningAddressTransfer, signing only, wrapped as an opaqueWalletAddressTransfer),claimAddressTransfer(transfer)(claimLightningAddressTransferwith that same authorization; the SDK posts/lnurlpay/<own key>/transferto the app's host),receiveSparkAddress()(receivePaymentfor a Spark address), andsendToSparkAddress(address, amountSats, idempotencyKey)(prepareSendPaymentwith exactly that amount, refused withNot a Spark addressbefore anything is sent unless the method issparkAddress, thensendPaymentwith the idempotency key, a UUID, so a repeated send is not paid twice). For the Fond's on-chain deposits the connection also hasreceiveBitcoinAddress()(receivePaymentwith{ type: 'bitcoinAddress' }and nonewAddress, so the existing static deposit address),listUnclaimedDeposits()(the SDK'slistUnclaimedDeposits({})mapped toWalletDepositrows:txid,vout,amountSats,donefor a submitted or claimed instant claim or a refund, andmaxClaimFeeSatsfor a recorded fixed ceiling), andclaimDeposit({ txid, vout }, maxFeeSats)(the SDK'sclaimDepositwithmaxFee: { type: 'fixed', amount }).identityPubkey(mnemonic)andsignAddressLookup(mnemonic, domain, timestampSecs)need no connection and no network: they use the SDK's own external signer of the words (defaultExternalSigners(mnemonic, null, 'mainnet').sparkSigner, the same identity keyconnectderives) and free it afterwards.signAddressLookupsigns the UTF-8 bytes oflnurlRecoverMessage(domain, pubkey, timestampSecs)and returns{ pubkey, signature }with the signature DER-encoded byderSignatureHex, the lookup the SDK itself sends on connect; the SDK'ssignMessagerefuses that message, which is why the external signer signs it. - Inputs: None.
- Returns / side effects: A
WalletSdk. UsesdefaultConfig('mainnet')with the api key,lnurlDomainset to the host passed by the service (the app's own host), and a fixed storage name. The SDK keeps wallet state in IndexedDB; the phrase is passed in memory only. - Used by: The wallet service as the default loader, and the recovery flow on
/recoverandopenPreviousWalleton/settings/previous-wallets/[sparkPubkey], which open a second wallet beside the member's own.
Function: connectWallet
- Purpose: Connects from the tab phrase with the app's own host (
window.location.host) as the address domain. Does nothing without a key or a phrase, so the SDK never receives a domain while the wallet is not configured. On every new connection it starts non-blocking settings work, and every later account viewer-key change joins the same promise chain across connections. A new connection and the silent repair enablesparkPrivateModeEnabledonly when it is false. A later change towalletViewerPublicKeywrites only the viewer key. When each run reaches the front it readsgetUserSettingsand the account's then-currentwalletViewerPublicKey, and setssparkMasterIdentityPublicKeyonly when that account key is valid 66-character lower-case hex and differs from the SDK's current value. Every awaited settings SDK call stops holding the chain within 5 seconds after that exact connection is dropped, so a call that never answers cannot block settings work for the replacement connection. A later rejection is swallowed. If an abandoned call later succeeds, the then-current connection queues a silent full settings pass, re-reading and re-applying private mode and the account's then-current viewer key after the stale write; that repair is not reported. A stale run starts no further settings calls itself and does not report its aborted call, but a failure it recorded before a later call was aborted is still reported. It never disables privacy, never unsets a viewer, and never writes an invalid value. A key that becomes current again is written again when the SDK differs; an overlapping A → B change on one connection finishes the A run before reading and applying B. The first balance read after connect usesensureSynced, so a cached balance is not shown as final and the store staysconnectinguntil that read finishes. The wallet code is downloaded first, without a time limit: while it downloads for the first time in this page the store isconnectingwithdownloadingset (the balance reads Downloading wallet…), and every call or retry meanwhile waits on the same download instead of starting another. A failed download is a failed open like any other, and the next attempt downloads again in the same page. Connecting and the first synchronized read are then limited to 30 seconds (WALLET_CONNECT_TIMEOUT_MS); if they do not finish in time while the wallet is still connecting, the wallet shows theerrorstate with Try again. A wallet that asyncedrefresh already showed as ready is left as it is. Store otherwise goes toreadyorerror. Subscribes to SDK events and refreshes onsynced. The latest call wins and a superseded connection is closed. - Automatic retries: After a failure (this call's, or a balance read that closed the connection) the wallet is opened again by itself, without an attempt limit, for as long as the tab holds the phrase and the key. The pauses are exponential with a cap and jitter: nominally 2 s, 4 s, 8 s, 16 s, 32 s, then 60 s every time (
WALLET_RETRY_BASE_MS, doubled per failure, capped atWALLET_RETRY_CAP_MS), each shortened by a random share of up to 20 % (WALLET_RETRY_JITTER), so the first retry follows after 1.6 to 2 s and no pause is longer than 60 s. Each retry is a full attempt; its connect has its own 30 s limit once the wallet code is loaded. The pause before a retry starts once the connection of the failed attempt has finished disconnecting, or 5 s after the failure when it has not by then (WALLET_RETRY_DISCONNECT_WAIT_MS), so a disconnect that never settles cannot hold the retries back. Until thenonlineandvisibilitychangestart nothing, so a retry does not open a connection beside one that is still closing within that time; Try again does not wait for it. Between and during the retries the store stayserrorwithretryingset, neverconnecting: screens that need the wallet keep the could-not-be-opened state with Try again, and a retry that succeeds makes the storeready. No retry starts while the tab is hidden or the browser is offline; the cycle then waits without a timer.visibilitychange(to visible) andonlinestart the retry at once and begin the backoff again at 2 s; while a retry is already running they only reset the backoff. A cycle ends when the wallet is ready, ondisconnectWallet(sign-out or phrase removal: its timer and both listeners are removed), when the phrase or the key is gone at the next retry, or when this function is called again (also by Try again andensureWalletConnected), which supersedes a running retry through the run counter, closes its late connection, and starts over at once. - Inputs: Optional
WalletSdkLoader(defaults toloadWalletSdk). - Returns / side effects: void. Updates
useWalletStore. The settings chain is deliberately not awaited, so it never holds the wallet UI at connecting. A failed settings read or update reportsWallet settings not updatedonly when that call failed while the run still owned the current connection and the run is not the silent repair, with only a fixed stage and the existing safe error name/code/cause classification, never a key, address, SDK message, or thrown value. The failure of a call that was abandoned is not reported. A failure established before a later call in the same run was abandoned is reported. The silent repair reports neither the read nor the update. Times the SDK load, the connect, and the first synced balance read as the wallet spanswallet.sdk.load,wallet.connect, andwallet.sync.first(traceWallet). Each automatic retry is timed in the same spans. - Error report and interaction log: Only the first failure is reported: once a failed open was reported, no later failure (an automatic retry, Try again, or a setup try) is reported until the wallet has been ready again or was disconnected. For that first failure, when the attempt that is still the latest fails, it sends
captureMessage('Wallet did not open')at levelerrorwith the fingerprint['wallet-open-failed', reason]and the tagwallet_open_reason, and recordswallet_open_failedwithreason:timeoutat the 30 s deadline,errorwhen loading the wallet code, connecting, or the first synchronized read rejected. Both also say why:stage(sdk_loadwhen downloading or starting the wallet code failed,connectwhen connecting or adding the event listener failed,first_syncwhen the first synchronized balance read failed, or when a balance read started by asyncedevent failed before the wallet was ready,deadlineat the 30 s deadline),errorName,errorCode, andcauseKindfromerrorCause(all threenullat the deadline, where nothing was thrown),elapsedMssince the attempt started,online(navigator.onLine), andvisibility(document.visibilityState). The error report carries them as extras and as the tagswallet_open_stage,wallet_open_error,wallet_open_error_code,wallet_open_cause(nonewhen absent),wallet_open_online, andwallet_open_visibility, besidewallet_open_reason; the fingerprint stays one issue per reason. No part of the error's message is sent, and neither is the thrown value itself, its stack, its cause, the SDK config, the phrase, the key, or any other field of the error (a rejection without a value reportserrorNameunknown). A superseded attempt reports nothing. Nothing is sent to error reporting while it is off, and the event is dropped without a session. - Used by:
listenForWalletPhrase,useWallet.retry,useWalletPay.retry,ensureWalletConnected.
Function: onIncomingPayment
- Purpose: Subscribes to received payments that complete while the wallet is open in this tab. After the first synchronized balance read of a connection, the newest 100 payments are read (
listPayments), and the ids of the received, completed ones count as known; a failed read counts as none known. From then on an SDKpaymentSucceededevent whose payment (mapped bytoWalletPayment; token payments carry none) is received, completed, and not known is added to the known ids, the balance is read again (refreshWallet), and once that read and any newer balance read of the connection are done (only the newest read writes the balance) it is announced once to every listener, so a listener showing the balance shows the new one; when the connection ended meanwhile (sign-out, or a failed read that drops it) nothing is announced. A received payment that completes while that list is still being read is held and announced once the list is in, unless the list holds it; when the read fails, what was held is dropped, so nothing old is announced. Payments the wallet held when it connected, sends, pending or failed payments, and a second event for the same id are not announced. A new connection starts again. - Inputs:
listener(payment: WalletPayment). - Returns / side effects: Unsubscribe function. No network of its own.
- Used by:
useIncomingPayment,MoveFundsSheet.
Function: onPaymentReceived
- Purpose: Subscribes to every received, completed payment of the signed-in wallet, each payment id once per phrase: the moment the SDK reports it — once the known payments of the connection were read, right after its id is added to the known ids and before the balance is read again (
refreshWallet); while that list is still being read, at once without adding it to the known ids (even when that list then holds it or cannot be read), the told payments keeping it to once; and each payment a connection lists when it opens, oldest first, so one that completed while no connection was open (before the first, or while the wallet reconnected after a failure) is heard too. A listener that subscribes later first hears the payments told so far for the wallet signed in now. UnlikeonIncomingPayment, which announces only payments that complete while the wallet is open and only after the balance read, old payments are included: the listener judges which one it waits for (the till takes a payment that names its charge, and keeps a Lightning payment that names no charge only to ask the api about it). A sign-out starts it over only when that sign-out is still the latest run after the connection drops; a sign-in that already replaced that run keeps the payments it told. For a screen that must react to the money arriving without waiting for the balance read. A payment announced when the connection ended meanwhile was still told here. - Inputs:
listener(payment: WalletPayment). - Returns / side effects: Unsubscribe function. No network of its own.
- Used by: the point-of-sale screens (
PosTill,PosAmount), which subscribe once per tab when a signed-in till page first opens and stay subscribed.
Function: announceReceivedForE2e
- Purpose: In a Playwright build only (
getE2eNow()), tells everyonPaymentReceivedlistener about a payment as if the wallet had just reported it, so e2e drives a screen that waits for the money through that listener without a wallet. Does nothing in any other build. - Inputs:
payment: WalletPayment(received, completed). - Returns / side effects:
void. Calls theonPaymentReceivedlisteners; no network, no balance read. - Used by:
PosTillunder the?visual=pos-receivedand?visual=pos-received-unnamedpins.
Function: refreshWallet
- Purpose: Reads
getInfo(withensureSyncedwhen asked, so a payment that arrived without a wallet event is counted) and stores balance and identity key. The balance is never derived from payment events. When reads overlap only the latest one counts (this one or the synced read inside the wallet payment primitive, which shares the read counter): it alone writes the store, and only a failed refresh that is still the latest closes the connection and setserror, after which the automatic retries ofconnectWalletopen the wallet again. The failure of a stale read is ignored. A failure before an open ofconnectWalletwas ready (while it waits for its first synchronized read, also after that read was overtaken, or while its event listener is still being added) ends that open and is reported once as its failure (Wallet did not openandwallet_open_failed) atfirst_sync, like the open's own failures. - Inputs: Optional
{ ensureSynced?: boolean; ignoreFailure?: boolean }; without them, a plain read whose failure while current closes the connection and setserror. WithignoreFailure, a failed read changes nothing and the wallet stays as it is. - Returns / side effects: void. Updates
useWalletStore. Times the read as the wallet spanwallet.balance(traceWallet). - Used by: The
syncedlistener thatconnectWalletregisters, thesendthat the wallet payment primitive returns,useWalletPay(synced reads every 4 s whileinsufficientshows),useLoanRepay(synced reads while top-up is open), andWalletSync(a synced read every five minutes while the wallet is ready).
Function: disconnectWallet
- Purpose: Closes the connection and resets the store (
locked, ordisabledwithout a key). Runs when the tab phrase is cleared, which includes logout. Ends the automatic retries after a failed open: their timer and theironlineandvisibilitychangelisteners are removed, a retry still running is superseded and its late connection closed, and the next failed open is reported again. When this sign-out is still the latest run after the connection drops, it forgets the payments told to theonPaymentReceivedlisteners (which a later listener would hear first), so the next sign-in starts over. A sign-in that already replaced this run keeps the payments it told. Disconnecting leaves the SDK's wallet data, including balance and payment history, in this browser's IndexedDB. It is not encrypted at rest and is removed only with the site's browser data. - Inputs: None.
- Returns / side effects: void. Updates
useWalletStore. - Used by:
listenForWalletPhrasewhen the phrase is cleared.
Function: listenForWalletPhrase
- Purpose: Subscribes to the tab-phrase event; phrase present → connect, cleared → disconnect. Returns the unsubscribe. No listener at all without a key.
- Inputs: Optional
WalletSdkLoader(defaults toloadWalletSdk). - Returns / side effects: Unsubscribe function.
- Used by:
WalletSync.
Function: rememberPhraseFromPrf
- Purpose: Derives the phrase from PRF bytes a passkey response already carried and keeps it in tab memory. Only when the key is configured, the bytes are present, the account is
walletRequired, the response's credential is the account'spasskeyCredentialId, and the session is still the one that started it. Never throws, never sends the bytes or the phrase and never stores them persistently (tab memory only). A derivation overtaken by a later remember or clear (sessionPhraseGeneration) remembers nothing. While a derivation runs,settlePhraseDerivationswaits for it. - Inputs:
PhraseSource(prfFirst,credentialId,account,sessionToken). - Returns / side effects:
truewhen the phrase was remembered, elsefalse. When the account's own seed passkey answered without PRF output, or its PRF output could not be turned into a phrase, it records that for the session (until the next phrase change), sounlockWalletPhraseanswersnoPrforfailedwithout asking that passkey a second time. - Used by:
usePasskeyLogin(login and registration, started before the new session is stored so background setup can wait for it),renewPasskey,unlockWalletPhrase,useWalletPhrase.showPhrase, and the recovery flow's sign-in with the new passkey (transfer).
Function: walletGateApplies
- Purpose: Decides whether an account must have its recovery phrase in this tab before it counts as signed in.
- Inputs:
account; wallet build configuration,canUnlockWallet, and the Playwright-only value fromvisualPin. - Returns / side effects: In a real build, true only when the wallet key is configured and the account can derive its wallet. Accounts that cannot hold a wallet are never held back. In a Playwright build, true only for the
balance-locked…pins so ordinary fixture sessions remain signed in. No side effects. - Used by:
isWalletOpenandhydratesLocked.
Function: isWalletOpen
- Purpose: Defines the signed-in invariant for one account: its phrase is in tab memory, or the wallet gate does not apply to it.
- Inputs:
accountandhasPhrase. - Returns / side effects: Boolean; one-time wallet setup is deliberately not part of the result. No side effects.
- Used by:
useWalletOpen, andLanguageSwitcher(outside React, to skip the account write while a login is opening its wallet).
Function: hydratesLocked
- Purpose: Detects a valid stored session that must be held back after reload, a new tab, or reopening the app because this tab has no recovery phrase. In a Playwright build the
?visual=held-sessionpin also holds it back, while a login in that tab then counts as open (that build has no wallet to open), so the reload, login card, and one-prompt login run end to end; a production build ignores the pin. - Inputs: Hydrated
account; reads the current tab phrase throughpeekSessionPhrase, delegates account eligibility towalletGateApplies, and reads the pin throughvisualPin. - Returns / side effects: Boolean: true when the wallet gate applies or the
held-sessionpin is set, and the tab has no phrase. True makes hydration store the token aslockedSessioninstead of active auth. No direct side effects. - Used by:
useHydrateSession.
Function: finishWalletOpen
- Purpose: Completes wallet opening after login. It first waits for the phrase derivation already started from the login passkey's PRF output and asks for the seed passkey only when another passkey signed in without producing that phrase.
- Inputs: Current auth account and tab phrase through
settlePhraseDerivations,peekSessionPhrase, andunlockWalletPhrase. - Returns / side effects: Promise of
'open','cancelled','noPrf', or'failed'; never rejects. On success the phrase remains in tab memory only. Wallet setup is not awaited and starts separately in the background. - Used by:
WalletLoginCard.
Function: useActiveSession
- Purpose: The session token public pages may act with. Returns the store session, except
nullwhile an account is set whose wallet is not open in this tab yet, so a login still opening its wallet counts as signed out there (decision "login = wallet open"). - Inputs: None. Reads
useAuthStoresessionandaccountanduseWalletOpen. - Returns / side effects: The usable session token, or
null. A held-back session is alreadynullin the store; an account that cannot hold a wallet, and a session whose account has not loaded yet, keep their token. No side effects. - Used by:
PublicMessageLoader(signed-in fetch and mark-as-read),NoteTranslate(mark-as-read and the translate call), andForumQuotedBody/QuotedForumNote(signed-in quote fetch and the member link), andAmountEntry(saving the chosen unit on the account).
Function: useWalletOpen
- Purpose: Reactive signed-in predicate for gated screens: the current account exists and its wallet is open under
isWalletOpen. Besides the gate, components outside it (the Menu chrome, the preference sync, the payout notice, the public profile's login, anduseActiveSession) read it to treat a session whose wallet is not open as signed out. - Inputs: Auth-store
accountpluspeekSessionPhrase, subscribed throughSESSION_PHRASE_EVENT; the server snapshot has no phrase. - Returns / side effects: Boolean. False while signed out, while a stored token is held as
lockedSession, and between a successful login and phrase derivation. Adds and removes the tab-phrase event listener. - Used by:
OnboardingGate,ViewProfileClaim,SignedInChrome,AccountPreferenceSync,DailyPayoutStoppedNotice, anduseActiveSession.
Function: settlePhraseDerivations
- Purpose: Waits until every phrase derivation running in this tab (
rememberPhraseFromPrf) has finished. The login derives the phrase from its passkey response without waiting for it, so a caller that needs the phrase right after login waits here instead of asking for the passkey a second time. - Inputs: None.
- Returns / side effects: Resolves once no derivation is running. Never rejects.
- Used by:
runWalletSetup,finishWalletOpen,unlockWalletPhrase, anduseWalletPhrase.showPhrase.
Function: unlockWalletPhrase
- Purpose: Seed-passkey fallback for opening the wallet phrase:
obtainPrfFirstFromGetof the account'spasskeyCredentialId, thenrememberPhraseFromPrf. No api call when an api ceremony ran in this tab; otherwise only the authentication begin that gives the relying-party id. One ceremony per tab: a call while one is in progress, also from a remounted screen, joins it and gets the same result. No prompt when the phrase is already in tab memory: it first waits for a derivation the login started from its own prompt (settlePhraseDerivations), and returns'unlocked'when the phrase is then there. - Inputs: None (reads the auth store).
- Returns / side effects:
'unlocked','cancelled','noPrf'(the passkey answered without PRF output, so this phone or browser cannot hold the wallet), or'failed'. Answers'noPrf'or'failed'without a prompt when this session's login already used the seed passkey without giving a phrase (rememberPhraseFromPrf), so a login never asks the same passkey twice. Times the passkey prompt as the wallet spanwallet.passkeywithprompt: unlock(traceWallet); the PRF output is never part of the span. - Used by:
finishWalletOpenonly.
Function: canUnlockWallet
- Purpose: True when the account has
walletRequired === trueand a non-emptypasskeyCredentialId. - Inputs:
accountornull. - Returns / side effects: Type predicate
account is Account & { passkeyCredentialId: string }. - Used by:
useWallet,useWalletPay,useWalletSend,useLoanRepay,rememberPhraseFromPrf,unlockWalletPhrase.
Function: useWallet
- Purpose: State and actions for the
/walletbalance block after the central gate has established that the wallet is open. An unconfigured wallet or account that cannot hold one isdisabled; there is no rendered locked state. A store that has not connected yet is presented asconnecting. An account still needing wallet verification also staysconnectingwhile background setup runs, withdownloadingset while the wallet code downloads; exhausted setup reportserrorwithsetupFailed. After a failed open the status iserrorwithretryingwhile the wallet service opens the wallet again in the background, and turnsreadyon its own. While the wallet code is still downloading the status isconnectingwithdownloadingset.retryalways connects again in this page; it never reloads the page. - Inputs: None. Reads the auth store,
useWalletStore,useWalletSetup(due,failed), and Playwright-only pins throughvisualPin(?visual=setup-pendingshows connecting,?visual=wallet-received,?visual=move-arrived,?visual=wallet-pay-insufficient,?visual=heart-payment,?visual=heart-payment-pending,?visual=received-from-member,?visual=received-member-unknown,?visual=sent-to-member,?visual=sent-member-unknown,?visual=history-heart,?visual=history-heart-pending,?visual=history-repayment, and?visual=repayment-paymentshow ready with the fixture balance,?visual=balance-reopeningshowserrorwithretryingand turns ready with the fixture balance afterWALLET_VISUAL_REOPEN_MS, 4 s, and?visual=balance-downloadingshowsconnectingwithdownloading). - Returns / side effects:
{ status, balanceSats, retry, downloading, setupFailed, retrying }, wherestatusexcludeslocked,downloadingis true only atconnectingwhile the wallet code downloads, andretryingis true only aterrorwhile a retry is on its way (never withsetupFailed).retryreconnects in this page. Balance, history, and send pins set deterministic states only in a Playwright build; pinned retry is inert. - Used by:
WalletScreen,WelcomeScreen,useWalletSend,MenuAccountHeader,HeaderBalance,WalletTour,MoveFundsSheet.
Function: putWallet
- Purpose: Claims the in-app wallet's identity public key for the signed-in account (
PUT /me/wallet, body{ sparkPubkey }). The api overwrites an unverified claim and refuses once the wallet is verified. - Inputs: Session token, identity public key (66 lower-case hex).
- Returns / side effects: The updated
Account. Throwswallet-verifiedon 409,wallet-unavailableon 404 (feature off), andwallet-requeston any other failure or an invalid body. - Used by:
runWalletSetup.
Function: proxyMeWalletPut
- Purpose: Proxies PUT
/me/walletto the api. - Inputs: Incoming
Requestwith Bearer and JSON{ sparkPubkey }. - Returns / side effects: Upstream
Response. - Used by: Route PUT
/me/wallet.
Function: putRecoveryShare
- Purpose: PUT
/me/recovery-sharewith Bearer to store 21.gifts' share of the owner's social recovery for the account's verified wallet. - Inputs: Session token and
{ sparkPubkey, share }: the verified wallet key and the raw share with index 2 (20 lowercase words), never a holder's code. Only these fields are sent. - Returns / side effects: The updated
Account, withsocialRecoverySetUptrue. ThrowsRecoveryErrorkey_in_useon 409 (the wallet is not connected or changed),unavailableon 5xx or 429, andinvalidon any other non-2xx. A body that failsaccountSchemathrows. - Used by:
useSocialRecoverySetupon/settings/social-recovery.
Function: proxyMeRecoverySharePut
- Purpose: Proxies PUT
/me/recovery-shareto the api. - Inputs: Incoming
Requestwith Bearer and JSON{ sparkPubkey, share }. - Returns / side effects: Upstream
Response. Does not read or log the body. - Used by: Route PUT
/me/recovery-share.
Function: fetchPreviousWallets
- Purpose: GET
/me/previous-walletswith Bearer: the wallets the account used before a social recovery. - Inputs: Session token.
- Returns / side effects:
PreviousWallet[](sparkPubkey,sparkAddress,replacedAt,balanceSats), wherebalanceSatsis the public explorer balance the api read ornullwhen unknown; it is information only. ThrowsUnauthorizedon 401 andPrevious wallets are unavailableon any other non-2xx. A body that failspreviousWalletsSchemathrows. - Used by:
usePreviousWallets(the previous wallets on/security) anduseRemainingBalance(the previous wallet's page checks that its key is listed).
Function: proxyMePreviousWalletsGet
- Purpose: Proxies GET
/me/previous-walletsto the api. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route GET
/me/previous-wallets.
Function: deletePreviousWallet
- Purpose: DELETE
/me/previous-wallets/:sparkPubkeywith Bearer: drops one previous wallet of the account, together with the 21.gifts share stored for it. - Inputs: Session token and the previous wallet's identity key (URL-encoded into the path).
- Returns / side effects: Resolves on 204, and on 404 (
Not found): the page asks only for a key it found listed, so 404 means the wallet is already removed, e.g. a repeat after a lost answer. Any other status throwsCould not remove the previous wallet. - Used by: The remove action of
RemainingBalanceScreen, only after a synced read of that wallet gave 0.
Function: proxyMePreviousWalletDelete
- Purpose: Proxies DELETE
/me/previous-wallets/:sparkPubkeyto the api. - Inputs: Incoming
Requestwith Bearer, pathsparkPubkey(URL-encoded upstream). - Returns / side effects: Upstream
Response(204 with no body when dropped). - Used by: Route DELETE
/me/previous-wallets/[sparkPubkey].
Function: fetchHeldShareBoxes
- Purpose: GET
/me/held-shareswith Bearer: the boxes the signed-in member keeps other members' shares in, oldest first. The api returns only the caller's own boxes and cannot read them. - Inputs: Session token.
- Returns / side effects:
HeldShareBox[](id,ciphertext,updatedAt). ThrowsUnauthorizedon 401 andHeld shares are unavailableon any other non-2xx. A body that failsheldShareBoxesSchemathrows. - Used by:
loadHeldSharesandrelockHeldShares.
Function: putHeldShareBox
- Purpose: PUT
/me/held-shares/:idwith Bearer and JSON{ ciphertext }: creates (201) or replaces (200) one box of the signed-in member. - Inputs: Session token, the box id (URL-encoded into the path), and the sealed box (base64url).
- Returns / side effects:
createdon 201 (the account had no box with this id), otherwisereplaced. Any non-2xx (400 for a bad id or box, 409Box id in useorToo many held shares, 401, 429, 5xx) throwsCould not keep the share. - Used by:
keepHeldShareandrelockHeldShares.
Function: deleteHeldShareBox
- Purpose: DELETE
/me/held-shares/:idwith Bearer: deletes one box of the signed-in member. The api answers 204 also for a box that is already gone, so a repeat after a lost answer succeeds. - Inputs: Session token and the box id (URL-encoded into the path).
- Returns / side effects: Resolves on 204; any other status throws
Could not delete the share. - Used by:
useHeldShares(the confirmed delete of one share, and of the boxes that do not open with the current words) andrelockHeldShares(a box a re-lock wrote again after it was deleted).
Function: proxyMeHeldSharesGet
- Purpose: Proxies GET
/me/held-sharesto the api. - Inputs: Incoming
Requestwith Bearer. - Returns / side effects: Upstream
Response. - Used by: Route GET
/me/held-shares.
Function: proxyMeHeldSharePut
- Purpose: Proxies PUT
/me/held-shares/:idto the api. - Inputs: Incoming
Requestwith Bearer and JSON{ ciphertext }, pathid(URL-encoded upstream). - Returns / side effects: Upstream
Response. Does not read or log the body. - Used by: Route PUT
/me/held-shares/[id].
Function: proxyMeHeldShareDelete
- Purpose: Proxies DELETE
/me/held-shares/:idto the api. - Inputs: Incoming
Requestwith Bearer, pathid(URL-encoded upstream). - Returns / side effects: Upstream
Response(204 with no body). - Used by: Route DELETE
/me/held-shares/[id].
Function: proxyLnurlpayRegisterPost
- Purpose: Proxies the in-app wallet's address registration (POST
/lnurlpay/:pubkey) to the api, which accepts it only for the account's own username and claimed key and then marks the wallet verified. - Inputs: Incoming
Request(signed JSON body; theX-Breez-SignatureandX-Breez-Timestampheaders are forwarded), pathpubkey. - Returns / side effects: Upstream
Response. - Used by: Route POST
/lnurlpay/[pubkey].
Function: proxyLnurlpayRecoverPost
- Purpose: Proxies the in-app wallet's address lookup (POST
/lnurlpay/:pubkey/recover) to the api. - Inputs: Incoming
Request(signed JSON body), pathpubkey. - Returns / side effects: Upstream
Response. - Used by: Route POST
/lnurlpay/[pubkey]/recover.
Function: proxyLnurlpayTransferPost
- Purpose: Proxies the new in-app wallet's address claim during a social recovery (POST
/lnurlpay/:pubkey/transfer) to the api, which admits it only for the account's pending recovery and the old wallet's authorization. - Inputs: Incoming
Request(JSON body signed by both wallets), pathpubkey(the new wallet key, URL-encoded upstream). - Returns / side effects: Upstream
Response. Default proxy options, like its/lnurlpaysiblings. - Used by: Route POST
/lnurlpay/[pubkey]/transfer.
Function: proxyLnurlpayMetadataGet
- Purpose: Proxies the in-app wallet's read of payer notes on received payments (GET
/lnurlpay/:pubkey/metadata, query unchanged) to the api. - Inputs: Incoming
Request, pathpubkey. - Returns / side effects: Upstream
Response. - Used by: Route GET
/lnurlpay/[pubkey]/metadata.
Function: proxyLnurlpInvoiceGet
- Purpose: Proxies a payer's request for a payment request to a member's in-app wallet (GET
/lnurlp/:username/invoice, query unchanged) to the api. The pay request for a verified wallet points its callback here. - Inputs: Incoming
Request, pathusername. - Returns / side effects: Upstream status and body with
Access-Control-Allow-Origin: *. - Used by: Route GET
/lnurlp/[username]/invoice.
Function: proxyVerifyGet
- Purpose: Proxies a payer's check whether a payment to a member's in-app wallet settled (GET
/verify/:paymentHash) to the api. - Inputs: Incoming
Request, pathpaymentHash. - Returns / side effects: Upstream status and body with
Access-Control-Allow-Origin: *. - Used by: Route GET
/verify/[paymentHash].
Function: paymentInfo
- Purpose: Reads the SDK payment details into
WalletPaymentInfo. A description matchingpos:plus a charge id with no space (/^pos:\S+$/) setspurposetoshopandchargeIdto the text afterpos:, and does not put that memo back intodescription. A gift memo (zap:plus 64 hex digits) setspurposetogiftand is also not kept asdescription. Any other non-empty description is kept. - Inputs: SDK payment details, or
undefined. - Returns / side effects:
WalletPaymentInfo. Pure. Not exported. - Used by:
toWalletPayment.
Function: toWalletPayment
- Purpose: Maps one SDK payment to the
WalletPaymentthe/walletpayment list and the/wallet/paymentscreen read (the screen shows only part ofinfo; the invoice's node key is kept but not shown):receivedorsent, whole sats and whole-sat fees (the SDK amounts arebigint), epoch ms (the SDK time is seconds), status, method (lightning,spark,deposit,withdraw;tokenand anything else isother), the payer's note from the received-payment metadata, andinfo: the Lightning or Spark invoice and its description (a Spark description comes frominvoiceDetails), payment hash and preimage, the invoice's node, the paid Lightning address and the comment sent with it, a zap request (NIP-57 kind 9734 JSON: the zapper's public key, the trimmed message, and theetag of the zapped note), and an on-chain transaction id and output. A blank note, description, or comment counts as none; a zap request that is not valid JSON, not an object, not kind 9734, or has no public key is left out; an unknown status counts as completed. A gift memo (zap:plus 64 hex digits) is not kept as the description:purposeisgift, the list and payment screen call a sent one Gift and a received one Gift on your post, and those 64 hex digits are the payment hash when the payment has none of its own. A shop memo (pos:plus a charge id with no space) is not kept as the description:purposeisshopand the title is Shop payment. - Inputs: An SDK payment (
id,paymentType,status,amount,timestamp, optionalfees,method, anddetails). - Returns / side effects:
WalletPayment. Pure. - Used by:
loadWalletSdk(listPayments).
Function: toFixturePayment
- Purpose: Maps one synthetic SDK payment for the pinned wallet screens. Same mapping as
toWalletPayment, then the sent gift (df98837c-6a12-4b15-94f8-375c33937a4e) gets To @alice as a link to/members/acc_e2e. The title stays Gift. Other fixtures are unchanged. The SDK record itself has no address for that gift. - Inputs: One
PaymentfromWALLET_PAYMENT_FIXTURES. - Returns / side effects:
WalletPayment. Pure. - Used by:
useWalletHistoryanduseWalletPaymentunder the?visual=history-rowspin.
Function: toWalletReportPayment
- Purpose: Maps one SDK payment to the payment the wallet data report sends:
id,direction(inorout),status(an unknown status counts as completed), whole-satamountSatsandfeeSats,timestamp(ISO 8601 from the SDK's epoch seconds),method(lightning,spark,token,onchainfor the SDK'sdepositandwithdraw, otherwiseunknown), and the counterparty data the SDK lists:paymentHash(HTLC payment hash),invoice(Lightning or Spark request),destination(Lightning address, else LNURL domain, else base-chain transaction id, else the receiving node's public key),description, andlnurlComment(the comment sent, else the payer's note received). Blank texts arenull. - Inputs: An SDK payment (
id,paymentType,status,amount,fees,timestamp,method, optionaldetails). - Returns / side effects:
WalletReportPayment. Pure. Reads only the fields named above: the HTLC preimage and every other SDK field are never copied. - Used by:
loadWalletSdk(listReportPayments).
Function: ensureWalletConnected
- Purpose: Makes sure the wallet is open from the tab phrase and returns its identity public key. Reuses a ready connection and waits for one in flight; otherwise calls
connectWallet, also while the wallet is aterrorbetween automatic retries, which that call supersedes. - Inputs: Optional
WalletSdkLoader. - Returns / side effects: The identity public key. Throws
wallet-connectwithout a key or a tab phrase, or when the connection fails. - Used by:
runWalletSetup,receiveWalletSparkAddress,signWithWallet, anduseSocialRecoverySetup(Secure my account checks that the open wallet is the account's verified wallet).
Function: appHost
- Purpose: The host the app is served from (
window.location.host). The wallet's address lives on it, the app forwards the wallet's address calls to the api, and every wallet of the app connects and signs with it as its domain. - Inputs: None.
- Returns / side effects: The host, with a port when the page has one. Browser only.
- Used by:
connectWallet(thelnurlDomainofconnect) and the recovery flow on/recover(the domain of the old and new wallets and of the signed address lookup).
Function: receiveWalletSparkAddress
- Purpose: Reads the Spark address of the signed-in member's own wallet (
receiveSparkAddressof the connection), so a balance can be sent to it. - Inputs: Optional
WalletSdkLoader, forwarded toensureWalletConnected. - Returns / side effects: The address. Opens the wallet from the tab phrase first when it is not open yet. Throws
wallet-connectwhen the wallet cannot be opened or closed meanwhile, otherwise the SDK's error. - Used by:
transferRemainingBalanceon/settings/previous-wallets/[sparkPubkey], anddfxLoginUrlon/settings.
Function: signWithWallet
- Purpose: Signs text with the member's own wallet identity key. The signature is the SDK's compact r‖s hex over one SHA-256 of the UTF-8 text.
- Inputs: The text to sign, and an optional
WalletSdkLoaderforwarded toensureWalletConnected. - Returns / side effects: The signature hex. Opens the wallet from the tab phrase when it is not open yet. Throws
wallet-connectwhen the wallet cannot be opened or closed meanwhile, otherwise the SDK's error. The text and the signature are not logged. - Used by:
dfxLoginUrlon/settings(Log in at DFX).
Function: dfxLoginUrl
- Purpose: Builds the DFX Buy URL for the signed-in member's own in-app wallet: reads the Spark address, fetches DFX's sign-in text, checks it equals the expected prefix plus that address, signs it, and exchanges the signature for a session token. The token is only in the returned URL. Nothing is stored, and the address, the text, the signature, the token, and the URL are not logged.
- Inputs: Optional
WalletSdkLoader, forwarded toreceiveWalletSparkAddressandsignWithWallet. - Returns / side effects: The absolute
https://app.dfx.swiss/buyURL withsession,blockchain=Spark, andasset-out=BTC. The entire sign-in, including both requests and their response bodies, is limited toDFX_LOGIN_TIMEOUT_MS(15 seconds) from the start; reaching the limit aborts the request and rejects immediately, without sending a later request if the wallet completes late. Throwswallet-connectwhen the wallet cannot be opened. Throwsdfx-loginwhen that time limit is reached, when DFX answers non-2xx, returns a body that is not JSON, omits a non-emptymessageoraccessToken, or returns an unexpected sign-in text. A failed request rejects with that fetch error. PerformsGET https://api.dfx.swiss/v1/auth/signMessage?address=..., checks the returned text exactly before signing, and performsPOST https://api.dfx.swiss/v1/authwith{ address, signature, wallet: '21gifts' }. - Used by: The Log in at DFX row on
/settings(SettingsScreen).
Function: registerWalletAddress
- Purpose: Registers the account's username as the address of the connected wallet. Only the account's own username is sent; the app never asks whether a name is free.
- Inputs: Username.
- Returns / side effects: Resolves once the registration was accepted. Throws
wallet-connectwithout a connection, otherwise the SDK's error. Times the registration as the wallet spanwallet.address.register(traceWallet). - Used by:
runWalletSetup.
Function: listWalletPayments
- Purpose: Lists the connected wallet's Bitcoin payments, newest first, one page at a time.
- Inputs:
{ offset, limit }. - Returns / side effects:
WalletPayment[]. Throwswallet-connectwithout a connection, otherwise the SDK's error. - Used by:
useWalletHistory.
Function: getWalletPayment
- Purpose: Reads one payment of the connected wallet by its SDK id, for the
/wallet/paymentscreen. - Inputs:
id. - Returns / side effects: The mapped
WalletPayment. Rejects withwallet-connectwhile no wallet is connected, and with the SDK's error for an id the wallet does not know. No other network call than the SDK's. - Used by:
useWalletPayment.
Function: listWalletReportPayments
- Purpose: Lists the connected wallet's Bitcoin payments, newest first, one page at a time, in the shape the wallet data report sends (
WalletReportPayment). - Inputs:
{ offset, limit }. - Returns / side effects:
WalletReportPayment[]. Throwswallet-connectwithout a connection, otherwise the SDK's error. - Used by:
reportWallet.
Function: needsWalletSetup
- Purpose: Whether background wallet setup applies: the wallet is configured (
getBreezApiKey), the signed-in account requires a wallet and has its seed passkey (canUnlockWallet), has a username, andsparkWalletVerifiedis strictlyfalse. Older api bodies without the field never qualify. - Inputs:
Accountornull. - Returns / side effects: Boolean type guard. Pure; it neither starts setup nor prompts.
- Used by:
runWalletSetup,listenForWalletSetup,useWalletSetup,useWallet,useWalletPay,useWalletSend,useLoanRepay, andPosTill.
Function: runWalletSetup
- Purpose: Runs one background wallet setup for the current session without prompting. It waits for any login or sign-up phrase derivation to settle, returns
lockedwhen the recovery phrase is still absent from tab memory, then connects, sendsPUT /me/walletwith the lower-cased identity key, registers the username returned by that claim, and reloads the account. A 409 claim means the wallet is already verified and skips registration. Failed tries repeat quietly after 2 s, 5 s, and 15 s (WALLET_SETUP_RETRY_DELAYS_MS). - Inputs: Optional
WalletSdkLoader, defaulting toloadWalletSdk. - Returns / side effects: Promise of
done | locked | failed | superseded; never rejects and never opens a passkey prompt. Calls for the same session join one shared run across components and remounts. A session change yieldssuperseded. After the final failed try, stores that session assetupFailedSession; the phrase remains in tab memory only. - Used by:
retryWalletSetupandlistenForWalletSetup.
Function: retryWalletSetup
- Purpose: Explicit retry after background setup exhausted its attempts.
- Inputs: Optional
WalletSdkLoader, defaulting toloadWalletSdk. - Returns / side effects: Clears
setupFailedSession, then returns the promise fromrunWalletSetup; never rejects. - Used by:
useWalletSetup.retry.
Function: listenForWalletSetup
- Purpose: Root listener that starts background setup when the recovery phrase arrives, when the account changes (including a username saved during onboarding), and once immediately when subscribed. It starts only when the current account still needs setup and the phrase is in tab memory. A session recorded as failed is left alone until explicit retry.
- Inputs: Optional
WalletSdkLoader, forwarded torunWalletSetup. - Returns / side effects: Unsubscribe function. Subscribes to
SESSION_PHRASE_EVENTand the auth store, then performs the initial check. Without a configured Breez key it adds no listener and returns a no-op unsubscribe. - Used by:
WalletSync.
Function: useWalletSetup
- Purpose: Whether the one-time setup is still due, and state and retry action for the small setup-failure note on money screens.
dueisneedsWalletSetupof the signed-in account, or true under the?visual=setup-pendingpin (Playwright builds only).failedis true only while the account still needs setup andsetupFailedSessionmatches the current session, or while one of the three setup-note screenshot pins is active. - Inputs: None. Reads the auth and wallet stores,
needsWalletSetup,walletSetupPin, andvisualPin. - Returns / side effects:
{ due, failed, retry }.retrycallsretryWalletSetupin this page; it never reloads the page. A pinned fixture leaves retry inert. - Used by:
WalletSetupNote,useWallet,useWalletPay,useWalletSend,useLoanRepay,WalletReceive, andPosTill.
Function: walletSetupPin
- Purpose: Screenshot pin for the inline setup note on a money screen.
- Inputs: Reads
visualPin()and matchesbalance-setup-failed,wallet-pay-setup-failed, orpos-setup-failed. - Returns / side effects: Boolean. Because
visualPincentralizes the guard, returns false during SSR and in every deployed build. - Used by:
useWalletSetup.
Function: WalletSetupNote
- Purpose: Small, non-blocking setup-failure note used only on money screens after background setup gives up.
- Inputs: None. Reads translations and
useWalletSetup.retry. - Returns / side effects: A
role="alert"paragraph withwalletSetup.error(Your wallet could not be set up yet.) and a secondary Try againButtonunder it. Retry starts setup again in this page; it never reloads the page. - Used by:
WalletBalance(on/walletand/wallet/payment),WalletPay,WalletReceive,PosTill, andLoanRepayScreen.
Function: useIncomingPayment
- Purpose: The received payment that completed last while the app is open, kept for a given time after it arrived. One subscription (
onIncomingPayment) per caller and session (useAuthStore), none while signed out; a newer payment replaces the shown one and starts the time again. A payment belongs to the session it arrived in: it is never shown after that session ended or under another one. - Inputs:
holdMs(how long a payment stays shown). - Returns / side effects:
{ payment, dismiss }:paymentis theWalletPaymentornull,dismissstops showing it early. Clears its timer and unsubscribes on unmount. Under the?visual=wallet-receivedpin, honoured only in a Playwright build (visualPin), a fixed ₿500 received payment arrives on mount and is held forholdMslike a real one (the screenshots move Playwright's clock to reach the later states), without subscribing; a production build ignores the pin. - Used by:
HeaderBalance(2.4 s),ReceivedNotice(6 s).
Function: useCopied
- Purpose: Copy to the clipboard with a two-second Copied state, shared by the Receive view, the Settings address row, the move-funds flow, and the on-chain deposit address on
/fonds/[username]. - Inputs: None.
- Returns / side effects:
{ copied, copy }:copy(text)writestextwithnavigator.clipboard.writeText; each success showscopiedfor two seconds, counted again from each copy. A missing or refusing clipboard changes nothing. Clears its timer on unmount. - Used by:
WalletReceive,SettingsScreen(address row),MoveFundsSheet,FondDeposit(on-chain address).
Function: RECEIVED_FROM_MEMBER_PAYMENT
- Purpose: Provide a synthetic completed incoming Spark payment for screenshot coverage.
- Inputs: None; the fixture is fixed and outside the payment history list.
- Returns: An SDK payment of ₿200.
- Used by:
useWalletPaymentunder the Playwright pin.
Function: RECEIVED_FROM_MEMBER_SENDER
- Purpose: Provide the sender associated with the screenshot payment.
- Inputs: None; the fixture is fixed.
- Returns: Payment id, account id and username for Alice.
- Used by:
usePaymentCounterpartyunder the Playwright pin.
Function: SENT_TO_MEMBER_PAYMENT
- Purpose: Provide a completed outgoing Spark payment for screenshots.
- Inputs: None.
- Returns: A synthetic SDK payment of ₿200 with no fee.
- Used by:
useWalletPaymentunder the Playwright pin.
Function: SENT_TO_MEMBER_COUNTERPARTY
- Purpose: Provide Bob as the screenshot payment's counterparty.
- Inputs: None.
- Returns: Payment id, account id and username.
- Used by:
usePaymentCounterpartyunder the Playwright pin.
Function: isSparkPaymentRequest
- Purpose: Recognize Spark invoice and address prefixes.
- Inputs: A payment request string.
- Returns: Whether it begins with a Spark prefix.
- Used by:
WalletPaymentDetails.
Function: fetchPaymentCounterparties
- Purpose: Look up counterparties for wallet payments.
- Inputs: A session and payment rows containing only id and incoming or outgoing direction.
- Returns: Valid counterparty rows, or an empty list on failure or invalid response.
- Used by:
usePaymentCounterparty.
Function: usePaymentCounterparty
The api names the other side only from the transfer its own read of the wallet observed (about once a minute), so a name can be missing right after a payment and appear later; a payment whose other side is not a member wallet never gets one.
- Purpose: Resolve the counterparty of a completed Spark payment by id and direction, even without an invoice or hash. A Lightning, on-chain, deposit, withdraw, or token payment is not looked up, because the api names only plain Spark transfers. Each lookup first waits for a running wallet report without requesting another, because the api names only a payment the caller has already reported as completed. A match is cached for the mounted screen and its session by id and direction. After a miss the hook asks again after 15 s, 30 s, 60 s, and 120 s (at most five lookups per opened screen), then stops; a miss is never cached, so opening the screen again starts with a fresh lookup. A match stops the retries, and unmounting or a session change cancels a waiting retry and drops a late answer.
- Inputs: One wallet payment.
- Returns: Its counterparty or null.
?visual=received-from-memberand?visual=sent-to-memberreturn fixtures without a request.?visual=received-member-unknownand?visual=sent-member-unknownreturn null without a request. - Used by:
WalletPaymentDetails.
Function: proxyMeWalletCounterpartiesPost
- Purpose: Forward the counterparty lookup to the api.
- Inputs: A POST request with bearer session and payment identifiers.
- Returns: The upstream response.
- Used by:
POST /me/wallet/counterparties.
Function: fetchHeartPosts
- Purpose: Looks up the forum posts attached to wallet heart payments, and the credit notes behind loan repayments, through the same-origin
POST /me/wallet/heartsproxy. It lowercases the submitted hashes and accepts only complete, typed rows with a lowercase 64-hex payment hash. A repayment row (RepaymentContext) also needs a non-emptymessageId, an integerdayIndexof at least 0,termDaysas an integer of at least 1 ornull,roleborrowerorgiver, stringauthorNameandtext(either may be empty), and a booleandeleted. A body without arepaymentsarray (an api from before repayments) has no repayments; the hearts are read as before. - Inputs: A Bearer
sessionTokenand paymenthashes(the caller sends chunks of at most 32). - Returns / side effects:
{ hearts, repayments }(HeartLookup): validHeartPost[]andRepaymentContext[], with malformed elements dropped from each; both are[]without throwing after a network error, non-2xx response, or bad body. - Used by:
useHeartContext.
Function: useHeartContext
- Purpose: Resolves the current wallet view's unique lowercase payment hashes to heart posts and to loan repayments (
repaymentsByHash), with the same cache, chunks, pending set, and stale-response guard for both. A hash the api returns in both arrays stays a heart. It usesuseActiveSession, requests sequential chunks of at most 32, exposes unresolved hashes aspending, keeps settled results for this mounted hook, requests only newly added hashes, and ignores stale responses after the hash set changes. In a Playwright build,?visual=heart-paymentand?visual=history-heartreturn the Sunday lunch post and an empty pending set without callingfetchHeartPosts, and?visual=heart-payment-pendingand?visual=history-heart-pendingreturn an empty map and a pending set containing only the visual heart hash, also without a fetch.?visual=repayment-paymentand?visual=history-repaymentreturn the two repayment fixtures (REPAYMENT_VISUAL_CONTEXTS: Ben's note, day 3 of 7, as giver, and Mia's, day 5 of 10, as borrower), no hearts, and an empty pending set without a fetch. A production build ignores all six pins. - Inputs: Readonly payment-hash array.
- Returns / side effects:
{ byHash, repaymentsByHash, pending }; all are empty without an active session or hashes. Failed and unmatched hashes leavependingonce settled, are in neither map, and are not retried by a same-input re-render. - Used by:
WalletHistory,WalletPaymentDetails.
Function: useWalletHistory
- Purpose: The
/walletpayment list: loadsWALLET_HISTORY_PAGE_LIMIT(20) payments newest first once the wallet is ready, appends the next page onloadMore(skipping ids it already has), and reloads every loaded page wheneveruseWalletStore.syncCountchanges, which happens after connect and after each SDKsyncedevent, so the list does not depend on payment events. Only the latest load writes state. A failed later page stops paging quietly.?visual=history-empty|history-rows|history-heart|history-heart-pending|history-repayment|history-errorpins a fixture list only in a Playwright build;history-heartandhistory-heart-pendingare the single heart fixture payment,history-repaymentis the received and the sent repayment fixture (REPAYMENT_GIVER_VISUAL_PAYMENT,REPAYMENT_BORROWER_VISUAL_PAYMENT), andhistory-rowsisWALLET_PAYMENT_FIXTURESmapped withtoFixturePayment(ten synthetic payments covering a zap, a sent gift, a Spark receive, a Lightning-address send with a fee, a received note, a pending and a failed send, an on-chain deposit and withdrawal, and a shop payment, netting to the ₿21'000 visual balance). - Inputs: None.
- Returns / side effects:
{ status, payments, hasMore, loadMore, retry }. - Used by:
WalletHistory.
Function: ShopChargeFigureState
- Purpose: What a shop payment row shows before and after its receipt: whether that read is still out, and the stored figure once it is known.
- Inputs: None. The shape is
{ pending: boolean, figure: { code, amount } | null }. - Returns / side effects:
pendingis true until the receipt read settles, and false when the payment is not a shop charge.figureis null while pending, on a miss, or when this is not a shop charge. No I/O of its own. - Used by:
useShopChargeFigure,WalletPaymentDetails,WalletHistory.
Function: useShopChargeFigure
- Purpose: Receipt figure of a shop payment. A payment whose
purposeisshopand whosechargeIdis a string loads that receipt withfetchShopChargeReceipt. While the read is pending,figureis null andpendingis true. A 404 or any other failed read (receiptnull) staysfigurenull. A receipt then goes throughcommittedFiatFigurewith the visitor's fiat as preferred. It does not read the spot. A payment that is not a shop charge does not fetch:pendingis false andfigureis null. - Inputs: Payment method details, or
nullwhen there is no payment (purpose,chargeId,lnAddress). The Lightning local part is the text before@when both sides are non-empty and the local part has no space; otherwise the username passed to the receipt read is null. - Returns / side effects:
ShopChargeFigureState. Fetches only for a shop charge. - Used by:
WalletPaymentDetails(PaymentView),WalletHistory(HistoryFiat).
Function: WalletHistory
- Purpose: Payments card on the
/wallethome under the balance card while the wallet is ready. Each row is anext/linkto its/wallet/paymentscreen (paymentHref) with a chevron on the right: normally the received or sent icon and the title (paymentTitle: Gift on your post for a zap, Gift (sent) or Gift on your post (received) for a gift memo, Shop payment for a shop memo, the paid Lightning address, the description, On-chain deposit / On-chain withdrawal, else Received / Sent). A gift hash on a payment that is not still pending, resolved byuseHeartContext, instead shows the filled accent heart and one line of the post (newlines become spaces, falling back to the author name) instead of the gift title. A payment that is still pending keeps the direction icon and the gift title and is not looked up. A payment hash thatuseHeartContextnames a loan repayment, for the member as giver or as borrower, shows the lucideHandCoinsicon in the accent colour and the title Loan repayment (wallet.payment.repayment), and the line under the date is the credit note text on one line, falling back to the author name, and nothing when both are empty. Every payment that is not still pending, has a payment hash, and is not a shop payment is looked up (paymentLookupHash), so a repayment received over the Lightning fallback, which has no memo, is found too. While a lookup is pending the direction icon and the gift title stay. Neither gift nor shop memo is shown as the description, and a gift memo's 64 hex digits are the payment hash when the payment has none of its own. The amount is signed+or−(a failed one struck through and muted); under it are the date and time, then Pending or Failed (failed in the danger colour) when not settled, and the current spot on the right when no stored figure is showing (bitcoin alone only when that spot is not loaded, and no fiat while a shop receipt is still loading). A shop or till charge shows the currency figure stored on that charge throughuseShopChargeFigureonce the receipt returns, and does not use the spot; while that read is pending, on a 404 or a failed read, and for every other payment, the row shows the current spot when no stored figure is available, and bitcoin alone only when that spot is not loaded or the shop receipt is still loading; a third line has the message (paymentMessage: payer note, zap message, or the comment sent to a Lightning address; never a loan repayment'srepay:marker), truncated, or the credit note line of a repayment. Empty: No payments yet. Error: one sentence and Try again; the error stays shown until the reload's result arrives. Nothing renders during the first load. - Inputs: None (reads
useWalletHistory,useHeartContext,useShopChargeFigure, and number format). It readsuseSpotRatefor the spot beside a row that has no stored figure. - Returns / side effects: The card, or
null. The next page loads when the end of the list is in view (IntersectionObserver), checked again after every completed load and after an error and retry. - Used by:
WalletScreenView.
Function: WalletBalance
- Purpose: Balance block on the
/wallethome for connecting, ready, and error states. There is no locked state because the gate only reveals this screen after the wallet is open. Connecting readswallet.downloading(Downloading wallet…) while the wallet code is still being downloaded, andwallet.connecting(Opening your wallet…) after that. It renders nothing when disabled. Requests the spot rate only inready. The ready balance is a large Bitcoin figure; when the default fiat has a usable rate, each tap swaps which amount is large. Without a usable rate only Bitcoin appears. - Inputs:
status(WalletViewStatus),balanceSats,onRetry, optionalsetupFailed(default false), and optionaldownloading(default false). - Returns / side effects: A region named Balance, or
nullwhen disabled. An ordinary error showswallet.balanceErrorand Try again; withsetupFailedit rendersWalletSetupNoteinstead. Keeps which ready figure is large in component state, Bitcoin first on every mount. - Used by:
WalletScreenView.
Function: payFromWallet
- Purpose: The wallet pay primitive. Prepares a payment on the current connection and returns amount and fee for confirmation; the returned
sendpays it once, gives up waiting after 30 s (failedwithsentLate, because the payment may still complete), and refreshes the balance while its connection is still the current one (a replaced connection reads its own synchronized balance). Nothing is retried. A send after the wallet was disconnected or replaced, or a second call ofsend, reportsfailedwithout paying. For a base-chain address the result carriesonchain(feesper speed andspendableFeeSats, the balance minus the amount) andsendtakes the chosen speed. It never sends without a fresh quote: a speed whose fee is abovespendableFeeSatsisinsufficient, and a quote withinWALLET_QUOTE_MARGIN_MS(15 s) of its expiry isexpired, both without calling the SDK. - Inputs:
WalletPayRequest:{ type: 'input', input, amountSats? }or{ type: 'lnurl', request, amountSats, comment? }. - Returns / side effects:
confirm(amountSats,feeSats, optionalonchain,send),insufficient(the balance read before confirmation does not cover amount plus fee, for a base-chain address amount plus the lowest fee, with that fee asfeeSats, or the SDK says so, without a fee),belowMinimumwithminSats(the SDK refused the amount as below the smallest it sends to this address,… below the minimum of N sats …),failed(prepare or the balance read failed, or the connection changed during prepare or that read), orunlock(no connection). The synced balance read also updatesuseWalletStorewhile it is the latest read of the current connection; when a newer read already wrote the store, the check uses that newer balance, so it matches the balance shown; while a newer read is still pending, it uses its own read.sendresolves topaid,insufficient,failed(an error or the 30 s limit), orexpired(a base-chain quote that ran out, before the SDK or as its answer; nothing was sent). Never rejects.confirmalso carriesmethod(lightning,spark,onchain,lnurl, orunknown: read from the request, andonchainonce the SDK quotes a base-chain fee). Times the prepare and the send as the wallet spanswallet.prepareandwallet.send, each with only itsroute(spark,lightning, oronchain, from the request'smethod: an LNURL receiver islightning, ansp1…address isspark, anything else unknown isonchain) (traceWallet). The send's route isonchainwhen the prepare returned a base-chain fee quote,lightningwhen the request read asonchainbut the prepare returned no such quote (a base-chain URI the SDK pays over Lightning), and otherwise the prepare's route. In a Playwright build only,?visual=repay-e2e-paymentturns a test Spark input ending in its sat amount into a zero-fee confirmation whose send posts/e2e/wallet-send; production always ignores that pin. - Failure details: Every outcome that does not pay carries
failureforreportPaymentFailure;payFromWalletreports nothing itself, because its callers may prepare again (an expired quote, a Spark invoice with a Lightning fallback, a heart after unlock).failureholdsstage(prepare;confirmfor asendrefused before the SDK is asked;sendfor the SDK's send),reason,method,amountSats(the request's amount before prepare, the prepared amount after),feeSats(the chosen speed on the base chain), the base-chainonchainFees, and the SDK rejection aserror. Reasons:unlock(no connection),insufficient,below_minimum,disconnected(the connection changed during prepare, the balance read, or beforesend),balance_read,already_sent(a secondsend),expired, and for an SDK rejection the shape of its message:expired,no_route,timeout(also the 30 s limit, withsentLate),network,lnurl_error, otherwisesdk_error. The message is read only to classify, never reported: the text of anErroror a thrown string; anything else, or a rejection whose message cannot be read (a throwing getter), classifies assdk_errorwithout converting it. - Interaction log: A send the SDK reports as sent is recorded as
payment_sentwith the amount, the fee of the chosen speed, and whether it went to a base-chain address, under the session of the send. When the app stops waiting afterWALLET_SEND_TIMEOUT_MS,sendanswersfailedwithsentLate, which resolvestrueand recordspayment_sentif the SDK still reports the send, orfalseif it fails. - Used by:
useWalletPay(gift pay sheets),useWalletSend(/wallet),sendHeartTip,useLoanRepay(the last throughpayInvoiceSparkFirst, asuseWalletPay).
Function: payInvoiceSparkFirst
- Purpose: Prepares one api invoice in the in-app wallet, Spark first, so a payment between two 21.gifts wallets moves as a Spark transfer without a Lightning fee, and still goes over Lightning when the wallet cannot use the Spark invoice. The Spark invoice is the api's per-payment request to the receiving member's wallet; the app never sees or shows a member's Spark address.
- Inputs:
pay(the wallet prepare:payFromWallet, or the injected one of the Fond loop), the invoice{ sparkInvoice, pr }(sparkInvoicemay benull,undefined, or''when the api issued none;pris the Lightning payment request of the same invoice), and an optionalonSparkFailurecallback. - Returns / side effects: The
WalletPayResultof the Spark prepare, or ofpr. Without a Spark invoice it preparesprat once. When the Spark prepare isfailedwith reasonsdk_error(the wallet refuses that Spark invoice),onSparkFailuregets its failure andpris prepared instead. Every other Spark outcome is returned as it is (confirm,insufficient,belowMinimum,unlock, andfailedforexpired,timeout,network,disconnected, orbalance_read), because Lightning would stop on the same cause. It only prepares: the fallback is chosen before anything is sent, and the caller sends at most one of the two. - Used by:
useWalletPay,useLoanRepay,runFondPayoutTick.
Function: errorCause
- Purpose: What a report may say about a thrown value: its name, a code, and a cause kind from a fixed table, never the value itself and no part of its message.
- Inputs: Anything that was thrown or rejected with.
- Returns / side effects:
{ errorName, errorCode, causeKind }.errorNameis the error'sname, or its constructor's name, when it is on a fixed list: the built-in JavaScript and WebAssembly error classes (TypeError,RangeError,RuntimeError, …),DOMExceptionand its names (QuotaExceededError,AbortError,TimeoutError, …),ChunkLoadError, and the app's own error classes; otherwiseunknown, so a name set to anything else (a key, a user name) is never sent. A thrown string or number reports its type (string,number); any other thrown value that is not an object (a boolean, a bigint, a symbol, a function,null,undefined) reportsunknown.errorCodeis the error's owncodewhen it is a whole number of up to six digits (aDOMException's, so-1,1.5, or1e+21is no code) or one of a short list of known constants (network codes such asECONNRESETandETIMEDOUT, and the legacyDOMExceptionnames such asQUOTA_EXCEEDED_ERR), or else the SDK's error kind at the start of its message when it is one of the kinds the wallet SDK writes (Network error: …→network,Service connectivity error: …→service_connectivity), otherwisenull. Both are lists, not shapes, so a key or a name written as a code, or other text beforeerror:, is never sent.causeKindis the first row ofCAUSE_KINDSthat matches the error's own name, code, and message (or a thrown string), compared on the device by whole string, start, or end only, never by a pattern:wasm_out_of_memory(WebAssembly.…: out of memory,out of memory),wasm_unreachable(aRuntimeErrorunreachablein each browser's wording),wasm_runtime(any otherRuntimeError),chunk_load_failed(ChunkLoadError, a failed dynamic import in each browser's wording),fetch_failed(Failed to fetch,NetworkError when attempting to fetch resource.,Load failed),storage_quota(QuotaExceededError,The quota has been exceeded.),sdk_network,sdk_service_connectivity,sdk_storage(the SDK's error kind),timeout(TimeoutError),aborted(AbortError); anything else isunknown. Only the identifier leaves the function, never the text it was matched against. The lists and the table are frozen, and matching uses only indexed loops,===, and string checks taken when the module loads; the error'sname,message,code, andconstructorare each read once before anything is compared, so nothing a thrower changes while the error is read (a built-in method, a row of the table) decides the result. Any other field of the error (a stack, a cause, a config, a phrase, raw bytes) is never read into the result. An error that cannot be read (a throwing getter) reports onlyunknown. Never throws. - Used by:
connectWalletandrefreshWallet(theWallet did not openreport and thewallet_open_failedevent).
Function: reportPaymentFailure
- Purpose: Reports a payment from the in-app wallet that did not go out, so it is known when members cannot pay, why, and how often.
- Inputs: A
PaymentFailure(stageprepare|confirm|send, a shortreasoncode,methodlightning|spark|onchain|lnurl|unknown,amountSats,feeSats, optionalonchainFeesanderror, aspayFromWalletor the screen built it), thePayFlowthat started it (sendfor the/walletSend view,posfor a shop charge read there,giftfor a gift on a note, reply, or habit comment,reactionfor a paid reaction,post_feefor the posting fee,repayfor a loan repayment on/loans/repay,inboxfor the inbox pay sheet,heartfor a heart,recoveryfor the balance move of a social recovery on/recover,previous_walletfor Transfer remaining balance of a previous wallet,fond_payoutfor the automatic Fond payout loop), and optionally thesessionthe payment ran under and thesentLateof a timed-out send. - Returns / side effects: None. Records the member event
payment_failedwithstage,reason,method,flow, andamountSats(scalars only; dropped whensessionis no longer the current one). SendscaptureMessage('Payment failed')at levelerrorwith the fingerprint['payment-failed', stage, reason](one issue per stage and reason, not one per payment), the tagspay_stage,pay_reason,pay_method, andpay_flow, and the extrasamountSats,feeSats,onchainFees,errorName, anderrorCode. No text of the rejection is ever reported, because SDK and api messages can carry invoices, addresses, or keys:errorNameis theErrorsubclass name when it is on a fixed list (the built-in error classes,AbortError,TimeoutError,NetworkError,ZodError, and the app's own error classes such asLnurlRelayError; any other name isError), or the JavaScript type of anything else (a thrown string or byte array isstringorobject);errorCodeis the relay'sreason(LnurlRelayError) or the SDK's error kind at the start of its message (Network error: …→network, letters only), otherwisenull. A rejection that cannot be read (a throwing getter) keeps only its name, so reporting never throws. The event still passes thebeforeSendscrubber (seesentryOptions). Member state (unlock,insufficient,below_minimum) and hearts (which keepHeart not sent) are never sent to error reporting, only recorded. AtimeoutwithsentLateis sent to error reporting at once;payment_failedfollows only whensentLateresolvesfalse, and a send that still went out is sent once more assent_late(it was paid, so no member event). Nothing goes to error reporting while it is off. - Used by:
useWalletPay,useWalletSend,sendHeartTip,useLoanRepay,transfer(the balance move of a social recovery),transferRemainingBalance,runFondPayoutTick.
Function: sdkFailureReason
- Purpose: Short reason code of a wallet SDK rejection, so a payment that did not go out is reported by kind and never by its text.
- Inputs: The SDK's rejection (any thrown value).
- Returns / side effects: A
PayReason, from the shape of the message only:insufficient(the SDK says the funds do not cover it),expired,no_route,timeout,network,lnurl_error, otherwisesdk_error(also for a value whose message cannot be read). The text is read only to classify and is never returned. A refused minimum is read bypayFromWalletitself, since it carries the minimum. - Used by:
payFromWallet(prepare and send),transfer(a failed balance send of a social recovery),transferRemainingBalance(a failed send of a previous wallet).
Function: parseWalletInput
- Purpose: Reads a pasted payment request or address with the SDK's
parseon the current connection. - Inputs: Text as pasted; it is trimmed.
- Returns / side effects:
targetwith theWalletTarget,invalidfor blank or unreadable text,unreachablewhen text that names a receiver byname@domainor LNURL cannot be read (the receiver's server did not answer this browser; there is no relay), orunlockwithout a connection or when the connection changed while the text was read. Never rejects. - Used by:
useWalletSend.
Function: useWalletPay
- Purpose: Runs the in-app wallet payment of one gift-sheet invoice. The wallet pays
sparkInvoicewhen the api issued one, otherwisepr; a Spark invoice the wallet refuses at prepare falls back topr(payInvoiceSparkFirst). A wallet that is unavailable or the account cannot hold reportsunavailable. Because the wallet is open whenever the member is signed in, there is no passkey or unlock phase: the hook connects and prepares, then always stops atconfirm, including for a zero fee. While setup is due it reportspreparing; if setup gives up, it reportssetupFailedand no payment continues by itself. - Inputs:
sparkInvoice(string,null, orundefined),pr(fallback request for the same invoice),amountSats(the exact whole-sat amount the sheet shows), andflow(thePayFlowof the sheet). Reads the auth store,useWalletStore, anduseWalletSetup. - Returns / side effects:
{ view, sent, feeSats, missingSats, pay, retry }.sentsays where the last send stands:pendingfrom Send until the wallet answers (a send the app stopped waiting for stayspendinguntil itssentLateresolves),paidonly once it went out,nullbefore a send and after one that did not go out; a pinnedpayingorunconfirmedview reportspaid. Views areunavailable,preparing,confirm,paying,insufficient,failed,setupFailed, orunconfirmed. It prepares only after setup is no longer due, never pays a mismatched or stale request, pays at most once, and never retries a send automatically.payis the only send trigger. An insufficient view polls a synchronized balance every 4 s and prepares again only after the balance covers amount plus known fee; after any send, 60 s without sheet confirmation becomesunconfirmed. Retry clears prepared state and reconnects in this page after a wallet error; it never reloads the page. Recognized?visual=wallet-pay-…values pin deterministic views only throughvisualPinand leave actions inert. - Interaction log: A send the SDK reports as sent is recorded as
gift_sentwith the amount, also when the sheet closed before the send finished. A send the app stopped waiting for is recorded asgift_sentonce itssentLateresolvestrue. - Failure report: Every prepare that does not reach
confirm(alsoinsufficient, and a refused Spark invoice before its Lightning fallback), a prepared amount other than the sheet amount (amount_mismatch), and every send that does not pay (also after the sheet closed, with itssentLate) goes toreportPaymentFailureunderflow, the sheet amount, and the session at the start of the prepare or send. A prepare whose sheet moved on meanwhile is not reported. - Used by:
WalletPay.
Function: WalletPay
- Purpose: Pay slot of the
PaySheet: the forum gift, the money reaction, the posting fee, the habit comment gift, and the inbox. It pays only from the in-app wallet and never offers an invoice QR, an address, or another wallet. The wallet is already open for every signed-in member. The slot shows Checking your wallet… while connecting, preparing, or waiting for background setup; after preparation it shows one full-width primary button: theconfirmLabel(Send {amount}, or Lend {amount} on a loan that still collects, with the amount's fiat, for example Send ₿21 · $0.02), Pay {amount} and post without a fiat suffix for a posting fee, or Send when no label is passed. A fee row with the preferred-fiat suffix sits above that button only when the quoted fee is nonzero; in-app payments normally quote no fee, so the row is usually absent. Too little balance shows the missing amount and Add Bitcoin (AddBitcoinButton), which closes the sheet and opens the wallet's Receive view. - Inputs:
sparkInvoice,pr,amountSats,rateDay,flow(thePayFlowpassed touseWalletPayfor its failure report), optionalchargeFigure(a stored{ code, amount }shown as-is;nullor omitted uses the current spot), optionalpostsOnPay(default false; Pay {amount} and post stays bitcoin only), and optionalconfirmLabel(a function from the amount with its fiat — a passedchargeFigureas-is, otherwise the current spot, or bitcoin alone when neither exists — to the text of the confirm button instead of Send). - Returns / side effects: React slot for the current
useWalletPayview in oneflex w-full flex-col items-stretch gap-3column.failedshows its alert and a full-width secondary Try again.setupFailedrendersWalletSetupNote:walletSetup.errorand a secondary Try again button.preparingandpayingshow a spinner and status;confirmshows thesize="lg"button (or Pay {amount} and post whenpostsOnPay), with the fee row only for a fee above ₿0;insufficientshows the alert, Still missing with fiat, and Add Bitcoin;unconfirmedis neutral. Inside aPaySheetit reports throughusePaySheetSentwhether a payment is out (payingorunconfirmed), so the sheet shows its success step only for a payment that went out. A view change shows at once (the sheet has no motion inside its pay slot). - Used by:
ForumPaySheet,ForumReplyPayPage, andInboxScreen. Loan repayments useLoanRepayScreen, not this invoice slot.
Function: useWalletSend
- Purpose: Drives the
/walletsend flow. Only the steps that need the open wallet wait for it: the SDK read of the text (parseWalletInput) and the prepare that gives the fee (payFromWallet). Everything else runs at once, also right after login while the wallet still opens: a Lightning address or LNURL on another host is read through the api, a shop on this host is asked for its open charge, and the amount step never waits. A text the wallet has to read is kept on the input step while the wallet opens (walletWaitopening,busy) and read on its own once the wallet is ready. A payment whose fee is not known yet shows thequotestep (amount and recipient, no fee) and is prepared on its own once the wallet is ready, then showsconfirm. While the wallet cannot be opened (useWalleterror, also when the one-time setup gave up),walletWaitiserrorandretryWalletopens the wallet again (useWalletretry) or runs the one-time setup again (useWalletSetupretry); the text and the step stay. When the account has no wallet it can use here (useWalletdisabled), a step that needs the wallet ends on the input step with theunavailablealert at once. The wallet SDK has no read without an open connection, and its prepare takes the receiver details its own read returned, so the read of such a text waits instead of being done twice. Paste, thenparseWalletInput. A 21.gifts shop on this app's own host (ownShop: its address, LNURL, or/pl/?lightning=link) is asked first for an open charge (fetchShopChargeInvoice); with a Spark invoice,payFromWalletprepares that invoice and the confirm step shows<name>@<host>, the charge amount, and the wallet's fee for it (₿0). No charge, no Spark invoice, a failed prepare, or a prepared amount other than the charge falls back toparseWalletInputbelow; a balance too low for the charge shows theinsufficientalert. When that own-host member has no open charge (none), the amount step that follows marks the receiver as that member and names it<name>@<host>asownShopwrites it: Continue first asksfetchMemberSparkInvoicefor a Spark invoice of exactly the amount entered, with the message trimmed and cut to the receiver's limit, andpayFromWalletprepares it, so the confirm step shows To <name>@<host>, the amount, and Fee ₿0. No Spark invoice, a failed prepare, or a prepared amount other than the one entered pays the member over Lightning as below (fee as the wallet quotes it); a balance too low for the Spark invoice shows theinsufficientalert. An open charge without a Spark invoice (fallback) and a failed charge payment do not ask the member again. Other own-host LNURLs (not an address) and addresses on another host never ask for a Spark invoice. A request with an amount is prepared at once. A request or address without an amount asks for an amount (1 sat upward); a Lightning address or LNURL receiver asks for an amount within its bounds and, when it takes one, a comment cut to its limit. A Lightning address or LNURL receiver whose whole-sat bounds are one amount (min equals max, also after rounding millisats) skips the amount step: that amount goes the same way as Continue in the amount step (payFromWallet, orpostLnurlInvoicethenpayFromWalletfor another host), without a comment, and Cancel on its confirm step returns to the input; an api refusal of that amount (Amount out of range,Comment too long, or any other) returns to the input with its alert (failedfor those two), never to an amount step. The recipient of an LNURL for/.well-known/lnurlp/<name>(bech32,lightning:, or anhttps/pl/?lightning=link) is<name>@<host>(lnurlPayAddress); another LNURL keeps its domain. Confirm shows amount, fee, and recipient; Send pays once. A base-chain Bitcoin address (or abitcoin:URI that offers only one) asks for an amount (1 sat upward); a URI amount is prepared at once. When the SDK refuses the amount as below its minimum, the amount step opens again with the amount alert naming that minimum, and later amounts below it are refused without asking the SDK again. Its confirm step carriesonchain: the fee of each speed, the largest fee the balance covers, and the chosenspeed(medium, or slow when the balance does not cover medium);setSpeedchooses another covered speed andfeeSatsfollows it. Send sends with that speed. When the quote expired (expired), nothing is sent: the same payment is prepared again and the confirm step returns with the new quote, the same speed when the balance still covers it, andrenewed; when the wallet can no longer send by then, that prepare waits on thequotestep for the wallet. Unreadable text, a recognised request this wallet cannot pay yet, an unreachable receiver, a failed prepare or send, and a low balance return to the input with an alert. A read whose handler throws unexpectedly ends with theunreadablealert (a prepare that throws, withfailed), so a pasted, typed, or scanned text never leaves the input step silent. A Lightning address or LNURL on another host (lnurlRelayTarget) skipsparseWalletInput:postLnurlPayRequestgives the bounds (whole sats, at least 1) and comment length,postLnurlInvoicereturns the invoice for the amount in millisats, andpayFromWalletprepares that invoice; a prepared amount other than the one entered fails.Not a payable address,Address not found, andAddress could not be reachedreturn to the input with thenotPayable,notFound, andrelayUnreachablealerts;Amount out of rangeandComment too longkeep the amount step with the amount or comment alert; anything else, or no session, isfailed; these api answers do not wait for the wallet, and only an answer that arrives after Cancel, a closed view, or a new read is dropped. No send is retried on its own; only an expired fee quote is prepared again, before anything is sent. Cancel and the header Back close the amount, quote, confirm, or sent step (also dropping a prepare that waits for the wallet); while a confirm send is in flight, both keep the confirm step (the header Back still closes it while an expired quote is renewed, dropping the renewal). A step that needs the wallet waits while the account is in the one-time wallet setup (needsWalletSetup). When the wallet leavesready, the amount step stays, an idle confirm step becomes thequotestep again (its prepared payment belonged to the closed connection), and a read or prepare whose answer arrives meanwhile waits again (one that rejects still ends with theunreadableorfailedalert); a send in flight is kept. When the account leaves wallet mode while a step waits, the flow ends on the input step with theunavailablealert. A waiting step runs once the store reads the wallet as ready, checked again on every hold, so a store that is ready again before the next render still runs it. Every time the store leavesready(also between two renders) starts a new wallet opening: a read or prepare that started on an earlier one runs again instead of using its answer, an idle confirm step prepared on an earlier one quotes again on its own, and Send pressed before that re-quote quotes again instead of sending. A shop charge's fallback read that starts after such a re-quote belongs to the current run. - Failure report: A prepare that ends the payment goes to
reportPaymentFailurewith the amount asked for and the session at its start: a failed prepare,insufficient,belowMinimum, a prepared amount other than the one expected (amount_mismatch), and a handler of the current run that threw (app_error). A prepare that runs its fallback (the shop's or member's Spark invoice before the Lightning or wallet read) is not reported; the fallback reports its own outcome. A send that does not pay is reported with itssentLate, also when its step was closed meanwhile, except an expired base-chain quote of the current step, which is prepared again instead. An api refusal of the invoice for another host's receiver is reported at stageprepare, methodlnurl, asrelay_not_payable,relay_not_found,relay_unreachable,relay_amount,relay_comment, orrelay_failed. The flow isposfor a shop charge, including the wallet read its failed Spark attempt falls back to (one report when both fail), andsendotherwise; an amount the member types after that fallback is their own payment and reports assend. Reading the text (the SDK read or the api's pay request) is not a payment and is not reported. - Inputs: None.
- Returns / side effects:
{ state, busy, walletWait, retryWallet, sending, text, setText, comment, setComment, submitInput, submitAmount, setSpeed, confirm, cancel, abandon };sendingis true only while a confirmed payment is being sent, sobusywithout it on the confirm step is the renewal of an expired quote.walletWaitisopeningorerrorwhile a read on the input step, or thequotestep, waits for the wallet, otherwisenull.abandonleaves the flow on an empty input step without an alert and drops a read, prepare, or quote renewal in flight (a late answer changes nothing); it does nothing while a confirmed send is in flight or under a pin.state.stepisinput(witherror, one of which isunavailable),amount,quote(recipient and amount, before the fee is known),confirm, orsent(with the amount and the recipient of the confirmed payment).?visual=send-input|send-amount|send-amount-error|send-amount-request|send-amount-no-comment|send-amount-min|send-confirm|send-confirm-sending|send-confirm-fixed|send-confirm-shop|send-confirm-member|send-input-busy|send-amount-busy|send-sent|send-amount-onchain|send-amount-onchain-min|send-confirm-onchain|send-confirm-onchain-fast|send-confirm-onchain-slow|send-confirm-onchain-low|send-confirm-onchain-renewed|send-confirm-onchain-renewing|send-confirm-onchain-sending|send-unsupported|send-invalid|send-failed|send-insufficient|send-error|send-not-payable|send-not-found|send-relay-unreachable|send-unavailable|send-unreadable|send-comment-long|send-input-opening|send-input-wallet-error|send-confirm-opening|send-confirm-opens|send-confirm-wallet-errorpins a fixture step (recipientbob@example.com,₿2'100, fee₿0; the request target issp1qexample…a9f2;send-confirm-fixedis the confirm step of the point-of-sale QR ofshop@21.gifts, named throughlnurlPayAddress, for₿7'000with the Lightning fee₿3, andsend-confirm-shopthe same step paid with the shop's Spark invoice, fee₿0;send-confirm-memberis the confirm step of₿2'100to the memberalice@21.giftswithout an open charge, paid with that member's Spark invoice, fee₿0; the base-chain pins usebc1qar0srr…wf5mdq,₿50'000, and the fees fast₿2'840, medium₿1'420, slow₿710:send-amount-onchainits amount step,send-amount-onchain-minthat step with the SDK minimum₿294,send-confirm-onchainits confirm step on medium,send-confirm-onchain-faston fast,send-confirm-onchain-slowon slow,send-confirm-onchain-lowwith a balance that covers at most a₿2'000fee, so fast is disabled, andsend-confirm-onchain-renewedafter an expired quote) for screenshots, only in a Playwright build;send-confirm-sendingandsend-confirm-onchain-sendingalso report a send in flight (busyandsending);send-confirm-onchain-renewingreports a quote being renewed (busywithoutsending);send-input-openingandsend-input-wallet-errorpin a read on the input step that waits for the wallet (walletWaitopeningorerror,busy),send-confirm-openingandsend-confirm-wallet-errorthequotestep of₿2'100tobob@example.com, andsend-confirm-opensthatquotestep untilWALLET_SEND_PIN_OPEN_MS(1.5 s) later, when it shows thesend-confirmfixture; undersend-confirm-wallet-error,retryWalletshowsopeningand the same fixture that long after (undersend-input-wallet-errorit only showsopening); actions are inert while pinned (and under any?visual=balance-…,?visual=history-…, or other?visual=send-…value in a Playwright build), except that undersend-input-busyandsend-amount-busyContinue marks that step busy, and under an idle base-chain confirm pinsetSpeedchooses a covered speed. - Used by:
WalletScreen,WelcomeScreen.
Function: walletSendBounds
- Purpose: Smallest and largest amount a send target takes.
- Inputs: A target that needs an amount.
- Returns / side effects:
{ min, max }: the receiver's bounds for an LNURL or an outside address read through the api; for a base-chain address the SDK minimum once a prepare named it, otherwise 1 sat, upward; otherwise 1 sat upward. - Used by:
useWalletSend,WalletSend.
Function: ownShop
- Purpose: Finds the 21.gifts shop on this app's own host that a pasted or scanned text pays, so the
/walletsend flow can ask it for an open charge: a Lightning address<name>@<host>(an optionallightning:prefix is removed), or an LNURL ofhttps://<host>/.well-known/lnurlp/<name>(bech32,lightning:, or in anhttps/pl/?lightning=link, read throughlnurlPayAddress). The own host is the onelnurlRelayTargetuses (giftsLightningAddressof this page; case,www., and a trailing dot are ignored; a local boot counts as21.gifts). - Inputs:
textas pasted or scanned,hostname(window.location.hostname). - Returns / side effects:
{ name, address }with the lower-case name and<name>@<own host>, ornullfor an address or LNURL on another host and any other text. Pure. - Used by:
useWalletSend.
Function: fetchShopChargeReceipt
- Purpose: Load the receipt of a shop charge. A Lightning address with a local part uses
GET /pay/:username/charges/:id. Otherwise (usernamenull) it usesGET /pay/charges/:id. A 404, any other non-OK response, or a body that is not a receipt is missing. - Inputs:
chargeId(the text afterpos:) andusername(the local part of the paid Lightning address, ornull). The shop hook never passes''. - Returns / side effects: The receipt, or
null. A failed read does not throw. - Used by:
useShopChargeFigure.
Function: fetchShopChargeInvoice
- Purpose: Spark invoice for the open charge of a 21.gifts shop, so the in-app wallet pays that charge without a fee.
GET /pay/:username; when itschargeis pending (or carries no status) and has not run out,POST /pay/:username/invoicewith{ amountSats }of that charge, thenGET /pay/:usernameagain. Since the api also issues a Spark invoice to a member without a charge, the invoice counts only while the same charge (sameid, amount, and end) is still open on that second read. - Inputs: The shop's
username. - Returns / side effects:
{ kind: 'invoice', amountSats, sparkInvoice };{ kind: 'none' }when no charge is open, also when it closed before the second read;{ kind: 'fallback' }when a read fails or is not the expected JSON, the invoice answer has nosparkInvoice(or names another amount), or another charge is open on the second read. Never rejects. The invoice request isfetchMemberSparkInvoicewithout a message. - Used by:
useWalletSend.
Function: fetchMemberSparkInvoice
- Purpose: Spark invoice for exactly the amount a member typed in the
/walletsend flow, to a 21.gifts member on this app's own host without an open charge, so the in-app wallet pays that member without a fee.POST /pay/:username/invoicewith{ amountSats }, pluscommentwhen the message is not empty. - Inputs: The member's
username,amountSats(whole sats), andcomment(already trimmed and cut to the receiver's limit, or''for none). - Returns / side effects: The
sparkInvoicestring, ornullwhen the answer has none (the api issues no Spark invoice for that member), names another amount, is not OK, is not the expected JSON, or the request fails. Never rejects; the caller then pays over Lightning. - Used by:
useWalletSend,fetchShopChargeInvoice.
Function: lnurlRelayTarget
- Purpose: Routing decision of the
/walletsend flow. A Lightning address (user@domain) or a bech32 LNURL whose host is not this app's own host is read through the api (POST /lnurl/pay-request,POST /lnurl/invoice). The own host is the domaingiftsLightningAddressuses for this page (a local boot counts as21.gifts); the comparison dropswww.on both sides and ignores case and a trailing dot. Own-host addresses, payment requests, Spark targets,₿DNS payment addresses, and anything else stay with the wallet'sparse. - Inputs:
textas pasted (trimmed; an optionallightning:prefix is removed),hostname(window.location.hostname). - Returns / side effects: The address or LNURL to send as
target, ornullwhen the wallet reads the text. Pure. - Used by:
useWalletSend.
Function: postLnurlPayRequest
- Purpose: Reads the pay request of a Lightning address or LNURL on another host through the api, because many LNURL servers send no CORS headers. Same-origin
POST /lnurl/pay-requestwith{ target }and the Bearer session. - Inputs:
sessionToken,target(user@domainor a bech32 LNURL). - Returns / side effects:
{ target, minSendableMsat, maxSendableMsat, commentAllowed, description, domain }(lnurlPayRequestSchema). ThrowsLnurlRelayError: 400Not a payable addressisnotPayable, 404Address not foundisnotFound, 502Address could not be reachedisunreachable; any other status or text, a network error, or a body that fails the schema isfailed. - Used by:
useWalletSend.
Function: postLnurlInvoice
- Purpose: Asks the receiver of a Lightning address or LNURL on another host for an invoice through the api. Same-origin
POST /lnurl/invoicewith{ target, amountMsat, comment? }and the Bearer session. The api resolves the target again, checks amount and comment against the pay request, and checks that the invoice amount and description hash match before it answers. - Inputs:
sessionToken,target(frompostLnurlPayRequest),amountMsat, optionalcomment(omitted when empty). - Returns / side effects:
{ pr }(lnurlInvoiceSchema), the BOLT11 invoice the wallet pays. ThrowsLnurlRelayErrorwith the reasons ofpostLnurlPayRequest, plus 400Amount out of rangeasamountand 400Comment too longascomment. - Used by:
useWalletSend.
Function: LnurlRelayError
- Purpose: Typed rejection of
postLnurlPayRequestandpostLnurlInvoice, so the send flow can choose its alert without reading English api text. - Inputs:
reason:notPayable,notFound,unreachable,amount,comment, orfailed. - Returns / side effects: Error named
LnurlRelayErrorwith a readonlyreason. The api error text is matched only together with its status; an unknown pair isfailed. - Used by:
postLnurlPayRequest,postLnurlInvoice,useWalletSend.
Function: WalletSend
- Purpose: The Send view on
/walletand over/welcome, opened with Send (and kept while a send is in flight, its Sent line shows, or a send alert is up). A region named Send Bitcoin. The input step is a full-size camera: a black layer markeddata-port-fillfills the visible page port edge to edge (absolute to the AppShell scrollport, whichglobals.cssmakes its containing block only while such a layer is in the page; bottom corners follow the frame), withQrScannerinside and the hint over the top of the picture; the Send Bitcoin label is not shown then. Two floating pills (at least 48px, wrapping onto two rows at 320px) sit over the lower part of the camera. While a picture is showing they areButton variant="overlay"; until the preview plays, when the camera is off, or when the scanner reports that the picture is not showing, they arevariant="secondary"tone="dark": Paste (wallet.sendPaste, lucideClipboardPaste) reads the clipboard (navigator.clipboard.readText; iOS shows its own Paste bubble) and takes the text exactly like a scan; a refused clipboard shows Pasting was not allowed. Use Enter manually instead. and an empty one The clipboard is empty. as a smallrole="alert"pill over the camera for four seconds, while the camera keeps running. Enter manually (wallet.sendEnterManually, lucideKeyboard) opens a bottom sheet over the camera (rounded-t-2xl bg-app-card) with a Close (X, Cancel) top-left, the focused field Payment request or address, any alert under it, and Continue; Close or the header Back returns to the camera. The first text the camera reads, or the pasted text, goes into the field throughsend.setText, and once the field holds itsend.submitInputruns once, as Continue would. While the text is read a white spinner sits in the middle of the camera area and both pills are disabled. An input alert shows in large white type a third of the way down with a filled Try again (login.retry,variant="primary"tone="dark") that clears it (send.setText('')) and starts the camera again; with the sheet open the alert sits under the field instead. The camera is mounted only while the input step is idle, shows no alert, and the sheet is closed, so a refused code is not read again at once. After a scan or paste the camera stays off until the submit moves on (busy, another step, or an alert) or the text changes, so one code is submitted once. The camera, Paste, and Enter manually never wait for the wallet. While a read waits for it (send.walletWait), the spinner in the camera area hasrole="status"Opening your wallet… (wallet.connecting) under it in the same large white type; when the wallet could not be opened, the camera area shows the alert Your wallet could not be opened. Please try again. (wallet.balanceError) with a filled Try again (login.retry,variant="primary"tone="dark") that callssend.retryWalletand keeps the text. Theunavailableinput alert is Your 21.gifts wallet is not available here, so this cannot be paid. (wallet.payUnavailable). The amount step usesAmountEntry; for a Lightning address or LNURL receiver (read by the wallet or, on another host, through the api) it adds the receiver's bounds and, when the receiver takes one, an optional Message (optional) field; when the receiver refused the message as too long, an alert says so. An amount outside the bounds, or none, shows an alert with them; without receiver bounds the alert asks for at least ₿1 with the default fiat (for a base-chain address, at least the SDK minimum once the SDK named it). The confirm step has no box: the amount large in the centre (the size of the home balance) with the default fiat small under it when a rate is loaded, except an open till charge, which shows the currency figure the shop operator typed and not this spot rate, To … small and cut short, and Fee ₿… small, with the default fiat only when the fee is above ₿0; in theAppShellFootera large full-width Send (spinner and disabled while sending) and a small Cancel text button (wallet.sendCancel). A payment to a base-chain address keeps that layout and adds, between To … and the footer: when the quote was renewed, the alert The fee offer expired, so nothing was sent. Check the new fee and press Send again.; then Fee ₿… and Total ₿… (amount plus fee) intext-basesemibold, each with the default fiat; then the group Speed with one full-width row per speed (Fast, Medium, Slow), each with its fee in ₿ and the default fiat on one line, the chosen row pressed (aria-pressed, accent border); a row whose fee the balance does not cover is disabled and says Balance too low, and every row is disabled while sending; then the muted line that this network fee is much higher than the fee of other payments. Thequotestep has the same layout as the confirm step, without a fee: the large amount with the default fiat, except an open till charge, which shows the currency figure the operator typed and stored and not that default fiat and not the spot; a missing string shows the current spot beside bitcoin, and the amount stays bitcoin only when that spot is not loaded, To …, then aLoader2androle="status"Opening your wallet… where the fee goes, or, when the wallet could not be opened, the alert Your wallet could not be opened. Please try again. with a secondary Try again (wallet.payRetry,send.retryWallet); the footer Send is disabled without a spinner and Cancel works. After sending: a large check icon, Sent ₿… large with the default fiat small under it, except a till charge, which keeps the currency figure the operator typed, To … with the recipient of the confirmed payment, and a large full-width Done in the footer. The amount step has a Close (X, Cancel) that stays on this view. Cancel on the confirm step stays on this view too; while a confirm send is in flight (sending) it is disabled and the confirm step stays, but while an expired quote is renewed it stays enabled and closes the step. The sent step closes with Done. - Inputs:
send(UseWalletSendResult),manualEntry(whether the sheet is open), andonManualEntry(opens or closes it). Reads the spot rate itself. That rate prices an amount still being typed. It does not price an open till charge. - Returns / side effects: The region. A scan or paste clears the amount draft before it submits. Reads the clipboard only when Paste is pressed.
- Used by:
WalletPanelView.
Function: WalletReceive
- Purpose: The wallet Receive view, on
/walletand over/welcome: the label Receive, the member's Open CryptoPay QR (profile.giftsQr,profileQrLogo; the profile QR, shown on every user agent), theprofile.giftsHeadinglabel, the 21.gifts address (font-mono, truncated), a labeled secondary Copy that writes the address to the clipboard and says Copied with a check mark for two seconds, counted again from each copy (a missing or refusing clipboard leaves Copy), and Set an amount (ButtonLinkto/pos). Without a username, Set a username first. links to the address row of/settings(/settings#address); signed out, only Set an amount. The view opens also while the one-time wallet setup still runs: until the address is registered (useWalletSetupdue), aLoader2androle="status"Opening your wallet… (wallet.connecting) stand where the QR, address, and Copy go, and a setup that gave up (failed) showsWalletSetupNotethere instead; Set an amount stays. - Inputs: None. Reads
accountfromuseAuthStore,useWalletSetup,useCopied, and the page host. Under Set an amount, an account withhadExternalWallet === true(missing hides it) also gets the underlined muted text button Move Bitcoin from another wallet (moveFunds.open), which callsrequestMoveFunds. - Returns / side effects: The receive block. Writes to the clipboard only on Copy. No network.
- Used by:
WalletPanelView.
Function: WalletPanelView
- Purpose: The open wallet view as the page body:
WalletReceiveorWalletSend, each in aCard surface={false}with ansr-onlyh1 Wallet (wallet.title,tabIndex={-1}) that takes the focus when the view opens, because the button that opened it is gone. The Send input step's camera fills the page port itself. - Inputs:
panel(receive|send),send(UseWalletSendResultorundefined),manualEntry, andonManualEntry. - Returns / side effects: The view's column, or
nullfor Send without a send flow. No network. - Used by:
WalletScreenView,WelcomeScreen.
Function: WalletFooterActions
- Purpose: The wallet's two large labeled buttons in the shell footer (
AppShellFooter, outside the scrollport, so they stay while the page scrolls): Receive on the left (wallet.receive, lucideArrowDownRight, pointing in) and Send on the right (wallet.sendButton, lucideArrowUpRight), equalButton size="lg"in amax-w-smtwo-column grid (data-footer-actions). They follow the page scroll: a progress from 0 (full: 56 px tall,text-base, 20 px icons, gridpt0.5rem, footer bottom padding1.25rem) to 1 (slim: 36 px,0.875remtext, 16 px icons,0.25rem,0.75rem) moves with the scroll distance itself, about 80 px down to slim and 80 px up to full, with no transition while the page moves. Within 24 px of the top they are always full. When the scroll stops for 140 ms at an in-between value they glide (320 ms,ease-glidecubic-bezier(0.32, 0.72, 0, 1)) to the nearer end; under reduced motion they go there at once. The scroll position is clamped to the page, so an iOS overscroll does not count. While the scrollport carriesSCROLL_FOLLOW_ATTR(a reveal following a moving reaction form or pay sheet,ForumBoard) its scroll events do not count either, and the buttons do not glide to an end in the middle of it (also when the wait after an earlier scroll runs out while it is set); the scroll that ends that move counts from where the buttons last followed, as one move, and starts the 140 ms wait again. Every size is acalcon--footer-collapse, which the component writes on the shell's frame body (AppShellContextbodyEl) together withdata-footer-snapduring a glide, so the footer padding and the forum home + follow; at rest (unset) every value equals the full size. Above them anaria-hidden,pointer-events-none18px fade with a light blur (-inset-x-5 bottom-full h-[18px] bg-gradient-to-t from-app-card to-transparent backdrop-blur-[1.5px], masked to fade out) lets the page end softly. Below 360px the icons hide and the side padding ispx-2, so long translations fit at 320px. Both stay enabled while the wallet opens; only a step inside a view that needs the open wallet waits for it.
With folded (the forum home while a text field in its page has the focus) the buttons fold away: one grid row around them goes from grid-rows-[1fr] to grid-rows-[0fr], the row and the fade go to opacity-0, invisible and pointer-events-none, and the shell footer's bottom padding goes to 0, so the footer has no height and nothing in it can be pressed or focused. The row clips its content only while folded or folding, so at rest nothing (a focus ring) is cut off, and it holds the buttons at its bottom (flex flex-col justify-end), so while folded their boxes stay inside the frame instead of below the window. The component marks the frame body with data-footer-fold while folded and, for 280 ms after each change, with data-footer-folding, which turns on the transitions (duration-280, ease-glide); under reduced motion that marker is not set and the fold happens at once. The page above only grows downwards, and the pull-back at the end of the page that this causes is ignored like the one of the slimming. The buttons stay mounted and keep following the scroll, so they come back at the size the scroll asks for. /wallet never passes folded.
- Inputs:
onReceive,onSend, optionalfocus(receive|send|null): when the buttons come back after a view closed, that button takes the focus, and optionalfolded(defaultfalse). The buttons carrydata-wallet-tour(receive,send), the targets ofWalletTour. - Returns / side effects: The footer registration. Listens to the shell scrollport's
scroll(passive) and removes--footer-collapse,data-footer-snap,data-footer-fold,data-footer-foldingand a pending glide or fold timer on unmount. No network. - Used by:
WalletScreenView,WelcomeScreen.
Function: useWalletPanel
- Purpose: Which wallet view (Receive or Send) shows over a page, shared by
/walletand/welcome, with its Back steps. Receive and Send open at once, also while the wallet still opens: only a step inside the view that needs the open wallet waits for it, and a view never closes because the wallet is not ready. The Send view stays while a send is in flight, its Sent line shows, or an input alert is up; leaving the Sent line returns to the page. The manual-entry sheet closes whenever the send step changes, a read starts waiting for the wallet (send.walletWait; the camera area then shows that wait), or a view opens or closes. Opening a view keeps the page's scroll position and shows the view from the top (the shell scroller); closing it restores that position. - Inputs:
{ send, openPinnedSend? }: the send flow (orundefined), and whether a?visual=send-…pin opens Send on mount (/welcomeonly; read throughvisualPin, so only in a Playwright build). - Returns / side effects:
{ shown, returnFocus, openReceive, openSend, manualEntry, setManualEntry, stepBack, close }.returnFocusnames the view that just closed (forWalletFooterActionsfocus),nullwhile a view is open.openSenddoes nothing without a send flow.stepBackcloses the sheet, then an open send step (held while a read or send is in flight), then clears the text and returns to the page; a read that waits for the wallet is dropped withsend.abandon()and the page comes back. It returnsfalsewhen no view is open.close(the wordmark and the Menu's Home) callssend.abandon(), which drops a read, prepare, or quote renewal in flight and empties the field, and returns to the page at its top; it does nothing while a confirmed send is in flight. No network. - Used by:
WalletScreenView,WelcomeScreen.
Function: visualPin
- Purpose: The one reader of the
?visual=screenshot pin. Honoured only in a Playwright build (getE2eNow()set); every deployed build getsnull. - Inputs: None. Reads
window.location.search. - Returns / side effects: The pin name, or
null(also during server rendering). No network. - Used by:
useWallet,useWalletPay,useWalletSend,useWalletPanel,useWalletPayment,useWalletSetup(walletSetupPin),useLoanRepay,WalletLoginCard,walletGateApplies,hydratesLocked(held-session),paymentHref,sendHeartTip,useHeartTip,useRecoveryFlow(recover-…), anduseRemainingBalance(prev-…).
Function: paymentTitle
- Purpose: What a payment is called in the list and on its screen: Gift on your post for a zap (no Nostr jargon on screen), else Gift (sent) or Gift on your post (received) for a gift memo, else Shop payment for a shop memo, else the paid Lightning address, else the invoice description, else On-chain deposit / On-chain withdrawal, else Received / Sent. Neither gift nor shop memo is shown as the description; a gift memo's 64 hex digits are the payment hash when the payment has none of its own. A loan repayment carries the same memo or zap as a gift, so it gets these gift titles here; Loan repayment comes only from the lookup in
WalletHistoryandWalletPaymentDetails. - Inputs: A
WalletPayment. - Returns / side effects:
{ text }(literal) or{ key }(catalog key to translate). Pure. - Used by:
WalletHistory,WalletPaymentDetails.
Function: paymentMessage
- Purpose: The message that came with a payment: the payer's note, else a non-empty zap message, else the comment sent to a Lightning address. A zap message that is a loan repayment marker (
repay:<day>:<uuid>, any case) is not a message, so the raw marker is never shown, whether or not the repayment lookup has returned. - Inputs: A
WalletPayment. - Returns / side effects: The message, or
null(also for the repayment marker). Pure. - Used by:
WalletHistory,WalletPaymentDetails.
Function: paymentLookupHash
- Purpose: Which hash the wallet hearts lookup (
useHeartContext) is asked about for one payment: its payment hash, lowercased, when the payment is no longer pending and is not a shop payment. That covers a gift memo and a loan repayment over the Lightning fallback, which has a payment hash but no memo and so no purpose. - Inputs: A
WalletPayment. - Returns / side effects: The lowercase hash, or
nullfor a pending payment, a shop payment, or a payment without a hash. Pure. - Used by:
WalletHistory,WalletPaymentDetails.
Function: paymentHref
- Purpose: The address of a payment's screen,
/wallet/payment?id=<encoded id>. Under the?visual=history-rowspin (read throughvisualPin, so only in a Playwright build) it adds&visual=history-rows, so the screen shows the same fixture payment. - Inputs:
id. - Returns / side effects: The path. Pure apart from reading the pin.
- Used by:
WalletHistory.
Function: useWalletPayment
- Purpose: Loads one payment for
/wallet/payment: once the wallet is ready it callsgetWalletPayment(id), and again wheneveruseWalletStore.syncCountchanges, so a pending payment turns completed or failed in place. A missing id, a payment the wallet does not know (the SDK's not-found answer), or a token payment ismissing; any other failed read iserrorwith aretrythat showsloadingand reads again; a later read that fails keeps a payment already shown, and a wallet that stops being ready drops it back toloading; an answer after unmount is dropped. Under the?visual=history-rowspin (Playwright builds only) it shows theWALLET_PAYMENT_FIXTURESpayment with that id throughtoFixturePayment(ormissing), under?visual=heart-paymentand?visual=heart-payment-pendingthe heart fixture when the id matches (otherwisemissing), under?visual=repayment-paymentthe received or the sent repayment fixture whose id matches (otherwisemissing), under?visual=received-from-member,?visual=received-member-unknown,?visual=sent-to-member, and?visual=sent-member-unknownthe respective member payment fixture when the id matches (otherwisemissing), under?visual=history-errora failed read (error, whoseretrydoes nothing), and reads nothing. - Inputs:
idfrom the address, ornull. - Returns / side effects:
{ status: 'loading' },{ status: 'ready', payment },{ status: 'missing' }, or{ status: 'error', retry }. - Used by:
WalletPaymentDetails.
Function: WalletPaymentDetails
- Purpose: The
/wallet/payment?id=…screen (useSearchParams, so the page wraps it inSuspense).Card surface={false}with ansr-onlyh1 Payment. Ready: a centred head with the direction icon in a roundbg-app-card-mutedbadge, the title (paymentTitle: Gift on your post for a zap, Gift when a gift memo was sent, Gift on your post when one was received, Shop payment for a shop memo; neither memo is shown as the description, and a gift memo's 64 hex digits are the payment hash when the payment has none of its own). A gift hash on a payment that is not still pending, resolved byuseHeartContext, replaces that direction icon and gift title with the filled accent heart and, after the status, a bordered link to/messages/<messageId>containing the author when present, up to three lines of post text when present, and a chevron; deleted posts get no deleted label. A payment that is still pending keeps the direction icon and the gift title and is not looked up. Every other payment with a payment hash that is not a shop payment is looked up (paymentLookupHash). A hash resolved as a loan repayment, for the member as giver or as borrower, replaces the direction icon with the lucideHandCoinsicon in the accent colour, keeps a title but makes it Loan repayment (wallet.payment.repayment), shows the same post card for the credit note (link to/messages/<messageId>, author and text; a deleted note gets no deleted label, like a deleted heart post), drops the message block and the Description row, adds a Repayment day row (wallet.payment.repaymentDay:wallet.payment.repaymentDayOf{day} of {days} with the one-based day andtermDays, or only the day whentermDaysis null), and after the summary list a Repayment list link (forum.creditList, the wording the note's own repayment list link uses) to/messages/<messageId>/repayment-list. Therepay:marker is never shown, also while the lookup is out. The link's accessible name is the author and the text, or Post (shops.viewPost) when both are empty, not the note id. The summary list keeps To when the payment names a recipient, the same member link as a sent gift. While its lookup is pending the direction icon and the gift title stay and the post card is absent; a miss or failure keeps today's icon and title. The amount is large (text-3xlsemibold), signed+/−(failed: struck through and muted). A shop payment shows the currency figure stored on that charge under it, fromuseShopChargeFigure(committedFiatFigureof the receipt, with the visitor's fiat as preferred). While that read is pending, on a 404 or a failed read, and for any payment that is not a shop charge, the amount shows the current spot once a rate is loaded. This screen readsuseSpotRate. A missing stored string shows that spot, and the amount stays bitcoin only while the spot is not loaded or a shop receipt is still out. Then a status pill (Completed success, Pending notice, Failed danger) and, for a pending send, Still on its way. The amount stays reserved until it arrives or comes back., for a failed send Nothing left your wallet.; then the message block (paymentMessage) when there is one; then a bordered summary list: Date (long date and short time in the UI language), Type (Instant payment for Lightning, Wallet transfer for Spark, On-chain deposit, On-chain withdrawal, Payment), To (plain text for a Lightning address and a link to/members/<accountId>whenmemberAccountIdis set; the sent-gift fixture links to/members/acc_e2e), Description (only when the title is not already the description), Amount, Fee (Free at ₿0; hidden for a fee-less receive and for a failed payment), Total (sends with a fee), and Arrived on-chain (a deposit with a claim fee); every ₿ figure is bitcoin plus one fiat figure. The charge amount uses the stored shop figure and does not add the visitor's spot beside it. A fee uses the current spot on the fee sats. A shop total keeps the stored charge figure and adds the spot of the fee sats only, in that same currency; a fee in another currency stays beside its own bitcoin and is not a spot of the sum. Any other amount uses the current spot, and omits it only when no rate is loaded. While a shop receipt is still out, the charge amount and the total stay bitcoin. A fee of ₿0 stays Free. Then a Details button (wallet.payment.technical) with aria-expanded, closed until pressed, not an always-visible h2 list. Pressing it opens the technical list of the same values, each shortened to its first 10 and last 6 characters with an icon-only Copy (IconButtonghost, accessible name Copy {label}, a check mark and a polite Copied for two seconds; a refused clipboard keeps the icon): Transaction and Output, Payment request (the invoice), Payment hash, Proof of payment (preimage), and Payment ID. The zapper's key and the zapped note are not shown (docs/ui.md: no keys, npub, or zap jargon on screen). An on-chain payment also has View on mempool.space, which openshttps://mempool.space/tx/<txid>only afterExternalLinkWarningis confirmed (openInSystemBrowser). Missing:role="alert"This payment could not be found. A read that failed otherwise:role="alert"This payment could not be loaded. Please try again. (danger) and Try again, which reads it again. A shop payment shows the stored figure once the receipt returns. It does not calluseSpotRateStateand does not wait on a rate. A missing stored string shows the current spot once it has loaded, and the amount stays bitcoin until then. A payment that is not a shop charge shows that same spot. While the wallet is still connecting, could not be opened, or its one-time setup gave up,WalletBalanceis shown with no balance sats. A session whose wallet is not open in this tab seesWalletLoginCardfromOnboardingGatein place of this screen; thebalance-locked-prf-unsupportedpin adds the no-PRF alert above Log in. With no wallet here (useWalletdisabled) it says the payment could not be found.
For a received payment, From (wallet.payment.from) shows the counterparty's giftsLightningAddress when both exist, linked to /members/<counterparty.accountId>. To uses info.lnAddress first; otherwise, for a sent payment, it shows the counterparty's address linked to /members/<counterparty.accountId>. Payment request is omitted when the counterparty address is known and isSparkPaymentRequest(info.invoice) is true. While usePaymentCounterparty has no name (not looked up, not named yet, or never named), neither From nor a looked-up To is rendered, and no Spark value is put in their place.
- Inputs: None (the
idquery parameter,useWalletPayment,useHeartContext,usePaymentCounterparty,useShopChargeFigure,useWallet, number format, the UI language). The viewer's currency is not applied to the charge figure. - Returns / side effects: The screen. Writes to the clipboard only on Copy; leaves the site only after the warning.
- Used by:
WalletPaymentPage.
Function: WalletPaymentPage
- Purpose: Next.js page for
/wallet/payment. - Inputs: None.
- Returns / side effects: Fill
AppShellwithWalletChromeLefttop-left (the one arrow: the previous in-app view, the list when opened from it, or/welcomewhen this tab has none),SignedInChrometop-right, andOnboardingGate screen="wallet"aroundSuspenseandWalletPaymentDetails. - Used by: Screen
/wallet/payment.
Function: WalletSync
- Purpose: Root-mounted effect that keeps the wallet connection synchronized with the tab-memory phrase, runs due wallet setup in the background, and sends the wallet data report while signed in. It registers the phrase listener first so setup can reuse that connection.
- Inputs: None. Reads
useWalletStore. - Returns / side effects:
null. Subscribes throughlistenForWalletPhraseandlistenForWalletSetupwhile mounted, then unsubscribes both on cleanup. After every successful wallet read (syncCountchanges whileready: the login, each SDK sync, and the read after a payment) it callsreportWallet. EveryWALLET_REPORT_INTERVAL_MS(five minutes) while the wallet isreadyit reads the synchronized balance withrefreshWallet({ ensureSynced: true, ignoreFailure: true }), which reports again. Unmounting stops the timer and the subscription. - Used by:
RootLayout.
Function: reportWallet
- Purpose: While the member is signed in (login opens the wallet), sends the wallet data report to
POST /me/wallet/report: the balance, the time it was read, and every payment the api has not acknowledged yet, with its current status. The first report in a tab sends the full history; a status change (pending to completed) is sent again. - Inputs: None. Reads the session from
useAuthStoreand the status, balance, and identity key fromuseWalletStore. - Returns / side effects: A promise that never rejects. Without a session or a
readywallet nothing is sent. It lists every payment withlistWalletReportPaymentsin pages ofWALLET_REPORT_PAGE_SIZE(200) and posts them in requests of at most 200 withpostWalletReport. The acknowledged ids and their statuses live in tab memory only (no storage of any kind), keyed to the wallet identity: another wallet starts over, and a new tab sends the history again (the api treats repeats as the same payment). A payment that moved onto the next page while the pages were read is kept once. A failed list or post, or one that has not answered afterWALLET_REPORT_STEP_TIMEOUT_MS(30 s), stops the report; the next one sends the rest. A report with no unacknowledged payment and the same balance as the last one waitsWALLET_REPORT_QUIET_MS(60 s) after it. A call while a report runs adds one report after it. After the first listing in a tab, a received payment that is newly completed is recorded once aspayment_received_seenwith its id and amount. The body holds only the fields ofWalletReportPayment: never the recovery phrase, a private key, PRF output, or a preimage. - Used by:
WalletSync.
Function: walletReportSettled
- Purpose: Wait for the running wallet report and any report requested while it runs, without requesting another report.
- Inputs: None.
- Returns: A promise that resolves when the report settles, or immediately when none is running.
- Used by:
usePaymentCounterparty.
Function: InteractionLog
- Purpose: Root-mounted effect for the first-party interaction log. Renders nothing.
- Inputs: None. Reads
usePathnameand whetheruseAuthStoreholds a session. - Returns / side effects:
null. RunsstartInteractionLogwhile mounted. While signed in it recordsscreen_viewfor every path (query and fragment are never sent), andprofile_openedwith the account id on/members/:accountId. Signed out it records nothing. - Used by:
RootLayout.
Function: logInteraction
- Purpose: Queues one interaction of the signed-in member for
POST /me/events:screen_view,post_created,reply_created,gift_sent,heart_sent,payment_sent,payment_failed,wallet_open_failed,payment_received_seen,pos_charge_created,pos_charge_paid_seen,search,shop_opened,profile_opened,login,logout,signup_completed, or the wallet tour and move-funds eventswallet_tour_shown(steps),wallet_tour_step(step,target),wallet_tour_done(outcome,step),wallet_move_opened(source),wallet_move_step(step),wallet_move_copied(step),wallet_move_closed(step), andwallet_move_done(amountSats), orrecovery_done(no props), recorded once after the sign-in that ends a social recovery. - Inputs: The event name, optional flat
props(ids, amounts, counts, flags; the only free text is a search term;wallet_open_failedcarriesreason,stage,errorName,errorCode,causeKind,elapsedMs,online, andvisibility, all short codes, numbers, or flags), and optionally the session the recorded action ran under. Callers that record after an await pass it (postMessage,postMessageVideo,createPosCharge,searchMentionAccountstheirsessionToken;payFromWallet'ssend,useWalletPayandreportWalletthe session at the start of the send or report;reportPaymentFailurethe session its caller passes); when it is no longer the current session, the event is dropped, so it is never queued for another member. - Returns / side effects: None. Without a session nothing is kept, so anonymous visits are never recorded. Events still queued under another session are dropped before the new one is queued. The event carries the time (ISO 8601), the current path without query or fragment (the access key of
/view/:viewKeyand/view-key/:viewKeyis replaced by[key]), and the cleaned props: at most 12, keys that are short identifiers and do not name a secret (mnemonic,phrase,seed,share,slip39,prf,preimage,secret,token,password,privkey,private,session), values that are strings of at most 200 characters, finite numbers, booleans, ornull, and never a string that looks like a recovery phrase (12 or more words), 64 or more hex digits, or a bearer token. At most 500 events wait; the oldest are dropped first. Reaching 50 queued events starts a flush (the byte budget may split it into several requests). The path is cut at 512 characters. - Used by:
InteractionLog,reportWallet,payFromWallet,connectWallet,reportPaymentFailure,useWalletPay,usePasskeyLogin,postMessage,postMessageVideo,createPosCharge,PosTill,searchMentionAccounts,PlacesMapScreen,sendHeartTip,WalletTour,MoveFundsSheet, and the recovery flow on/recover(recovery_done).
Function: flushInteractions
- Purpose: Sends the queued interactions with
POST /me/events{ events }in batches of at mostINTERACTION_BATCH_SIZE(50) events and 60 000 UTF-8 bytes of request body, each request withkeepalive, so a request in flight when the page closes is still delivered (the browser caps a keepalive body at 64 KiB). - Inputs: None. Reads the session from
useAuthStore. - Returns / side effects: A promise that never rejects. Events go out only with the session they were recorded under: without a session, or with another one, the queue is dropped, and a flush stops after the batch in flight when another member signs in. A failed batch goes back to the front of the queue (still at most 500 events) and the next flush tries again; a failed batch of a member who is no longer signed in is dropped. A request that has not answered after
INTERACTION_REQUEST_TIMEOUT_MS(10 s) is aborted and counts as failed. A batch the api refused for good (a 4xx status other than 429) is dropped instead of sent again. Names an api that does not know them yet answers with 400 for the whole batch go out in batches of their own, one group per change that added them:payment_failedandwallet_open_failedtogether, thewallet_tour_*/wallet_move_*events together, andrecovery_doneas the grouprecovery(whichever group the oldest queued event belongs to goes first; the rest stay queued in order), so such a refusal never drops an event of another group or any other event. One flush per session runs at a time; a second call while it runs returns at once, and a flush of an earlier session still waiting on its request does not hold a new session's queue back. A flush whose member signed out meanwhile sends no further batch and drops what is left. - Used by:
logInteraction(full batch) andstartInteractionLog.
Function: logLogout
- Purpose: Records
logoutand sends it with the session that is ending, before the caller clears that session. - Inputs: None. Reads the session from
useAuthStore. - Returns / side effects: A promise that never rejects. With a session, it first sends
LOGOUT_EVENTonwindowwhile that session is still the current one, so a listener can still record its own event under it (the move-funds sheet recordswallet_move_closed); those events go out with the queue below. BuildslogoutlikelogInteractionand sends it at once withPOST /me/eventsin a request of its own, so a flush already running does not hold it back. It also sends the queued events, after a flush already running, sending a failed batch again everyLOGOUT_RETRY_MS, and after the logout event is accepted it sends any event queued meanwhile; it resolves when sending finishes; once the session has ended, when the requests already started and any retry wait have settled. A failed request is sent again everyLOGOUT_RETRY_MS(500 ms) while the session is still the current one; when the api refuses it for good (a 4xx status other than 429, for example a session it no longer accepts),logLogoutresolves at once without waiting for the queue.LogoutButtonbounds the wait at 5 s and then clears the session: queued events not sent by then are dropped, and a request still in flight keeps running (it is kept alive) until it is answered or aborted afterINTERACTION_REQUEST_TIMEOUT_MS. Without a session nothing is recorded or sent. - Used by:
LogoutButton.
Function: startInteractionLog
- Purpose: Starts sending the interaction queue while the app is open.
- Inputs: None.
- Returns / side effects: Flushes every
INTERACTION_FLUSH_MS(10 s), and when the document becomes hidden or onpagehide. Returns the function that stops the timer and removes both listeners. - Used by:
InteractionLog.
Function: WalletPhraseScreen
- Purpose:
/wallet/phrasebody. Recovery phrase or recovery error, with no receive QR. - Inputs: None.
- Returns / side effects: Renders
WalletScreenViewsurface="phrase"withuseWalletPhrase(). - Used by:
WalletPhrasePage.
Function: WalletPhrasePage
- Purpose: Next.js page for
/wallet/phrase. - Inputs: None.
- Returns / side effects: AppShell + OnboardingGate +
WalletPhraseScreen. - Used by: Route
/wallet/phrase.
Function: WalletPage
- Purpose: Next.js page for
/wallet. - Inputs: None.
- Returns / side effects: AppShell + OnboardingGate + WalletScreen: the wallet home with Receive and Send (Receive on the left). Recovery-phrase access is on
/security. - Used by: Route
/wallet.
Function: startPasskeyRegistration
- Purpose: POST
/auth/passkey/register/beginand parse options. - Inputs: Optional
viewKeystring and optionalnamestring. A non-emptyviewKeyPOSTs JSON{ viewKey }withContent-Type: application/jsonand ignoresname. Otherwise a non-emptynamePOSTs JSON{ name }withContent-Type: application/json. Otherwise POSTs with no body and no Content-Type. - Returns / side effects:
{ challengeId, options }. On!ok, throws the api{ error }string when present, otherwise a status fallback. SendsX-App-Build(getBuildId). 503codelogins_closedthrowsLoginsClosedError; 403codeapp_outdatedthrowsAppOutdatedError. - Used by:
usePasskeyLogin.submitNamefor a new account, andusePasskeyLogin.registeronly with a view key.
Function: usePasskeyLogin
- Purpose: Client hook for passkey login. The api's authentication options already carry
extensions.prf.eval.first, so the login prompt can return PRF output; the hook adds no extension to the request, and onlyauthenticateHeldlimitsallowCredentials(see Returns). Login PRF output is used only when that request'sprf.eval.firstequals the app's ownprfEvalFirstSalt; a missing, unreadable, or different salt counts as absent.loginauthenticates with an existing passkey. When authenticate returnsNotAllowedErrorandisInAppBrowser()is false, status becomeschoiceand registration is not started. When authenticate returnsNotAllowedErrorwhileisInAppBrowser()is true, status becomesunsupportedand register is not started. Fromchoice,authenticatenever falls through to register;register()(no view key) sets statusnameand starts neitherstartPasskeyRegistrationnorcredentials.create.submitNamenormalizes and, when valid, callsstartPasskeyRegistration(undefined, normalized)then the existing create ceremony.register(viewKey)starts the claim immediately and does not showname. User cancel (NotAllowedErrororAbortError) after a named create returns toname, notchoice. After a choice was offered, user cancel (NotAllowedErrororAbortError) on those ceremonies returns tochoice; directauthenticate/register(viewKey)fromViewProfileClaimnever sets that flag, so cancel returns toidle. Statusunknownis authenticate finishUnknown credential: the hook callssignalUnknownCredentialbest-effort with the ceremonyrpIdandcredential.idbefore showing it, and a later user-cancel returns tounknownwhile that flag is set. On iOS/iPadOS WebKit (including iPadOS desktop-site: Macintosh UA, MacIntel, maxTouchPoints > 1),credentials.get/credentials.createomit AbortSignal.cancelaborts an in-flight WebAuthn prompt and clears the choice flag.register(viewKey?)forwards an optional view key for public profile claim;retryafterregister(viewKey)resends the same key.loginnever sends a view key. FinishWrongAccountErrorclears the session (a held-backlockedSessionstays, so its login card stays and showslogin.wrongAccount), setswrongAccount, statuserrorwith that message, and does not fall through to discoverable registration.registerrequires WebAuthn PRF on create, confirmed by one get() under the registration options'rp.id(obtainPrfFirst); missing PRF, a missingrp.id, or a get() that differs from create() aborts withwallet.prfUnsupportedand does not finish. A finished login keeps its options'rpId(rememberCeremonyRpId) for a later phrase prompt in this tab. Registration and login now hand the PRF output they already hold torememberPhraseFromPrfjust before the session is stored withsetAuth(no extra prompt; what is sent to the api is unchanged); with the wallet configured, a login reportsclient.passkey.login.prfwithprfPresentas a boolean only; without PRF output nothing happens.login/authenticatecallclearSessionPhrase. On iPhone, iPad, or iPod below iOS 18, a named create still does not finish the account.NotAllowedErrororAbortErrorfrom create or from the extra-key read reportsclient.passkey.register.ceremonywithname,prfPresent: false, the beginchallengeId,accountIdwhenuser.iddecodes as a UUID, and messageiOS <installed> below 18 at createorat prf, then the browser text when it fits the diagnostic allowlist. A missing extra key reportsclient.passkey.register.prfwithprfPresent: false, those same ids, and messageiOS <installed> below 18 at prf.absent. Both throwlogin.iosVersioninstead of a silent cancel orwallet.prfUnsupported. On Android below 9, a named create does not finish the account.NotAllowedErrororAbortErrorfrom create or from the extra-key read reportsclient.passkey.register.ceremonywithname,prfPresent: false, the beginchallengeId,accountIdwhenuser.iddecodes as a UUID, and messageAndroid <installed> below 9 at createorat prf, then the browser text when it fits the diagnostic allowlist. A missing extra key reportsclient.passkey.register.prfwithprfPresent: false, those same ids, and messageAndroid <installed> below 9 at prf.absent. Both throwlogin.androidVersioninstead of a silent cancel orwallet.prfUnsupported. Every failed login postsclient.passkey.login.failbefore the card changes, even when no account id exists: the browsername, the allowlistedmessagewhen that text fits, and the beginchallengeIdwhen it is 64 hex. That row is written whencredentials.getthrows, when the assertion is missing, and when an in-app browser stops the ceremony first (stageloginorauthenticate, messagein-app browser). A dismissed register that is not an old-iOS or old-Android stop postsclient.passkey.register.failwith those fields, andaccountIdonly whenuser.iddecodes as a UUID. A failed login row and a dismissed register that is not an old-iOS or old-Android stop prefix the allowlisted message withiOS <installed>orAndroid <installed>when the user agent parses (iOS preferred), including versions new enough to pass the gate. Desktop and a user agent with no version token stay unprefixed. A cancelled named create stays onname; claim and paths before the name staychoice,idle, orunsupported. Begin and finish failures keep their own rows and do not need an account id. - Inputs: None (reads
useAuthStore; callsisInAppBrowseron authenticateNotAllowedError,iosPasskeyBlockandandroidPasskeyBlockon register, andiosInstalledVersionandandroidInstalledVersionwhen a failed attempt is reported). - Returns / side effects:
{ status, login, register, submitName, authenticate, authenticateHeld, retry, cancel, error, recoveryPending, walletPasskeyMissed, nameError }.authenticateHeldlimits the prompt tolockedCredentialId(allowCredentials) until that prompt ended without an answer for this held-back session (noteLockedPasskeyMissed), which setswalletPasskeyMisseduntil the next run starts, also after the hook mounts again before then (lockedPasskeyNotice); it then offers every passkey, as it does for an account without a wallet passkey. The result hasstatuswithstatusinidle | starting | error | unsupported | choice | unknown | name | closed | outdated.erroris the lastError.messagewhenstatus === 'error', elsenull.nameErrorisinvalid,taken, ornullwhilestatus === 'name', elsenull. After a named create,retryreturns to the name form and does not start create again.retryafterregister(viewKey)sends the same key again.retryafterauthenticaterepeats authenticate. The single login button repeats login. Calls WebAuthn and the api. Unmount still aborts the controller and clears the choice flag. A successful login or registration startsrememberPhraseFromPrfbeforesetAuth, so listeners reacting to the new session wait for that derivation, then starts the sparse owner-account refresh aftersetAuth; that refresh is tied to the stored session token, socancelor unmount does not discard it. For a new registration, the same sign-up passkey therefore supplies the phrase that background wallet setup uses after the username is saved; there is no extra prompt. Times the login passkey prompt (the assertion that also returns the PRF bytes) as the wallet spanwallet.passkeywithprompt: login(traceWallet).LoginsClosedErrorfrom any begin or finish setsclosedandAppOutdatedErrorsetsoutdated, both witherrornull; neither retries on its own, clears a held-back session, or opens another card.RecoveryPendingErrorfrom authenticate finish (409recovery_pending: the passkey belongs to a social recovery that is not finished yet) setserrorwithrecoveryPendingtrue and never callssignalUnknownCredential, because that passkey may become the account's only one;recoveryPendingis a typed marker, true only whilestatus === 'error', and every new run orcancelclears it. - Interaction log: After the session is stored, a completed registration is recorded as
signup_completedand a completed login aslogin. - Used by:
OnboardingGate,LoginCard,LogoutButton, andViewProfileClaim.
Function: fetchComposeTarget
- Purpose: GET
/messages/compose-targetso a basis account can invoice 1 sat to 21.gifts (the platform profile note) before posting or replying, and learn whether its next top-level post is its free first post. - Inputs: session token.
- Returns / side effects:
{ messageId, sats, firstPostFree }of the payable platform profile note, or throws collapsed copy.firstPostFreeis true only when the api sendstrue; a missing or non-boolean field is false, so the fee flow stays the default. - Used by:
ForumLoader(on mount for the first-post hint, and on every post below verified),PublicMessageThread,MemberProfileScreen.
The api sets firstPostFree while the member has no live or hidden top-level note of their own other than their About me note. Replies and conversation messages do not count, and it never comes back once a first post exists.
Function: PostFeeRequiredError
- Purpose: Typed error for the api's HTTP 403 on
POST /forum/messages: a member below verified sent a post or reply that needs a Bitcoin payment first, including a free first post the api no longer allows (for example when a second first post won the race). - Inputs:
message— the visitor copy (postMessage: the api error string, otherwiseA reply needs a Bitcoin payment;postMessageVideo:Could not post your message). - Returns / side effects: Error instance named
PostFeeRequiredErrorwith that message, so screens that show the message read the same as before. - Used by:
postMessage,postMessageVideo,ForumLoader(falls back from the free first post to the 1-sat posting fee).
The class exists so the composer can tell a refused free first post from any other failure. Every other error from a free create keeps its normal handling (requirements overlay, wallet step, rate limit, or the request error).
Function: getRepayment
- Purpose: GET
/messages/:id/repaymentwith no session. The public ledger of who gave what and each bitcoin repayment. - Inputs: Credit note id.
- Returns / side effects: The ledger, or null when the response is not ok or the body does not match. The ledger carries
closedAt; each line carriespaidSatsandpaidAmount, so a partially paid line remains due/scheduled whiledueSatsis its remainder. Adueline carrieswaitingwhen its giver cannot receive yet, andwaitingSharescounts those lines; new compatibility fields stay optional while an older api omits them. - Used by:
CreditLedger,LoanRepayScreen.
Function: CreditLedger
- Purpose: Show the givers and the repayment plan under a posted credit. Nothing renders until the ledger loads, and a failed read stays blank. Under Paid back, a string
startsOnfrom the api adds First repayment day: <date>. with the localized UTC date; a null or missingstartsOn(unfunded credit, or an api without the field) shows no such line.list="summary"(default) shows givers, the explanation, the chart, and a Repayment list link to/messages/<id>/repayment-list.list="page"shows that same heading block and omits the link. It lists each day when there are at most 7 day groups, whenfundedAtis null, or when any day has nodueOn. When the credit is fully given, every day is dated, and there are more than 7 day groups, the page shows still owed (only shares that are not paid), the first and last dates, how many days are paid, the next unpaid day (omitted once every day is paid), one row per recipient with that person's usual daily amount, day count, and sum, a together row, and one block per calendar month. Each month states how many days repeat the most common shown daily amount and split, and lists only the days that differ; a waiting share makes its day differ from the same split without one, and the usual day is a day without a waiting share whenever the month has one, so waiting days are always listed with their waiting line; a waiting share inside the usual day itself (every day of the month has one) adds Waiting for {name} to set up their wallet under the usual split. A month names one status only when every share in that month has that status, a waiting share counting as Waiting; otherwise it names only the day count. A footnote lists those different days, and names one usual daily total only when every day that is not listed shares that total. A fiat plan, a share, still owed, and the chart total stay in the ask currency and do not add bitcoin. Money already given keeps that currency and bitcoin. A bitcoin amount on that overview shows the current spot beside bitcoin, and stays bitcoin only when that spot is not loaded. The chart scale stays one unit. There is no extra control. - Inputs: Credit note id. Optional
list:'summary'|'page'(default'summary'). OptionalonLedger, called with every loaded ledger (the first read and each refresh). - Returns / side effects: The Given and Paid back lists, or null. Before rendering, each repayment row uses
dueSatswhen present; when an older api omits it, the validated compatibility remainder issats - paidSats(with a missingpaidSatstreated as zero). A fiat row likewise subtractspaidAmountfromamountin integer cents, so a partial row, chart bar, split, and still-owed total all show only its remainder. Onlist="page", day-group rows render for a short plan, and on a long plan only for the next unpaid day and for days that differ from that month's usual day.list="summary"never renders those rows. The chart uses day numbers (dayIndex + 1) untilfundedAtis set or a day has nodueOn; once the credit is fully given it uses the UTC dates. A fiat chart sums only amounts in the ask currency. Fetches when the id changes. Until that read finishes, a previous note's ledger is not shown. While any row isdue, refreshes every 4 seconds. A failed or null refresh leaves the list for the same note. A response after an id change or unmount is ignored. Names stay on one line. On a narrow screen the status sits under the amount; on a wide screen it sits beside it. A line the api markswaiting(its giver cannot receive yet; without that flag from an older api, a due line whose giver hascanReceive: false) shows the muted status Waiting instead of Due, and a muted Waiting for {name} to set up their wallet under the name. The list scrolls with the page. The summary link is shown once the ledger has loaded, even when there are no rows. - Used by:
ForumGoalBar(list="summary", withonLedgerfeedingLoanBlock).RepaymentListPage(list="page").
Function: RepaymentListPage
- Purpose: Next.js page for
/messages/[id]/repayment-list— the repayment list for one credit note: who gave, the chart, and the plan. A short plan, a plan that is not fully given, and any plan with a missing date list each day. A fully given plan with more than 7 dated days is the month overview fromCreditLedger(list="page"). The pictured 2-day screen still lists each day. Those rows render only here. The note, the forum, and a profile show a Repayment list link instead. Chrome isPublicMessageChrome. NoOnboardingGate. No second back control. The note id is not validated as a UUID here. - Inputs: Dynamic route params (
id). LoadsGET /messages/:id/repaymentthroughgetRepayment(viaCreditLedger). No session is required to view. Chrome follows the hydrated session. - Returns / side effects:
CreditLedgerwithlist="page"insidePublicMessageChrome. NogenerateMetadata. - Used by: Route
/messages/[id]/repayment-list. The Repayment list link on a collapsedForumGoalBarand onCreditLedgersummary.
Function: proxyMessagesRepaymentGet
- Purpose: Same-origin proxy for
GET /messages/:id/repayment. - Inputs: App Router
Requestand the message id. - Returns / side effects: Forwards to the api. No session is required.
- Used by:
src/app/messages/[id]/repayment/route.ts.
Function: proxyMessagesRepaymentPost
- Purpose: Same-origin proxy for
POST /messages/:id/repayment. - Inputs: App Router
Requestand the message id. The request may have no body for the next payable share or JSON{ amount }for a free-amount repayment. - Returns / side effects: Forwards the optional request body unchanged to the api.
- Used by:
src/app/messages/[id]/repayment/route.ts.
Function: postMessageInvoice
- Purpose: POST
/messages/:id/invoicewith{ sats },{ sats, text }when the visitor attached a reply comment,heart: truewhen the optional heart flag is set (a heart of the requestedsatswith no comment), andamountUsd,amountChf,amountEur,amountPhpwhen a preview rate is on screen. Emptytextis omitted. A missing preview omits those four fields. Existing callers omit the heart flag. - Inputs: session token, message id, sats, optional text, optional shown
amountUsd,amountChf,amountEur, andamountPhp(each a two-decimal string or null), optionalheart(trueonly). The amounts are read when the request is sent, not when an earlier requirements step started. - Returns / side effects:
{ pr, amountSats, sparkInvoice? }or throws collapsed copy.sparkInvoiceis the request the member's in-app wallet pays first (a string ornull;pris paid when the wallet refuses it, except for a heart, which is paid by the Spark invoice only); a body without it still parses, so the app works against an api that does not send it. 409missing_requirementsthrowsMissingRequirementsError; 409credit_closedthrowsCreditClosedError. 404 throwsNoteDeletedErrorinstead of the collapsed payment copy. A 400 withcodewallet_requiredthrowsWalletRequiredError(the member's own wallet is not set up yet) and one withcannot_receivethrowsCannotReceiveError(the receiving wallet cannot take this payment) (viathrowIfWalletAnswer), recognised by the body'scodeonly. A 403 body is read so aSUNDAY_RESTheart is reported assunday. A 503 body{ error: 'HEART_UNAVAILABLE' }throws anErrorwhose message isHEART_UNAVAILABLE, so a heart is reported asheart_unavailable; any other 503 keeps the collapsed copy. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,sendHeartTip.
Function: sendHeartTip
- Purpose: One-click heart:
postMessageInvoiceof the click'sheartSatswithheart: true, thenpayFromWalletonsparkInvoiceonly. WhenrateDayis set, the four amounts are the spot of that amount. WhenrateDayis missing, those amounts stay omitted. A heart is exactlyheartSatsand fee-free: without a non-emptysparkInvoice, or when theconfirmresult is notamountSatsheartSatswithfeeSats0, nothing is sent and the reason isheart_unavailable; the Lightningpris never paid. Otherwisesend()runs at once. No amount dialog and no gift sheet. A wallet snapshot that is ready with less thanheartSatsstops withno_balancebefore any request. In a Playwright build only (visualPin),?visual=heart-paidreturnspaid,?visual=heart-needs-balancereturnsno_balance, and?visual=heart-cannot-receivereturnsauthor_cannot_receive, both without invoicing. A send that endsfailedwithsentLate(the app stopped waiting afterWALLET_SEND_TIMEOUT_MS) keeps that note's Spark invoice in tab memory. WhensentLateresolvestruethe earlier heart counts as sent and the optionalonPaid(messageId)runs once; once that late heart is fully booked, its note is forgotten, so the next tap is a new heart with a new invoice and payment. WhensentLateresolvesfalsethe note is cleared. Until the late outcome is known, the next heart on that note first reads the newest 50 wallet payments (listWalletPayments) and sends nothing while that payment ispending, not listed yet (for up toHEART_TIP_UNSETTLED_MS, ten minutes), or the list cannot be read. A retap while that outcome is still in flight keeps thetimeout_pendingorpaidsettlement behavior; afailedpayment, or one still missing after that window, clears the note and the heart is sent as usual. - Inputs:
HeartTipInput(message id, session or null, readOnly, local Sunday, wallet snapshot, setup/unlock flags, optionalrateDay, andheartSats), and an optionalonPaid(messageId)for a send that pays after the app stopped waiting. - Returns / side effects:
{ kind: 'noop' }without a session or on a read-only board;{ kind: 'paid' }after a successful send; otherwise{ kind: 'failed', reason }with aHeartTipFailurecode:sunday(local Sunday or the api'sSUNDAY_REST),no_balance(the wallet snapshot is ready belowheartSats, before any request),insufficient_balance(prepare or send answersinsufficient, or the live wallet is ready with a balance belowheartSats, after the tap already showed the +1),wallet_setup_due(setup still due, or the api'swallet_required),author_cannot_receive,credit_closed(the invoice target is a loan that no longer collects),rate_limited,heart_unavailable(notheartSatsfee-free, no Spark invoice, or a 503HEART_UNAVAILABLE),request_failed(any other invoice error),payment_failed(prepare, unlock, or send failed),timeout_pending(an earlier heart on that note timed out and is not settled), andin_flight(another heart on that note is still in progress in this tab, also from a board mounted again; no new invoice). - Error report: Every
failedoutcome exceptno_balanceis sent to error reporting withcaptureMessage('Heart not sent')at levelerror, the tagheart_reasonset to the code, andmessageIdas the only extra. No amount, name, invoice, or token is attached, and the event passes the samebeforeSendscrubber as every other report. Nothing is sent while error reporting is off. - Interaction log: A heart the SDK reports as sent is recorded as
heart_sentwith the message id andamountSatsheartSats, under the session of the click, next to thepayment_sentthatpayFromWalletrecords; a send the app stopped waiting for is recorded once itssentLateresolvestrue. Every prepare or send of a heart that does not pay is passed toreportPaymentFailurewith the flowheartandamountSatsheartSats, so it is recorded aspayment_failedbut not sent to error reporting a second time: an unlock that is not possible or not completed, a failed prepare or send, a balance too low (also a live balance belowheartSats), and a prepared heart other thanheartSatsat ₿0 (amount_mismatch). An unlock followed by a paid heart records nothing. - Used by:
useHeartTip.
Function: heartFailureView
- Purpose: The view of one heart after a send that did not pay.
pressedstays while the remaining extra is above 0 or the +1 still shows. A refusal because the author cannot receive (author_cannot_receive) setscannotReceive;credit_closedsetscreditClosed. Other outcomes preserve either flag so a concurrent failure cannot clear its localized line. Only the next tap clears it. - Inputs: The heart's current view (or
undefined), this session's extra for the note after the rollback, and the send's outcome. - Returns / side effects: The heart's next view. No storage write and no payment.
- Used by:
useHeartTip.
Function: endHeartPlusOne
- Purpose: Drops the +1 after the 700 ms press window. The heart stays filled only while this session's extra is greater than 0. A view map with no row for the id is returned unchanged.
- Inputs: The current per-id heart view map, and the message id whose +1 ends.
- Returns / side effects: The next view map. No storage write and no payment.
- Used by:
useHeartTip.
Function: useHeartTip
- Purpose: Per-
messageIdheart machine for the three callers. A tap passes the current spot asrateDayand the account's storedheartSats(default 1). A tap on a signed-in, writable board vibrates and shows the filled heart with +1 at once, before any request, forHEART_TIP_PLUS_ONE_MS(700 ms, the length of the+1animation);sendHeartTippays in the background. After 700 ms only the +1 leaves; the fill and the count remain. Session hearts not yet in the serverheartCountareextra; each successful click adds exactly 1 to that count, never the sat amount. A second tap sends another heart and counts up; there is no undo. A heart that is not sent rolls back that tap'sextra; it is also reported. The one exception is a wallet snapshot that is ready with less thanheartSats(or theheart-needs-balancepin): then there is no vibrate, no new fill, and no +1, only therole="alert"lineforum.heartNeedsBalanceunder the heart, and nothing is sent. The Playwright-onlyheart-credit-closed-refreshedpin appliescreditClosedto every shown heart id so an authoritative closed-loan body can picture the retained refusal alert without a heart control. A signed-out or read-only tap does nothing. After a paid click,onPaid(messageId)lets the host reload the expanded reactions so the Hearts section appears. A send that first timed out and later reportssentLatetruerestores that tap's 1 in the stored sessionextra, reconciles it against the current server count, and callsonPaidonce as well, so the count is not low until a reload and a later server update cannot count it twice; that late heart is then done, and a later tap is a new heart with its own invoice and payment. A tap while that late outcome is still in flight keeps thetimeout_pendingorpaidsettlement result. A late failure restores nothing and calls neither. - Inputs:
{ readOnly }matching the board,heartCounts(id to the server heart count of notes the board actually shows; omit for{}), and optionalonPaid(messageId). - Returns / side effects:
{ onHeartTip, heartTipViews }passed toForumBoard; each view is{ pressed, plusOne, needsBalance, extra }, pluscannotReceive: trueaftercannot_receiveorcreditClosed: trueaftercredit_closed. The board showsforum.payErrorAuthorWalletor the localizedforum.payErrorCreditClosedloan-no-longer-collecting line; a heart-count update and a concurrent failure for another reason keep it (heartFailureView), and the next tap clears it. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread.
Function: proxyMessagesComposeTargetGet
- Purpose: Same-origin proxy for
GET /messages/compose-target. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/messages/compose-target/route.ts.
Function: proxyMessagesInvoicePost
- Purpose: Same-origin proxy for
POST /messages/:id/invoice. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/messages/[id]/invoice/route.ts.
Function: MessagesPage
- Purpose: Next.js page for
/messages(signed-in PN inbox). - Inputs: None.
- Returns / side effects: Fill
AppShell(align="center") withMessagesChromeLeftinSuspensetop-left (fallbackProfileChromeLeft),SignedInChrometop-right, andOnboardingGatearoundInboxLoader. Conversation HTTP is under/conversations. - Used by: Route
/messages.
Function: InboxLoader
- Purpose: Client loader for
/messages. Session and account fromuseAuthStore; returns null without a session. Fetches the unpagedGET /conversationslist, opens?c=viaonOpenrouter.push, and posts replies. An open thread setsshowAttachtrue: camera photos or JPEG/PNG/WebP gallery stills (cap 10) viaprepareForumPhoto; photo-only send allowed. Send is disabled whileposting || preparing. Thread stills load withfetchConversationMessagePhoto. Blob URLs are revoked on unmount, on thread switch, and on session loss; drafts and preparing drop on those same events (pickGeneration). The invoice path stays text/sats only and clears still drafts. The list has no attach. The first paint of an open thread callsfetchConversation(session, openId)without a cursor for the newest 20-message page. AnIntersectionObserveronInboxScreen'snearStartRef(the eighth grouped bubble from the start, or the first when fewer than eight render) attaches only after the thread end is in view or the thread fits, uses the active page scrollport as its root when one is mounted, then fetches a setnextCursorand prepends unique older messages. The first screen is the newest message. The cursor load does not blank the thread; while stuck to the bottom, InboxScreen keeps the newest in view. Returning to the list is the chrome link (noonBackhandler). Moderators getshowFiltertrue; members see the unfiltered inbound list.?c=opens only after the inbox list loaded. For a moderator an unlisted?c=first resolvesfetchModeratorGrouponce per id (neutral Loading…, not the list, while it runs); when that id matches, the thread never opens andfetchConversationis not called. A listedmoderator_grouprow never opens either. Other roles, and a failed lookup, fall through tofetchConversation; the api rejects accounts that may not read the thread. Also callsuseSpotRate()and passesrateDaytoInboxScreen. While a private thread is open and the tab is visible, the newest page is fetched every 5 seconds and unseen messages are appended; a hidden tab does not poll, and a failed poll keeps the thread. - Inputs: None (reads session and account from the auth store;
useSearchParams). - Returns / side effects: React element or
nullwithout a session. CallsfetchConversations,fetchConversation,fetchModeratorGroup(roleAtLeast(role, 'moderator'), unlisted?c=only),prepareForumPhoto,fetchConversationMessagePhoto,postConversationMessage,postConversationInvoice. After a successful thread fetch, localunread: falseandunreadMessageCount: 0, then fire-and-forgetmarkConversationRead,bumpUnreadAppBadgeEpochandrefreshUnreadAppBadge(remaining inbox from the local list; a thread only opens after the list loaded, so there is no second conversations fetch). After a successful paid-gift poll orpostConversationMessage, the matching list row is alsounread: falseandunreadMessageCount: 0(including when the first thread fetch failed). When that poll fills a thread whose firstfetchConversationfailed (messages === null), it also clearsmessagesErrorand takesnextCursorfrom the poll page so older history can still prefetch. Must not fail the thread view. AWalletRequiredError(apicodewallet_required) frompostConversationInvoicesets the form errorwalletRequired. When the open thread's row hascanReceive: false, a reply sends no amount, and a typed amount, an open invoice, and its payment poll are dropped (the list reloads after a session change). An invoice request still waiting when that happens is dropped when it returns, and Send works again without an amount. - Used by:
MessagesPage.
Function: groupThreadGifts
- Purpose: Pure grouping helper for an inbox/moderator-group thread. A message whose
giftFor equals a DIFFERENT message's id present in the same list is removed from the top level and appended to that parent's gifts, in original list order; a giftFor that is unknown, self-referencing, or names a message that is itself a gift leaves the message as an ordinary top-level entry with empty gifts, so no message is ever dropped. Order of top-level messages is preserved regardless of where a gift appears in the input array.
- Inputs: Oldest-first
ConversationMessage[]. - Returns / side effects:
ThreadGiftGroup[]({ message, gifts }per top-level message).
No side effects.
- Used by:
InboxScreen.
Function: InboxScreen
- Purpose: Presentational inbox: incoming threads as a conversation list, or one open thread with a 8000-character
MentionTextareaand sats amount field (showAmountfalse hides the field; the staff room has no gifts). Typing@lists people. Choosing one inserts@username. The moderator room uses this same composer. When attach is shown, Take a photo (CameraPhotoButton) and attach are a row of their own above the message. The message and send share one row; the amount is the next row (AmountEntrylayout="composer"), aligned with the message. An open invoice keeps that amount row on the page, disabled behind the pay sheet (after a payment also through the sheet's success step,usePaySheetHold; a close by the member frees it at once); the sheet states the amount large, as bitcoin plus the default fiat from the current spot rate. Without an amount, send stays vertically centered on the message; the photo icons stay on the row above.showAttach(default false for callers that omit it) adds the camera (CameraPhotoButton) and the ImagePlus control, still previews, and photo-only send; InboxLoader open threads and ModeratorGroupScreen pass true. Non-empty bodies go throughForumQuotedBodyso a pastedhttps://21.gifts/messages/<uuid>unfurls as a nested quoted-note card, using the samerateDay(a stored string as-is; a null or missing field on a passedstoredobject shows the current spot, and stays off the line only when that spot is not loaded; omittingstoreduses the current spot rate). A storedmentionslist turns@usernameinto a profile button for/members/<accountId>. That mark does not notify the person.photoUrls(${messageId}:${index}) render attached stills. WhenshowFilteris true (moderator), the list is filtered by the origin control (Direct / Contact / Damus; default Direct). Rows withkindmoderator_groupare never listed; the closed staff room lives on/moderate/group. Members (showFilterfalse) see inbound rows exceptmoderator_groupand no control. Each list row and the open-thread header show an origin label fromconversation.kind(Contact / Direct / Damus / Moderators chat group). Unread inbound rows usefont-semiboldnames,text-app-fglast text, a visible tabular-nums lining-nums unread-message count right of the name when the derived count is greater than zero (row.unreadMessageCount, or 1 whenunreadis true and the count is 0), andaria-labelinbox.threadUnreadwith{name}and{count}. The word Unread is not visible text. Read inbound last text is a muted preview. WhenlastFromMeis true andlastTextis non-empty, the list preview isinbox.sentPreview(You: {text}) in a filled chip; gift-only last messages (lastSats > 0, emptylastText) show the formatted amount . The list does not offer Translate. Thread remainders go throughForumQuotedBodywithconversationId(translateConversationMessage); nested forum quotes stay ontranslateNote. Thread incoming messages are full-width muted note cards;fromMemessages render as filledapp-btnbubbles on the right labelledinbox.you. Gift-only bubbles useforum.giftReply; text+sats shows the amount under the body. An open invoice shows the bottomPaySheet(Send to {name}, or Send without a name). Close (X) dismisses that sheet and stays on the thread. It is not the top-left back arrow. Open-thread heading is counterpart name + origin caption (noonBack, no in-card back). Heading and incoming author names withaccountIdareinbox.authorProfilebuttons to/members/:id;fromMestaysinbox.youtext; Damus/missing id stays plain text. A staff viewer sees another staff reply as an incoming muted card with that person'sname(profile link whenaccountIdis set).fromMe/inbox.youonly when this session is the actor. Settled thread sats amounts (gift-only bubble, text+sats line, and nested gift line) show a preferred-fiat suffix viapreferredFiatSuffix: a stored string as-is, and the current spot when that string is missing (bitcoin alone only when that spot is not loaded). Unpaid invoice previews use optionalrateDay(the current spot rate). A message whosegiftForpoints at another message renders viagroupThreadGiftsas a nestedrole="note"line inside the parent's<li>(name, ₿ amount, fiat suffix, time; not shown as its own top-level row) instead of a separate bubble. When supplied,nearStartRefattaches to the eighth grouped bubble from the start, or the first bubble when fewer than eight render, only after the thread end is in view or the thread fits. A scroll event attaches it only when the end is already in view. Being within 80px of the bottom sticks the view but does not by itself attach older history. Landing again on the last pin offset sticks when that offset is within 80px of the bottom. An open thread (openIdset, messages loaded) scrolls the page scrollport to the bottom so the first screen is the newest message and the composer. While stuck to the bottom (within 80px), prepends and stills keep the newest in view; scrolling up unsticks and prepends compensate scrollTop. A newest-id change re-sticks. Inside AppShell the pin waits for that scroller and does not fall back towindowwhile the node is missing (windowonly outside AppShell); the pin runs again when an invoice pay sheet opens; list view does not pin to the bottom; leaving a thread scrolls the list to the top once. The pay sheet's pay control isWalletPay, which pays from the member's in-app wallet (sparkInvoicewhen the api issued one, otherwisepr, which is also paid when the wallet refuses the Spark invoice); the sheet shows no invoice QR on any device. When the open thread hascanReceive: false, the amount field is disabled and Can't receive yet (CannotReceiveLabel) shows under it; text and photos still send. No invoice sheet shows for such a thread. - Inputs: List/thread/composer state from
InboxLoaderorModeratorGroupScreen. - Returns / side effects: React element. InboxScreen itself does not fetch;
ForumQuotedBodymay callfetchPublicMessagefor pasted/messages/<uuid>URLs. Form errorwalletRequiredrendersrole="alert"with the wallet-required link (inbox.errorWalletRequired) to/wallet. With an open invoice, the pay sheet is aPaySheet(inside aCollapsewithholdMsPAY_SHEET_HOLD_MS) titled Send to {name} with the open thread's name (Send without one), itsWalletPaybutton Send {amount}, and its success step Sent to {name} (or Sent); Close callsonPayCancel. - Used by:
InboxLoader,ModeratorGroupScreen.
Function: fetchConversations
- Purpose: GET
/conversationswith Bearer and parse{ conversations, unreadCount }. Missingunreaddefaults false; missingunreadCountdefaults 0; missingunreadMessageCountdefaults 0. The api returns incoming threads, plus the member's own 21.gifts contact thread when it has a message. GET/conversationsnever lists themoderator_groupthread, even for moderators. Each row includes requiredkind:member_member|member_platform|member_damus|moderator_group, requiredlastFromMe(true when the last message was sent by this session as the actor, not when another staff member sent as the platform), requiredlastSats, optionalaccountId(counterpart),unread, andunreadMessageCount(inbound unread messages). EnvelopeunreadCountis unread thread count. - Inputs: Session token.
- Returns / side effects: Conversation list, or throws visitor copy.
- Used by:
InboxLoader,ContactLoader,useUnreadCount,NotificationsLoader,refreshUnreadAppBadge.
Function: fetchConversation
- Purpose: GET
/conversations/:idwith Bearer, always sendinglimit=20, plus optionalcursorandsinceMessageId. Parses{ messages, nextCursor? }. Each message includes requiredfromMe(true iff this session is the actor) andsats, plushasPhoto/photoCount(client default 0 when omitted). For a staff viewer, incomingnameand optionalaccountIdare the actor when the api sends them. The newest page is returned first and messages inside each page are oldest-first;nextCursoris supplied only for a full page. - Inputs: Session token, conversation id, optional
{ sinceMessageId, cursor, signal }. - Returns / side effects:
{ messages, nextCursor }, normalizing an omittednextCursortonull, or throws visitor copy. - Used by:
InboxLoader,ModeratorGroupScreen.
Function: postConversationMessage
- Purpose: POST
/conversations/:idwith{ text }and, whenphotosis non-empty,{ photo, photos }(first still duplicated asphoto, at most 10 JPEG/PNG/WebP stills). Empty text is allowed when photos are present (Moderators group and/messagesDirect/Contact/Damus). Staff replies on official threads still send as the platform account on the api, but the created message'sfromMe,name, andaccountIdfollow the actor. - Inputs: Session token, conversation id, text, optional photos array.
- Returns / side effects: Created message, or throws api/visitor copy.
- Used by:
InboxLoader,ModeratorGroupScreen.
Function: fetchConversationMessagePhoto
- Purpose: GET
/conversations/:id/messages/:messageId/photo(index 0) or/photo/{n}.jpg(indices 1–9) with Bearer. Callers use a blob URL, not a bare<img src>. Empty body throws. - Inputs: Session token, conversation id, message id, optional zero-based index (default 0).
- Returns / side effects: Photo
Blob, or throws visitor copy (Could not load messages. Please try again.). - Used by:
InboxLoader,ModeratorGroupScreen.
Function: proxyConversationMessagePhotoGet
- Purpose: Same-origin Bearer proxy of api GET
/conversations/:id/messages/:messageId/photoor/photo/:file. - Inputs: Incoming App Router
Request, conversation id, message id, optional file (1.jpg–9.jpg). - Returns / side effects: Upstream image response.
- Used by:
GETon/conversations/[id]/messages/[messageId]/photoand/photo/[file].
Function: postConversationInvoice
- Purpose: POST
/conversations/:id/invoicewith{ sats },{ sats, text }, andamountUsd,amountChf,amountEur,amountPhpwhen a preview rate is on screen. Emptytextis omitted. A missing preview omits those four fields. - Inputs: Session token, conversation id, sats, optional text, optional shown
amountUsd,amountChf,amountEur, andamountPhp(each a two-decimal string or null). - Returns / side effects:
{ pr, amountSats, messageId, sparkInvoice? }, or throws api/visitor copy.sparkInvoiceis optional and may benull, as onpostMessageInvoice. A 400 withcodewallet_requiredthrowsWalletRequiredErrorand one withcannot_receivethrowsCannotReceiveError(viathrowIfWalletAnswer);InboxLoadermapsCannotReceiveErrortoauthorWallet. - Used by:
InboxLoader.
Function: openConversation
- Purpose: POST
/conversationswith{ forumMessageId }. - Inputs: Session token and forum note/reply id.
- Returns / side effects: Conversation row, or throws on 400/404/other.
- Used by:
MemberProfileScreenMessage (profile.message).
Function: markConversationRead
- Purpose: POST
/conversations/:id/readwith Bearer. Non-ok throws; success may ignore body. - Inputs: Session token and conversation id (encoded in the path).
- Returns / side effects: void, or throws visitor copy.
- Used by:
InboxLoaderafter a successful thread fetch (fire-and-forget; failures are ignored).ModeratorGroupScreenafter a successful group+thread load (fire-and-forget; failures are ignored).
Function: proxyConversationsGet
- Purpose: Same-origin proxy for api GET
/conversations. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/conversations/route.ts.
Function: proxyConversationsPost
- Purpose: Same-origin proxy for api POST
/conversations. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/conversations/route.ts.
Function: proxyModeratorGroupGet
- Purpose: Same-origin Bearer proxy for api GET
/conversations/moderator-group(singleton closed staff room as{ conversation }). - Inputs: App Router
Request. - Returns / side effects: Forwards to the api path
/conversations/moderator-group. - Used by:
src/app/conversations/moderator-group/route.ts.
Function: proxyConversationGet
- Purpose: Same-origin proxy for api GET
/conversations/:id. - Inputs: App Router
Requestand conversation id. - Returns / side effects: Forwards to the api.
- Used by:
src/app/conversations/[id]/route.ts.
Function: proxyConversationPost
- Purpose: Same-origin proxy for api POST
/conversations/:id. - Inputs: App Router
Requestand conversation id. - Returns / side effects: Forwards to the api.
- Used by:
src/app/conversations/[id]/route.ts.
Function: proxyConversationInvoicePost
- Purpose: Same-origin proxy for api POST
/conversations/:id/invoice. - Inputs: App Router
Requestand conversation id. - Returns / side effects: Forwards to the api.
- Used by:
src/app/conversations/[id]/invoice/route.ts.
Function: proxyConversationReadPost
- Purpose: Same-origin proxy for api POST
/conversations/:id/read. App route is POST/conversations/[id]/read. - Inputs: App Router
Requestand conversation id. - Returns / side effects: Forwards to the api (id encoded).
- Used by:
src/app/conversations/[id]/read/route.ts.
Function: NotificationsPage
- Purpose: Next.js page for
/notifications(signed-in notifications for living-room posts, replies, payments, moderator appointment, and moderator proposal). - Inputs: None.
- Returns / side effects: Fill
AppShell(align="center") withProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGate screen="welcome"aroundNotificationsLoader. Notification HTTP is under/forum/notifications(noroute.tsbeside this page). - Used by: Route
/notifications.
Function: NotificationsLoader
- Purpose: Client loader for
/notifications. FetchesGET /forum/notifications(posts, replies, payments, hearts, moderator appointment, and moderator proposal). After a successful list fetch,bumpUnreadAppBadgeEpochthen set the badge to remaining inbox unread plus staff-room unread (0or1; notifications treated as 0; visiting/notificationsdoes not force badge 0 when inbox or staff-room unread remains). Repeats aftermarkAllNotificationsReadif the session is unchanged. Fetches conversations (fetchConversations) and, whenroleAtLeast(account?.role, 'moderator'), the staff room (fetchModeratorGroup) for those counts; below moderator, remaining badge is inbox unread only (staff-room contributes 0, no request). A side that fails contributes 0. Opening amoderator_proposalrow goes to/moderate/proposalswithoutmarkNotificationRead. Opening amoderator_appointedrow waits formarkNotificationReadthen goes to/welcome(still navigates if that POST fails; skips navigation if the session changed). Aforum_replyorforum_mentiongoes to/messages/{replyId}without waiting. Aforum_post,zap, orheartgoes to/messages/{parentId}without waiting. Ids are URI-encoded. - Inputs: None (session from the auth store).
- Returns / side effects: React element or
nullwithout a session. No composer. After a non-cancelled successful list fetch, marks all read fire-and-forget, thenbumpUnreadAppBadgeEpochand sets the home-screen badge to remaining inbox unread plus staff-room unread (0or1; notifications treated as 0). Repeats aftermarkAllNotificationsReadif the session is unchanged. Fetches conversations (fetchConversations) and, whenroleAtLeast(account?.role, 'moderator'), the staff room (fetchModeratorGroup) for those counts; below moderator, remaining badge is inbox unread only (staff-room contributes 0, no request). A side that fails contributes 0. Does not clear remaining inbox or staff-room unread on error, cancel, or missing session. Every fetched row is rendered, including those withreadAtset, in API order; read rows are not discarded. - Used by:
NotificationsPage.
Function: NotificationsScreen
- Purpose: Presentational notifications list of living-room posts, replies, payments, hearts, moderator appointment, and moderator proposal (actor
{name} posted/{name} replied/{name} sent bitcoin/{name} sent you a heart/{name} proposed a moderator;moderator_appointedtitle usesnotifications.moderatorAppointedwith no{name}placeholder; post text or Photo, except aforum_postwhosetextequalsnameomits the body (profile-note leftover); reply text or Photo reaction, zap amount as stored, a heart omits the raw body text (it is not the"1"sat string), moderator appointment or proposal body only whentextis non-empty — emptytextomits the body line and does not usenotifications.photoPost/photoOnly; time; unread semibold).onOpenreceives the row object. No composer, no thread view, and no filter. Unread rows (readAt === null) are a section above rows that already havereadAt, each section keeping API order; an empty section is omitted. In every state the card ends with a muted underlined Notification settings link (settings.notificationSettings) to/settings#notifications. - Inputs: List state from
NotificationsLoader(notifications,error,loading,onRetry,onOpen). - Returns / side effects: React element. No network.
- Used by:
NotificationsLoader.
Function: fetchNotifications
- Purpose: GET
/forum/notificationswith Bearer and parse{ notifications, unreadCount }. - Inputs: Session token.
- Returns / side effects:
{ notifications, unreadCount }, or throws visitor copyCould not load notifications. Please try again. - Used by:
NotificationsLoader,useUnreadCount,refreshUnreadAppBadge,ForumLoader(welcome appointment banner).
Function: markNotificationRead
- Purpose: POST
/forum/notifications/:id/readwith Bearer and optional JSON{ endpoint }when this browser has a push subscription.currentPushEndpoint()is sent only when it is a non-empty string. Parses one notification. - Inputs: Session token and notification id (encoded in the path).
- Returns / side effects: Updated notification, or throws visitor copy.
- Used by:
NotificationsLoaderon row click;ForumLoaderwhen the welcome appointment pill is clicked.
Function: markAllNotificationsRead
- Purpose: POST
/forum/notifications/read-allwith Bearer and optional JSON{ endpoint }when this browser has a push subscription. Non-ok throws. When the body has atagsarray, those local notifications are closed. A body withouttagscloses nothing. - Inputs: Session token.
- Returns / side effects: void.
- Used by:
NotificationsLoaderfire-and-forget after a successful list fetch.
Function: markNotificationsReadForMessage
- Purpose: POST
/forum/notifications/read-by-messagewith Bearer and JSON{ messageId, endpoint? }.endpointis sent only when the current push endpoint is a non-empty string. Non-ok throws visitor copyCould not mark notification as read. On success, closes local notifications for stringtags; a missingtagsfield is[]. - Inputs: Session token and forum message id.
- Returns / side effects:
{ ok: true, tags: string[] }. - Used by:
ForumLoaderwhen a note becomes expanded,NoteTranslatewhen Translate is requested for a forum note while a session is present (not for a conversation message),PublicMessageLoaderwhen a signed-in message page is ready,MemberProfileScreenwhen a profile note becomes expanded, andPublicMessageThreadwhen a thread note becomes expanded.
Function: markVisibleForumNoteRead
- Purpose: POST
/forum/notifications/read-visiblewith Bearer and JSON{ messageId, endpoint? }.endpointis sent only when the current push endpoint is a non-empty string. Non-ok throws visitor copyCould not mark notification as read. On success, closes local notifications for stringtags; a missingtagsfield is[]. - Inputs: Session token and forum message id.
- Returns / side effects:
{ ok: true, tags: string[] }. - Used by:
ForumLoaderwhen a signed-in note card is fully inside the AppShell scrollport.
Function: isForumCardFullyVisible
- Purpose: True only when a forum note card sits fully inside the AppShell scrollport within
epsilonPx(default 1). A zero-size card is false. A card taller than the root by more thanepsilonPxis false. A card 2px past the root is false. A card exactly 1px past is true. - Inputs: Card and root
DOMRectReadOnlypicks (top,bottom,left,right,width,height), and optionalepsilonPx(default 1). - Returns / side effects: Boolean. No side effects.
- Used by:
ForumLoaderwhen measuringli[data-message-id]inside the shell scroller.
Function: activeMention
- Purpose: Find the
@usernametoken under a collapsed caret in a forum composer. A mark starts at@only when the previous character is not a username character, so an email address is not a mark. The query is the lowercase text between@and the caret. A bare@is a mark with an empty query. - Inputs: Composer text and a caret index.
- Returns / side effects:
{ start, end, query }, ornullwhen the caret is outside a mark, the query is longer than 32 characters, or the query is not a username prefix. - Used by:
MentionTextarea.
Function: remapClosedMentionStarts
- Purpose: Keep a dismissed
@attached to that character across one edit. Indexes after the edit shift with the text. An@inside the replaced span is forgotten, so a different@that lands on the old index opens. - Inputs: The previous composer value, the next value, the dismissed
@indexes, and the caret in the next value, or nothing when the caret is unknown. - Returns / side effects: The same set when no dismissed
@moved, otherwise the shifted indexes. - Used by:
MentionTextarea.
Function: MentionTextarea
- Purpose: Forum text field that lists people as soon as
@is typed. The field stays mounted when the list opens. The first page is prefetched for the signed-in session. More letters narrow the list to usernames that start that way in the same update, even when a previous server page is still stored. Choosing a row inserts@usernameand closes the list. A space already after the token stays a single space. A choice that would pass the length limit is not inserted. Keys during text composition stay with the input method. The caret sits after that space even when the text was already that handle. Escape or Tab, even while the first page is still loading, or a click outside the open list, keeps each such@closed until that character is gone, and a different@does not inherit the closure when text shifts. Choosing does not remember that@as closed. The list sits under the field, and above it only when this list would not fit underneath and there is more room above. No session, or a disabled field, is a plain textarea. - Inputs: Controlled value,
onChange, disabled, wrapper and textarea classes, accessible name, and optional placeholder, max length, rows,ariaDescribedBy,ariaInvalid, and textarea ref. - Returns / side effects: The textarea. When a token is active and at least one person matches, a
Peoplelistbox. Inserts the chosen handle throughonChange. - Used by: The post composer and reply composer in
ForumBoard, the ask-for-money text step inForumAskWizard, the shop text step inShopAddWizard, andInboxScreen(inbox and the moderator room).
Function: searchMentionAccounts
- Purpose: Load username suggestions for an
@token. Calls same-origin GET/forum/mentions, addingqonly when the prefix is non-empty. - Inputs: Bearer session and a lowercase prefix (
""for the first page). - Returns / side effects:
{ id, username, name }[]. Throws when the response is not 200 or the body is not that list. A non-empty search is recorded assearchwith the term and the number of results. - Used by:
MentionTextarea,ShopAccountControl,DailyPaymentAmountsScreen,ShopAddWizard.
Function: lookupAccountByUsername
- Purpose: Exact account lookup while a shop username is typed. Calls same-origin GET
/forum/accounts/by-username/:username. - Inputs: Bearer session and the username.
- Returns / side effects:
'found'when the response is 200 and the body has stringid,username, andname. Extra fields are ignored, and the stored spelling is not compared again.'missing'on 404, without parsing the body. Any other status, a 200 body without those three strings, or a fetch failure throws and is not reported as missing. - Used by:
ShopAddWizard,ShopAccountControl, andForumLoader.
Function: proxyForumMentionsGet
- Purpose: Same-origin proxy for api GET
/mentions. App route is GET/forum/mentions. Forwards the query string. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/forum/mentions/route.ts.
Function: proxyForumAccountByUsernameGet
- Purpose: Same-origin proxy for api GET
/accounts/by-username/:username. App route is GET/forum/accounts/by-username/[username]. - Inputs: App Router
Requestand the username from that route. - Returns / side effects: Forwards to the api with the username encoded.
- Used by:
src/app/forum/accounts/by-username/[username]/route.ts.
Function: proxyNotificationsGet
- Purpose: Same-origin proxy for api GET
/notifications. App route is GET/forum/notifications. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/forum/notifications/route.ts.
Function: proxyNotificationsReadAllPost
- Purpose: Same-origin proxy for api POST
/notifications/read-all. App route is POST/forum/notifications/read-all. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/forum/notifications/read-all/route.ts.
Function: proxyNotificationsReadByMessagePost
- Purpose: Same-origin proxy for api POST
/notifications/read-by-message. App route is POST/forum/notifications/read-by-message. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/forum/notifications/read-by-message/route.ts.
Function: proxyNotificationsReadVisiblePost
- Purpose: Same-origin proxy for api POST
/notifications/read-visible. App route is POST/forum/notifications/read-visible. - Inputs: App Router
Request. - Returns / side effects: Forwards to the api.
- Used by:
src/app/forum/notifications/read-visible/route.ts.
Function: proxyNotificationReadPost
- Purpose: Same-origin proxy for api POST
/notifications/:id/read. App route is POST/forum/notifications/[id]/read. - Inputs: App Router
Requestand notification id. - Returns / side effects: Forwards to the api (id encoded).
- Used by:
src/app/forum/notifications/[id]/read/route.ts.
Function: StatisticsPage
- Purpose: Next.js page for
/statistics(public measured people and shop charts, not a funding goal). Top-right is Log in without a session, nothing while a session is held back (the login card is in the page), andSignedInChromewith one.OnboardingGate screen="welcome"allowGuest. HTML/statisticsis the page, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left andOnboardingGate screen="welcome"allowGuestaroundStatisticsScreen. Noroute.tsbeside this page. Gift totals stay on public/stats. - Inputs: None.
- Returns / side effects: The statistics screen inside fill AppShell.
- Used by: Route
/statistics.
Function: ModeratePage
- Purpose: Next.js page for
/moderate(signed-in moderation hub for moderators). HTML/moderateis the hub, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left,SignedInChrometop-right, andOnboardingGate screen="welcome"aroundModerateScreen. Hidden HTTP lives under/forum/messages/hidden; proposal HTTP under/trust/proposals; grant-application HTTP under/funding/applications(noroute.tsbeside this page); the hub itself does not fetch. - Inputs: None.
- Returns / side effects: The moderation hub inside fill AppShell.
- Used by: Route
/moderate.
Function: roleRank
- Purpose: Numeric rank of a role from an explicit rank map (not
ROLE_ORDER.indexOf), for use byroleAtLeast. - Inputs:
role— one of'basis' | 'verified' | 'moderator' | 'fond' | 'software_developer' | 'initiator' | 'founder'. - Returns / side effects: Integer 0 through 6 (basis 0, verified 1, moderator 2, fond 3, software_developer 4, initiator 5, founder 6), read from the explicit rank map. Pure, no side effects.
- Used by:
roleAtLeast,layoutTrustChain.
Function: roleAtLeast
- Purpose: Product-rule primitive for every viewer permission/visibility check, including the daily payout roster: true when
rolemeets or exceedsminby numeric rank. An equal rank meets the minimum. A missing account (null/undefinedrole) is never at least any role. - Inputs:
role— live account role, ornull/undefinedwhen the account snapshot is absent;min— inclusive minimum role. - Returns / side effects: Boolean. Pure, no side effects; delegates to
roleRank. - Used by:
HabitComments,DeletePostControl,FondPayoutSync,FondDepositSync,ForumLoader,FundingApplicationDetailScreen,FundingApplicationsScreen,FundingApplyScreen,FundingPayoutsScreen,FundingStatusCard,GrantsScreen,HiddenNotesScreen,InboxLoader,MemberProfileScreen,MemberTrustActions,MemberVerifyScreen,ModerateHandbookScreen,ModerateScreen,ModeratorGroupScreen,NotificationsLoader,PlacesMapScreen,ProposalsScreen,PublicMessageThread,ShopAccountControl,ShopNoteEditControl,ShopPlaceControl,SignedInChrome,StatisticsScreen,useUnreadCount,refreshUnreadAppBadge,visibleForumMessages,canEditDailyPayoutRoster,isReplyPaymentExempt.
Function: canEditDailyPayoutRoster
- Purpose: The daily payout roster's minimum rank is
initiator: true forinitiatorandfounder, false for every lower role (includingfondandsoftware_developer) and fornull/undefined. - Inputs:
role— live account role, ornull/undefinedwhen the account snapshot is absent. - Returns / side effects: Boolean. Pure, no side effects.
- Used by:
GrantsScreen,DailyPaymentCommentScreen,DailyPaymentAmountsScreen,DailyPaymentModeratorsScreen.
Function: isOwnNote
- Purpose: True when the signed-in account wrote a note. A wallet cannot pay its own invoice, so nothing on your own note asks you to pay: the reply form there has no Amount field and posts unpaid, and your own payable reactions show no Gift (the heart is hidden through
heartViewerId). - Inputs:
viewerAccountId— signed-in account id, ornull/undefinedwhen signed out;noteAccountId— the note'saccountIdif the api sent one. - Returns / side effects: Boolean: true only when both ids are non-empty and equal. Pure, no side effects.
- Used by:
isReplyPaymentExempt,ForumBoard(reply amount field, Gift),ForumLoader,MemberProfileScreen, andPublicMessageThread(reply on the own note posts unpaid).
Function: isReplyPaymentExempt
- Purpose: True when the signed-in account may reply without paying: anyone at least verified is exempt, and every role is exempt on its own note (
isOwnNote). Basis on someone else's note is not exempt. - Inputs:
account—{ id, role }ornullwhen the account snapshot is missing;parentAccountId— the parent note'saccountIdif the api sent one (a missing id is not treated as exempt). - Returns / side effects: Boolean. Pure, no side effects; delegates to
isOwnNoteandroleAtLeast. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread.
Function: authorCannotReceive
- Purpose: True when a pay action on a note targets a member who cannot receive yet: the api sent
authorCanReceive: falsefor a live member note (accountIdset, nodeletedAt) that is not the viewer's own (isOwnNote). A body without the field is not this case. - Inputs:
note—{ authorCanReceive?, accountId?, deletedAt? };viewerAccountId— signed-in account id, ornull/undefinedwhen signed out. - Returns / side effects: Boolean. Pure, no side effects.
- Used by:
ForumBoard(label, disabled heart, Gift, Lend, and reaction amount),ForumLoader,MemberProfileScreen, andPublicMessageThread(a reply never invoices a gift to that author).
Function: utcDayFromMs
- Purpose: UTC calendar day
YYYY-MM-DDof an instant, taken fromtoISOString(the first ten characters of the ISO timestamp). - Inputs:
ms— epoch milliseconds of that instant. - Returns / side effects: UTC day string. Pure; no I/O.
- Used by:
previousUtcDay,chartRows,StatisticsScreen,ModerateScreen.
Function: previousUtcDay
- Purpose: UTC calendar day immediately before
day, so staff screens can name yesterday against the clock. - Inputs:
day— UTCYYYY-MM-DD. - Returns / side effects: Previous UTC day string. Pure; no I/O. Delegates to
utcDayFromMs. - Used by:
StatisticsScreenandModerateScreento pick yesterday.
Function: countOnDay
- Purpose: Person count on
yesterdayfromofficialCount. First matching day wins. - Inputs:
series—spendOverTimeoldest-first;yesterday— UTC day to look up. - Returns / side effects: That day's
officialCount,0when the day is missing, ornullwhen any point omitsofficialCount. Pure; no I/O. - Used by:
StatisticsScreen.
Function: chartRows
- Purpose: Last 30 UTC days ending on
today, oldest first, with person counts fromofficialCount. - Inputs:
series—spendOverTimeoldest-first;today— UTC day of the clock. - Returns / side effects: Oldest-first
{ day, count }rows. Last write wins when a day appears twice; a missing day is 0. Pure; no I/O. - Used by:
StatisticsScreen.
Function: formatUtcDate
- Purpose: Formats a UTC calendar day as numeric day plus long month in
localefor the yesterday sentence. - Inputs:
day— UTCYYYY-MM-DD;locale— active UI locale. - Returns / side effects: Locale date string in the UTC zone. Pure; no I/O.
- Used by:
StatisticsScreenin the yesterday sentence.
Function: chartDayLabel
- Purpose: Axis tick label for a UTC day as numeric day and month in
locale. - Inputs:
day— UTCYYYY-MM-DD;locale— active UI locale. - Returns / side effects: Short numeric day-month label in the UTC zone. Pure; no I/O.
- Used by:
ShopActivityChartandPeopleCountChartfor the first, middle, and last axis labels.
Function: fetchFxSpot
- Purpose: Loads the current price of 1 BTC in USD, CHF, EUR, and PHP from same-origin
GET /fx/spotwith no Authorization. The body is{ asOf, source, rates };ratesleaves out a code the api could not price. Without any quote the api answersasOfandsourcenullandrates{}, which is "no rate". - Inputs: None.
fetch('/fx/spot')with no Authorization. - Returns / side effects:
FxSpotparsed byfxSpotSchema(each price a decimal string such as"62345.12"). Throws Could not load the exchange rate. Please try again. on a non-OK response, a network failure, or a body that fails the schema. - Used by:
useSpotRate.
Function: proxyFxSpotGet
- Purpose: Same-origin proxy for api
GET /fx/spot. App route isexport const GET = proxyFxSpotGeton/fx/spot. No bearer is required. Forwards the incoming request unchanged. - Inputs: App Router
Request. - Returns / side effects: Upstream response from
proxyApiRequest(request, '/fx/spot'). - Used by:
src/app/fx/spot/route.ts.
Function: fetchShopActivity
- Purpose: Loads public shop-use counts from same-origin
GET /shops/activitywith no Authorization. StatisticsScreen calls it with or without a session. The body must be 30 unique contiguous UTC days, oldest first; otherwise this throws and the shop panel shows its error state. - Inputs: None.
fetch('/shops/activity')with no Authorization. - Returns / side effects:
ShopActivityDay[](day,shopCount). Network viafetch. Does not require the last day to be the browser's today. - Used by:
StatisticsScreenshop panel.
Function: proxyShopActivityGet
- Purpose: Same-origin proxy for api
GET /shops/activity. App route isexport const GET = proxyShopActivityGeton/shops/activity. No bearer is required. Forwards the incoming request unchanged. - Inputs: App Router
Request. - Returns / side effects: Upstream response from
proxyApiRequest(request, '/shops/activity'). - Used by:
src/app/shops/activity/route.ts.
Function: fetchListedShops
- Purpose: Loads one page of the public shop directory from same-origin
GET /shops/list?limit=20with no Authorization. ShopList calls it whether or not an account is signed in. An optional cursor is sent as&cursor=. A missingnextCursoris the end of the list.nextCursor: nullis rejected. A shop npub that failsSHOP_NPUB_REis rejected.placemay be null, andaddressmay be null. A body that omitsplace, or omitsaddresson a place object, is rejected. Otherwise this throws and the list showsshops.loadError. - Inputs: Optional
cursorstring. Omit it for the first page.fetch('/shops/list?limit=20')sends no Authorization header. - Returns / side effects:
{ shops: ShopListItem[]; nextCursor: string | null }. Network viafetch. ThrowsCould not load shops. Please try again.when the response is not ok or the body failsshopListResponseSchema. - Used by:
ShopList.
Function: proxyShopListGet
- Purpose: Same-origin proxy for api
GET /shops. App route isexport const GET = proxyShopListGeton/shops/list. No bearer is required. Forwards the incoming request unchanged, includinglimitandcursor. - Inputs: App Router
Request. - Returns / side effects: Upstream response from
proxyApiRequest(request, '/shops'). - Used by:
src/app/shops/list/route.ts.
Function: fetchGrantPlaces
- Purpose: Loads the public grant round places from same-origin
GET /funding/placeswith no Authorization.GrantPlacesPanelcalls it on the grant pages. The body must matchgrantPlacesSchema(roundandnextGoalShopspositive integers,places,admitted, andplacesLeftnonnegative integers,startsAta string); otherwise this throws. - Inputs: None.
- Returns / side effects:
GrantPlaces. Network viafetch. ThrowsCould not load the grant places. Please try again.on a non-ok response, a network failure, or a schema failure. - Used by:
GrantPlacesPanel.
Function: proxyFundingPlacesGet
- Purpose: Same-origin proxy for the public api
GET /funding/places. No session is required; the request is forwarded as received. - Inputs:
request(incoming App Router request). - Returns / side effects: Upstream response from
proxyApiRequest(request, '/funding/places'). - Used by:
src/app/funding/places/route.ts.
Function: fetchGrantContinuation
- Purpose: Loads the signed-in grant goal from same-origin
GET /funding/goalwithAuthorization: Bearer. GrantGoalsScreen calls it only when a session exists. The body must be 7 unique contiguous UTC days, oldest first, plus a nonnegativequalifyingShops; otherwise this throws and the goals page shows its error state. Does not callfetchShopActivity. - Inputs:
sessionToken— bearer session.fetch('/funding/goal')sends that token and does not invent one. - Returns / side effects:
GrantContinuation(days,qualifyingShops). Network viafetch. Does not require the last day to be the browser's today. - Used by:
GrantGoalsScreen.
Function: proxyFundingGoalGet
- Purpose: Same-origin proxy for api
GET /funding/goal. App route isexport const GET = proxyFundingGoalGeton/funding/goal. Forwards the incoming Authorization header and does not add one. This is not the public shop-activity proxy. - Inputs: App Router
Request. - Returns / side effects: Upstream response from
proxyApiRequest(request, '/funding/goal'). - Used by:
src/app/funding/goal/route.ts.
Function: ShopActivityChart
- Purpose: Draws the shop-count SVG (
role="img") for the UTC days it is given. Scale is the max count (at least 1). Ticks are 0, that scale, and the rounded midpoint when it differs. Today's bar isfill-app-subtle; other bars arefill-app-accent. Bars only when count > 0.data-testid="shop-activity-chart-bar". No goal line. - Inputs:
rows({ day, count }[]),today(UTC day drawn lighter),locale, andariaLabel. - Returns / side effects: SVG figure. No network.
- Used by:
StatisticsScreen(30 days) andGrantGoalsScreen(the last 7 days).
Function: PeopleCountChart
- Purpose: Draws the people-count SVG (
role="img") for 30 UTC days. Scale is the max count (at least 1). Ticks are 0, that scale, and the rounded midpoint when it differs. Today's bar isfill-app-subtle; other bars arefill-app-accent. Bars only when count > 0.data-testid="people-count-chart-bar". No goal line. - Inputs:
rows({ day, count }[]),today(UTC day drawn lighter),locale, andariaLabel. - Returns / side effects: SVG figure. No network.
- Used by:
StatisticsScreen.
Function: StatisticsScreen
- Purpose: Client chart of people counted once per UTC day, with a shop-activity panel under the people chart. A signed-out visitor fetches both feeds and sees both panels. Does not return
null. Any visitor fetches both feeds and sees yesterday's person count, the measurement paragraph, and the 30-UTC-day people chart (no goal line), then the shop panel (one explainer and the 30-UTC-day shop-count chart). Each panel loads and fails on its own. The people panel is always open and there is no Tap to close. No forbidden card. WhenroleAtLeast(..., 'moderator')and yesterday's person count is a number (including 0; not loading and not the people error panel, including omittedofficialCount), closedStaffFunctionssits after the people chart and before the shop panel; its only child is the payoutButtonLink(href/moderate/payouts,variantsecondary,sizelg, labelmoderate.payouts.link). Basis and verified never renderStaffFunctions. A signed-out visitor never rendersStaffFunctions. - Inputs: Account from
useAuthStore; catalog and locale viauseTranslations. - Returns / side effects: A React element. No session still fetches. Fetches
GET /gifts/statsand also callsfetchShopActivity. Does not returnnull. - Used by:
StatisticsPage.
Function: ModerateScreen
- Purpose: Client moderation hub of staff tools. Staff (
roleAtLeast(..., 'moderator')) see a labeled GoalsButtonLink(variant="secondary"size="lg") →/grants/goals(first tool), a labeled Hidden notesButtonLink(variant="secondary"size="lg") →/moderate/hidden, a labeled Open proposalsButtonLink(variant="secondary"size="lg") →/moderate/proposalsthat showsproposalCountplusmoderate.proposals.unreadwhen greater than zero, a Moderators chat groupButtonLink→/moderate/groupthat shows the staff-room unread count plusmoderate.groupUnreadwhen unread, a labeled HandbookButtonLink(variant="secondary"size="lg") →/moderate/handbook, a labeled Show payout per personButtonLink(variant="secondary"size="lg") →/moderate/payouts, and a labeled Show activity per shopButtonLink(variant="secondary"size="lg") →/moderate/shops(last tool). There is no payout-goal widget. Non-staff signed-in visitors see the heading plus forbidden copy and no tools list. Does not fetch hidden notes, proposals, applications, gift stats, or the group thread itself; unread for Open proposals and Moderators chat group comes fromuseUnreadCount. Rendersnullwithout a session. No un-hide control. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations;useUnreadCount(true, { writeBadge: false })for Open proposalsproposalCountand Moderators chat group staff-room unread (network for those counts; does not write the home-screen badge). - Returns / side effects: React element or
nullwithout a session. Does not fetchGET /gifts/stats. Others see forbidden copy and do not fetch. Does not fetch hidden notes, proposals, applications, or the group thread itself. - Used by:
ModeratePage.
Function: ModerateHandbookPage
- Purpose: Next.js page for
/moderate/handbook(signed-in staff handbook). HTML/moderate/handbookis the handbook page, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundModerateHandbookScreen. Hub is/moderate. - Inputs: None.
- Returns / side effects: The handbook screen inside fill AppShell.
- Used by: Route
/moderate/handbook.
Function: ModerateHandbookScreen
- Purpose: Client staff handbook of how 21.gifts works. Staff (
roleAtLeast(..., 'moderator')) see TOC Chapters and three chapters 21.gifts login (#login), Verified (#verified), Official funding program (#funding), each with a permalink andHandbookCopyLinktone="app". Non-staff signed-in visitors see the heading plus forbidden copy and no chapters. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. No fetch. On mount and hashchange, scrolls the matching chapter into view when the hash is#login,#verified, or#funding. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. No network. - Used by:
ModerateHandbookPage.
Function: HiddenNotesPage
- Purpose: Next.js page for
/moderate/hidden(signed-in hidden-notes list for moderators). HTML/moderate/hiddenis the hidden-notes page, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundHiddenNotesScreen. Hidden HTTP is under/forum/messages/hidden(noroute.tsbeside this page). - Inputs: None.
- Returns / side effects: The hidden-notes screen inside fill AppShell.
- Used by: Route
/moderate/hidden.
Function: HiddenNotesScreen
- Purpose: Client list of hidden living-room notes. Staff (moderator) fetch
listHiddenMessagesand show the lead copy plus the newest-hidden-first list (a non-interactive External badge next to the name when the row has aviavalue) (or empty / loading / try-again). A 21.gifts author name is aLinkto/members/:accountId. The time is aLinkto/messages/:id. An external name stays text inside the note link. The note text sits outside that link inTranslatableNoteBody(Languages Translate when the text differs from the UI locale). Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. No un-hide control.
- Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /forum/messages/hiddenonly when the role is at least moderator. - Used by:
HiddenNotesPage.
Function: PayoutsPage
- Purpose: Next.js page for
/moderate/payouts(signed-in staff payout-per-person table). HTML/moderate/payoutsis the table, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundFundingPayoutsScreen. JSON lives under/funding/payout-daysbecause Next.js forbids aroute.tsbeside this page. Hub is/moderate. - Inputs: None.
- Returns / side effects: The payout table inside fill AppShell.
- Used by: Route
/moderate/payouts.
Function: FundingPayoutsScreen
- Purpose: Client table of daily-grant payouts for seven UTC days. Staff (moderator) fetch
fetchFundingPayoutDaysand show a lead, a four-color legend, and name plus seven cells (black not entitled, white entitled but not collected, green payout received, amber welcome gift; split green/amber when both were paid the same day). Today is the rightmost column. A row withaccountIdlinks the name to/members/{id}. Empty, Loading…, and error plus Try again are separate. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. Moderator stipends are not in this table. Welcome gifts are in the table. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/payout-daysonly when the role is at least moderator. - Used by:
PayoutsPage.
Function: ShopActivityPage
- Purpose: Next.js page for
/moderate/shops(signed-in staff per-shop activity table). HTML/moderate/shopsis the table, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundShopActivityShopsScreen. JSON lives under/shops/activity/shops, the api path. Hub is/moderate. - Inputs: None.
- Returns / side effects: The shop table inside fill AppShell.
- Used by: Route
/moderate/shops.
Function: ShopActivityShopsScreen
- Purpose: Client table of POS activity per shop. Staff (moderator) fetch
fetchShopActivityShopsand show a lead and one row per shop in the api order: shop name (link to/{npub}when set, otherwise text; an empty name reads Unnamed), till account (@username, otherwise the account id), active days asN / windowDays, and the last charge day as a medium localized UTC date or Never. A shop withactiveDays0 shows its active days and Inactive in the danger color. Empty, Loading…, and error plus Try again are separate. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch; an api 403 shows the same forbidden copy. A session change, or losing the moderator rank, drops the loaded table, and a loaded result is shown only for the session that loaded it; a change between staff roles keeps it, because every staff role gets the same list. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /shops/activity/shopsonly when the role is at least moderator. - Used by:
ShopActivityPage.
Function: ProposalsPage
- Purpose: Next.js page for
/moderate/proposals(signed-in staff confirm/reject queue). HTML/moderate/proposalsis the queue, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundProposalsScreen. Proposal HTTP lives under/trust/proposalsbecause Next.js forbids aroute.tsbeside this page. Hub is/moderate. - Inputs: None.
- Returns / side effects: The open-proposals screen inside fill AppShell.
- Used by: Route
/moderate/proposals.
Function: ProposalsScreen
- Purpose: Client confirm/reject queue of open moderator proposals. Staff (moderator) fetch
fetchTrustProposalsand show subject name, Proposed by {name}, time, Reject on every open row (postTrustReject, including a self-proposal), and Confirm as moderator (postTrustConfirm) or Waiting for another moderator to confirm. whenproposedBy.id === account.id. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. A failed confirm or reject showstrustChain.actionFailed. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /trust/proposalsonly when the role is at least moderator. Confirm postsPOST /trust/confirm-moderator; reject postsPOST /trust/reject-moderator. While either POST is in flight, Confirm and Reject are disabled and Loader2 sits on the pressed action. - Used by:
ProposalsPage.
Function: FundingApplicationsPage
- Purpose: Next.js page for
/grants/applications(signed-in staff grant-application queue). HTML/grants/applicationsis the queue, not a GET proxy./moderate/applicationsredirects there. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundFundingApplicationsScreen. Application HTTP lives under/funding/applicationsbecause Next.js forbids aroute.tsbeside this page. - Inputs: None.
- Returns / side effects: The open-applications screen inside fill AppShell.
- Used by: Route
/grants/applications./moderate/applicationsredirects here.
Function: FundingApplicationsScreen
- Purpose: Client queue of open 21 gifts grant applications. Staff (at least moderator) fetch
fetchFundingApplicationsand show applicant name (link/grants/applications/{id}), applied time, empty / Loading… / error+Try again. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/applicationsonly when the role is at least moderator. - Used by:
FundingApplicationsPage.
Function: FundingApplicationDetailPage
- Purpose: Next.js page for
/grants/applications/[accountId](signed-in staff grant-application review). HTML page, not a GET proxy./moderate/applications/[accountId]redirects there. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundFundingApplicationDetailScreen. Application HTTP lives under/funding/applications/:accountId. - Inputs: Dynamic
accountId. - Returns / side effects: The application-detail screen inside fill AppShell.
- Used by: Route
/grants/applications/[accountId]. The moderate path redirects here.
Function: FundingApplicationDetailScreen
- Purpose: Client staff review of one grant application. Staff fetch
fetchFundingApplicationand answer two questions against living-room posts (no replies; post text usesTranslatableNoteBody, the applicant name stays plain; each post keeps its own time; there is no application time under the name). The first isfunding.review.question.staff, with an About link to/about. Yes showsfunding.review.truth. Yes there postspostFundingAdmit. No on either question postspostFundingRejectwhile the grant ispendingortrial. A failed decision showstrustChain.actionFailed. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. While a POST is in flight, visible decide buttons are disabled and show the Loader2 spinner. - Inputs:
accountId; session and account fromuseAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/applications/:accountIdonly when the role is at least moderator. Decide buttons only whengrant.statusispendingortrial. Successful Admit / Reject leaves the buttons disabled and returns to/grants/applicationswithreturnToView(a step back when the queue opened this page, otherwise a replace). When Admit throwsFUNDING_PLACES_FULL_ERROR, the alert is All places of this round are taken. Nobody else can be admitted until the next round opens. (funding.detail.placesFull) instead oftrustChain.actionFailed, and the member stays on the page. A decision answer for an application that is no longer on screen (anotheraccountId) is dropped: no navigation and no alert. Switching applications clears the shown detail and returns to the first question. The buttons stay locked while a decision for that same person is still in flight anywhere in this tab (a module-level set shared by every open detail screen), also after leaving, reopening, or deciding another person meanwhile; when that decision settles, another screen showing the person unlocks and reloads the application. An unmounted screen neither navigates nor alerts. A session reload of the same application still applies the answer. - Used by:
FundingApplicationDetailPage.
Function: SecurityPage
- Purpose: Next.js page for
/security, Account security, opened from its Menu row. - Inputs: None.
- Returns / side effects: Fill
AppShellwithProfileChromeLeftandSignedInChrome,OnboardingGate screen="profile"(name, username, and rules agreement, like/settings), thenSecurityScreen. - Used by: Route
/security.
Function: SecurityScreen
- Purpose: Signed-in
/securitybody: securing the account, the shares kept for others, and the recovery phrase and previous wallets, for members who are not technical. - Inputs:
sessionandaccountfromuseAuthStore(sparkWalletVerified,socialRecoverySetUp,passkeyCredentialId). - Returns / side effects:
nullwithout a session or before the account has loaded. Otherwise aCard surface={false}with h1 Account security (nav.security) and threesections, each labelled by an h2 in the section ramp and separated by a rule. Protect my account (security.protect, idprotect): without a verified wallet (sparkWalletVerified !== true) the muted Available once your wallet is connected. (socialRecovery.statusNoWallet) and no link; with one, Set up for this wallet. (socialRecovery.statusOn) whensocialRecoverySetUpis true, else Not set up yet. Two people you trust can help you get your account back. (socialRecovery.statusOff, also for an older api without the field), and aButtonLink size="lg"Secure my account (socialRecovery.secure) to/settings/social-recovery, primary while not set up and secondary once it is. Help someone else (security.help, idhelp-others): the mutedsecurity.helpBodyand a secondary Shares I keep for others (socialRecovery.heldLink) to/settings/held-shares. More options (security.more, idmore): with a non-emptypasskeyCredentialIda secondary Recovery phrase (settings.recoveryPhrase), otherwise the mutedwallet.addPhraseHintand a primary Add recovery phrase (wallet.addPhrase), both to/wallet/phrase; thenPreviousWalletsRow. All are client-side links. No request of its own and no passkey prompt. - Used by:
SecurityPage.
Function: SettingsPage
- Purpose: Next.js page for
/settings, the signed-in settings opened from the Settings Menu row. - Inputs: None.
- Returns / side effects: Fill
AppShellwithProfileChromeLeftandSignedInChrome,OnboardingGate screen="profile"(name, username, and rules agreement), thenSettingsScreen. - Used by: Route
/settings.
Function: SettingsScreen
- Purpose: Signed-in
/settingsbody: the home of the member's preferences and account actions. Profile keeps identity only. - Inputs:
sessionandaccountfromuseAuthStore(username,amountUnit), the preferred fiat fromuseFiatPreference,getAppVersion(), and the page host for the address. - Returns / side effects:
nullwithout a session or before the account has loaded. Otherwise aCard surface={false}with h1 Settings (settings.heading) and fivesections, each labelled by an h2 in the section ramp and separated by a rule: Wallet (wallet.title, idwallet): 21.gifts address (idaddress):giftsLightningAddressinfont-monowith an icon-only ghost Copy (wallet.payment.copyValue;Checkintext-app-successand a politesr-onlyCopied for two seconds), or, while no username is set, Set a username first. andUsernameForm variant="overlay"in place, and then Default amount (settings.defaultAmount): a neutralSegmentedControl₿ / the preferred fiat code bound toaccount.amountUnitthat saves throughsaveAmountUnit, with the muted hintsettings.defaultAmountHint, then Heart amount (settings.heartAmount), which saves the amount sent by a heart, and, while the in-app wallet isready(or a pindfx-login,dfx-login-busyordfx-login-erroris set), Log in at DFX (settings.dfxLogin) with the muted hintsettings.dfxLoginHint: a press opens a new tab and clears that tab'sopenerright after it opens, before any wait, then callsdfxLoginUrland, unless the member has closed the tab, sends it to the DFX Buy page; whetherdfxLoginUrlanswers or fails, a tab the member closed during the wait is left alone and no alert is shown; while it runs the button is disabled and a busy line showssettings.dfxLoginBusy, a blocked tab opens nothing, does not calldfxLoginUrl, and showssettings.dfxLoginErrorin arole="alert", and a failure or the 15-second limit while the tab remains open closes that tab and shows the same alert. Leaving the page during the wait closes the tab when the sign-in settles, without navigation or an alert. Display (settings.display):LanguagePreferenceSwitcher,ThemeSwitcher,FiatPreferenceSwitcher,NumberFormatSwitcher. Notifications (profile.push.heading, idnotifications):PushToggle. Account (settings.account):LogoutButton. About & legal (settings.about):next/linkrows Handbook, Legal & Privacy, Terms of Use, Living room rules, Contact, then the muted version line (app.version). When the address has a hash naming one of those ids, that part scrolls into view once the card renders. Securing the account lives on/security(SecurityScreen). No passkey prompt on this page. - Used by:
SettingsPage.
Function: PreviousWalletsRow
- Purpose: The wallets the signed-in account used before a social recovery, in More options on
/security(idprevious-wallets). It informs and links only: it never removes a wallet, because the explorer balance can lag behind the wallet; removal happens on the previous wallet's own page after a synced read of 0. - Inputs:
usePreviousWallets(); the UI locale (dates), the number format, the preferred fiat, anduseSpotRate(read only while some wallet shows a positive balance). - Returns / side effects:
nullwhile loading and for an empty list, so accounts without previous wallets see no change. A failed read: the overline Previous wallets (previousWallets.heading),p[role=alert]Previous wallets could not be loaded. (previousWallets.loadError), and a secondary Try again (login.retry) that callsretry. Otherwise the overline and one card per wallet (rounded-lg border p-3): Replaced on {date} (previousWallets.replaced, a medium date in the UI language), the explorer balance (Balance unknown fornull, Empty for 0, elseformatBitcoinwith the current spot in the member's fiat after·, or bitcoin alone while the spot is not loaded), and a secondaryButtonLink size="md"Transfer remaining balance (previousWallets.transfer) to/settings/previous-wallets/<key>. No key or address is shown. When the row first shows and the address hash is#previous-wallets, it scrolls itself into view (scrollIntoView({ block: 'start' })) once per mount, because this row loads after the screen has rendered. - Used by:
SecurityScreen.
Function: usePreviousWallets
- Purpose: Reads the previous wallets of the signed-in account once per mount (
fetchPreviousWallets,GET /me/previous-wallets). - Inputs:
sessionandaccount.sparkWalletVerifiedfromuseAuthStore. - Returns / side effects:
{ status: 'loading' | 'ready' | 'error', wallets, retry }. Only an account with a verified wallet can have previous wallets (a recovery keeps the wallet verified), so without one, or without a session, nothing is read and the result isreadyand empty; an api that does not mount the route (no LNURL server) then shows no load error either.walletsis empty unlessready.retryreads again (loadinguntil it settles). A new session reads again and never shows the list of the old one. An answer after unmount, or of a read that a newer one replaced, is dropped. Nothing here removes a wallet. - Used by:
PreviousWalletsRow.
Function: HeldSharesPage
- Purpose: Next.js page for
/settings/held-shares: the shares the signed-in member keeps for other members' Social Recovery, opened from Shares I keep for others on/security. - Inputs: None.
- Returns / side effects: Fill
AppShellwithProfileChromeLeftandSignedInChrome,OnboardingGate screen="profile"(name, username, and rules agreement, like/settings), thenHeldSharesScreen. - Used by: Route
/settings/held-shares.
Function: HeldSharesScreen
- Purpose: Body of
/settings/held-shares, the holder side of Social Recovery: the shares the signed-in member keeps for others in encrypted boxes on the api (useHeldShares). A share reaches the api only encrypted. - Inputs:
useHeldShares(), the signed-in account fromuseAuthStore, and the UI locale. - Returns / side effects:
nullbefore the account has loaded. Every list step is aCard surface={false}with h1 Shares I keep for others (heldShares.title) and the intro (heldShares.intro). Opening:BusyLineheldShares.opening. Unlock: the mutedheldShares.unlockHint, the alert of a failed prompt in the recovery phrase's wording (wallet.prfUnsupported,wallet.timeout, orwallet.errorGeneric), and the primaryButton size="lg"Open my shares (heldShares.unlock, disabled with a spinner while the prompt runs). Load error: the alertheldShares.loadErrorand Try again (login.retry). List: the notice of the last scan or delete (You now keep a share for @username. asrole="status", or arole="alert"withshareCode.invalid,heldShares.own,heldShares.duplicatenaming the owner,heldShares.saveError,heldShares.deleteError, orheldShares.lockedDeleteErrorfor the boxes that do not open), the primaryButton size="lg"Keep a share (heldShares.keep;BusyLineheldShares.savingin its place while a share is kept), then You keep no shares for others yet. (heldShares.empty) or a list: one card per share with@username(heldShares.owner) and icon-only ghostIconButtons Show code for @username (lucideQrCode,heldShares.show) and Delete share of @username (lucideTrash2intext-app-danger,heldShares.delete), then, when boxes do not open with the current words, one muted rowheldShares.lockedOneorheldShares.lockedManywith the icon-only Delete the shares that cannot be opened (heldShares.deleteLocked). Each trash opensInlineConfirm(heldShares.deleteConfirmorheldShares.deleteLockedConfirm, checkheldShares.deleteYes, XheldShares.deleteNo) and is hidden while it is open. Scan: an sr-only h1 and the full-port camera layer of the wallet Send view (section[data-port-fill],absolute inset-0 … bg-black, named Keep a share) holdingQrScannerwithcopyheldShares.scanHint,heldShares.cameraDenied, andheldShares.cameraUnavailable. Code: an sr-only h1, h2 Share of @username (heldShares.qrTitle),heldShares.qrBody, andQrCodeof the payload labelled Share code (heldShares.qrLabel, no logo). The one top-left arrow (AppShellTopLeftwithProfileChromeLeft onBackClick) steps from the camera or a code back to the list, otherwise it leaves. - Used by:
HeldSharesPage.
Function: useHeldShares
- Purpose: State and actions of
/settings/held-sharesfor the signed-in member, whoseaccount.idis the holder id. The shares live in encrypted boxes on the api under the member's login; the hook keeps only the box key of the member's words, and only for the account it was derived for (the words themselves sit in tab memory while the wallet is open in this tab, which the Open my shares passkey prompt also does, until the tab closes or a sign-out, sign-in or recovery clears them): another account signed in on this tab starts from an empty list (list view, no notice, no open confirm) and looks its own words up again, and a key, read, keep, delete, or passkey prompt that answers for the previous account changes nothing (the prompt's words are still hidden, and its error is not shown); a key derivation overtaken by a newer one neither reads nor shows an error. A box deleted on the page stays out of, and a share kept on the page is added to, a read that was already running. One keep or delete runs at a time: a scan,onScanResult,remove, orremoveLockedasked while a keep, a delete of one share, or the delete of the boxes that do not open runs does nothing. - Inputs:
sessionandaccount.idfromuseAuthStore; the words from tab memory (settlePhraseDerivations, thenpeekSessionPhrase) or fromuseWalletPhrase(showPhrase, the passkey prompt of Show recovery phrase, thenhidePhrase); usesheldShareBoxKey,loadHeldShares,keepHeldShare,deleteHeldShareBox, andparseShareCode. - Returns / side effects:
{ load, unlocking, unlockError, shares, lockedCount, saving, view, notice, confirmDelete, confirmDeleteLocked, unlock, reload, scan, onScanResult, showQr, askDelete, remove, askDeleteLocked, removeLocked, cancel, back }.loadisopening(words looked up or boxes read),unlock(no words in tab memory:unlock()asks for the passkey,unlockingandunlockErrormirror that prompt),loadError(words that give no key or boxes that cannot be read;reload()tries again), orready.sharesare sorted by owner username;lockedCountcounts the boxes that do not open with the current words, which are never deleted on their own.viewislist,scan, or{ qr: share }.scan()(only whenreadyand no keep or delete runs) clears the notice and pending confirms and opens the camera.onScanResult(text)returns to the list, setssaving, and keeps the share (keepHeldShare: the box that already holds the code, otherwise a new box):storedwith the owner's username, or the refusalinvalid,own,duplicate(that owner and set among the opened boxes), orsaveError, with the username when the payload was readable.showQr(share)opens its code.askDelete(share)setsconfirmDeleteto its box id,askDeleteLocked()setsconfirmDeleteLocked,cancel()clears both.remove(share)deletes its box and drops it from the list, or givesdeleteErrorand keeps it.removeLocked()deletes every box that does not open; the ones the api did not delete stay counted withlockedDeleteError.back()returnstrueafter stepping from the camera or a code to the list, andfalseon the list. Without a session or account nothing is read and the actions do nothing. - Used by:
HeldSharesScreen.
Function: SocialRecoveryPage
- Purpose: Next.js page for
/settings/social-recovery, Secure my account: the owner gives two people a Social Recovery share each and 21.gifts keeps the third. Opened from Protect my account on/security, the done step of/recover, and the grant prompt on/welcome. - Inputs: None.
- Returns / side effects: Fill
AppShellwithProfileChromeLeftandSignedInChrome,OnboardingGate screen="profile"(name, username, and rules agreement, like/settings), thenSocialRecoveryScreen. - Used by: Route
/settings/social-recovery.
Function: SocialRecoveryScreen
- Purpose: Body of
/settings/social-recovery, the owner side of Social Recovery: the steps ofuseSocialRecoverySetupunder one page title. - Inputs:
useSocialRecoverySetup(), the signed-in account fromuseAuthStore(socialRecoverySetUpfor the renew note), and the client-side router. - Returns / side effects:
nullbefore the account has loaded. Otherwise aCard surface={false}with h1 Secure my account (secure.title) and one step. Intro: the mutedsecure.introBody, the warningsecure.introWarninginfont-medium text-app-fg,secure.introAccounts,secure.introRemote, andsecure.introRenewonly whensocialRecoverySetUpis true, then a primaryButton size="lg"Continue (secure.start); while checking, aBusyLinewith Checking your wallet… (secure.checking) stands in its place. Person 1 / Person 2: h2secure.shareHeading,secure.shareBody, on person 2 alsosecure.shareDifferent, theQrCodeof that person's payload labelledsecure.shareQr(no logo), a primaryButton size="lg"Person {n} has scanned it (secure.scanned), and under the mutedsecure.refusedHinta secondaryButton size="lg"Start again with new codes (secure.resplit). Saving: theBusyLineSaving the 21.gifts backup… (secure.saving). Done: h2secure.doneTitle,secure.doneBody, and a primaryButton size="lg"Done (secure.done) that callsreturnToView('/security', router). An error replaces the step withp[role=alert](secure.walletMismatch,wallet.balanceError,secure.saveError, orsecure.walletChanged) and, except for the mismatch, Try again (login.retry) callingretry. The one top-left arrow (AppShellTopLeftwithProfileChromeLeft onBackClick) runsback: person 2 to person 1, person 1 to the intro, otherwise it leaves. - Used by:
SocialRecoveryPage.
Function: useSocialRecoverySetup
- Purpose: State and actions of Secure my account for the signed-in owner. The 12 words and the shares live only in this component's memory and are dropped when the page is left; only 21.gifts' share reaches the api. There is no passkey prompt: the words come from the open wallet in tab memory.
- Inputs:
peekSessionPhrase,ensureWalletConnected, and the session and account fromuseAuthStore(id,username,sparkPubkey,sparkWalletVerified); usessplitPhrase,encodeShareCode, andputRecoveryShare. In a Playwright build only (visualPin),?visual=sr-checking,sr-share-1,sr-share-2,sr-done,sr-mismatch, andsr-save-erroropen that step with a fixed split of the public BIP-39 test phrase of 16 zero bytes; a deployed build ignores them. - Returns / side effects:
{ step, error, codes, identifier, start, scanned, resplit, retry, back }.stepisintro,checking,share1,share2,saving, ordone.start()(Continue) reads the tab phrase (none → errorwallet), awaitsensureWalletConnected(a throw →wallet), and stops withmismatchunless the account'ssparkWalletVerifiedis true and itssparkPubkeyequals the wallet key in lower case; then it splits the words (splitPhrasechecks every pair) and builds the payloads of shares 1 and 2 for the account's id and username (a failure →wallet), and lands onshare1withcodesand the set'sidentifier.scanned()movesshare1toshare2, and onshare2uploads share 3 (PUT /me/recovery-sharewith the key checked bystart): success stores the returned account (setAccount, only for the same session) and givesdone;RecoveryErrorkey_in_use(409) giveschangedand drops the words; any other failure givessaveand keeps share 3.resplit()splits the same words again into a new set and shows person 1's new code.retry()runsstartafterwallet, the same upload aftersave, and returns to the intro afterchanged; it does nothing aftermismatch.back()returnstrueafter steppingshare2→share1orshare1→ intro (which drops the words and codes), andfalseon any other step or error, so the arrow leaves. An answer of a superseded step or after unmount is dropped, except that a stored share still updates the account of the same session; leaving the page drops the words and shares. - Used by:
SocialRecoveryScreen.
Function: RecoverPage
- Purpose: Next.js page for
/recover, the signed-out social recovery of an account whose passkey is lost, opened from Recover account via Social Recovery on the/logincard: the quiet link on its idle view, or the secondary control on a login problem. - Inputs: None.
- Returns / side effects: Fill
AppShellwithalign="center",ProfileChromeLeftwithHomeWordmark, and the lightLanguageSwitcher(the/loginchrome), thenRecoverScreen. Not behindOnboardingGate: its login gate would leave the page once the recovered account signs in, before the balance moved. - Used by: Route
/recover.
Function: RecoverScreen
- Purpose: Body of
/recover: the views ofuseRecoveryFlowunder one title, Recover your account (recover.title, the h1 of every view;sr-onlyover the camera). - Inputs:
useRecoveryFlow()and the client-side router. - Returns / side effects: A
Card surface={false}with one view, or, forscan, the camera layer ofOldWordsInput. start:recover.intro, a primary Scan two codes (recover.scan) and a secondary Type my 12 words (recover.type). type:OldWordsInput mode="type". opening: aBusyLinewithrecover.opening, orrecover.openingWaitwhilewaiting. blocked:LoginBlockedNotice; undercloseda primary Try again (login.retry,resume) and a secondary Start over (recover.again), because the view outlives the page;outdatedis the notice without Reload (reload={false}), since only the login card and the profile claim may reload the document. refused:p[role=alert]withrecover.notFound,recover.alreadyDone(plus a primary Log in,login.submit, which drops the recovery and callsreturnToView('/login', router)),recover.operator,shareCode.otherAccount, orrecover.noWallet, then a secondary Start over (recover.again). retry:recover.unavailableorwallet.balanceError, a primary Try again (login.retry), and Start over. found: h2recover.found,recover.restartafter a restart,recover.foundBody, the alert of the last try (view.claimError,wallet.timeout,wallet.prfUnsupported, orwallet.balanceError), and a primary Create new passkey (recover.createPasskey), disabled with a spinner while busy. transfer: h2recover.transferTitle,recover.transferBody, anolof Account (recover.stepAccount), 21.gifts address (profile.giftsHeading), and Balance (wallet.balanceHeading), each with aCheckimage namedrecover.stepDonewhen done, the status linerecover.transferWaitwhile waiting, the alertrecover.transferErrororrecover.balanceError, a primary Transfer (recover.transfer, disabled with a spinner while busy), and aftergenerica secondary Start over, afterbalancea secondary Move the balance later (recover.balanceLater). done:DoneStepwithview.balanceMissing. The one top-left arrow (AppShellTopLeftwithProfileChromeLeftandHomeWordmark) first steps from the warning ofDoneStepback to that step, otherwise runsback: from the camera or the words field to the start, otherwise it leaves. - Used by:
RecoverPage.
Function: DoneStep
- Purpose: The end of
/recover, a private step ofRecoverScreen: the account is back, why two people must be chosen again, and what to do about the old shares, in words for members who are not technical. It names neither a passkey nor the 12 words. - Inputs:
balanceMissing: some balance stayed in the previous wallet.warning: the warning shows.onWarn: called by Not now. - Returns / side effects: h2
recover.doneTitle,recover.doneBody,recover.doneSharesinfont-medium text-app-fg, thenrecover.balanceMissingwhen a balance stayed, otherwiserecover.doneDeleteOld, because moving a leftover balance can still need the old shares; a primaryButtonLinkSecure my account (socialRecovery.secure) to/settings/social-recoveryand a secondaryButtonNot now (recover.later). Not now callsonWarn, andwarningreplaces the step on the same page with h2 Continue without protection? (recover.laterTitle),recover.laterBody, a primary Secure my account, and a secondaryButtonLinkContinue anyway (recover.laterContinue) to/welcome.RecoverScreenholds that state, so the top-left arrow steps from the warning back to the done step. - Used by:
RecoverScreen.
Function: OldWordsInput
- Purpose: Reads the old 12 words of a wallet, for a social recovery on
/recoveror a previous wallet on/settings/previous-wallets/[sparkPubkey]: two share codes scanned, or the words typed. They stay in component memory and are handed over once. - Inputs:
mode(scanortype),onWords(words, ownerAccountId), and optionalexpectedOwnerAccountId. - Returns / side effects: scan: a
sectionnamed Scan two codes withdata-port-fillthat fills its positioned parent (the camera layer of the wallet Send view), holdingQrScannerwith Scan code {n} of 2 (recover.scanHint,hintVars) and therecover.cameraDenied/recover.cameraUnavailablealerts. Each code goes throughparseShareCode. After the first, the camera stops, and a check mark, Code 1 of 2 scanned (@username). (recover.scanFirstDone,role="status"), Now ask the second person to show you their code. (recover.scanNextPerson), and a whiteButton tone="dark" size="lg"Scan the second code (recover.scanSecond) stand centred on the black layer. That button starts the scanner again for the second, so the first code, often still in front of the camera, is not read again as the second; while it runs, the scanned line stays at the bottom. Then the two are combined withphraseFromShareCodes, and the words go toonWordswith the owner they name. A text that is not a share code (shareCode.invalid), the same code twice (Slip39Errormembers,shareCode.same), codes of different setups or that do not combine (shareCode.otherSet), or a code of an account other thanexpectedOwnerAccountId(shareCode.otherAccount) stops the camera and shows its alert in white over the black layer with anoverlayTry again that starts the camera again. type: aformwith a multilineFieldYour 12 words (no autocomplete, autocorrect, or spellcheck), the hintrecover.wordsHint(itsaria-describedby), and Continue (recover.wordsSubmit); the words are trimmed, lower-cased, and single-spaced, and anything but 12 valid BIP-39 words showsrecover.wordsInvalid(aria-invalid) until the field changes; valid words go toonWordswith ownernull. Nothing is handed over after unmount. - Used by:
RecoverScreenandRemainingBalanceScreen.
Function: useRecoveryFlow
- Purpose: State and actions of
/recover: the view ofuseRecoveryStoreand the presses that drive the recovery flow. - Inputs:
useRecoveryStore, the recovery-flow functions, and, in a Playwright build only (visualPin), the?visual=pinsrecover-opening,recover-opening-wait,recover-blocked-closed,recover-blocked-outdated,recover-not-found,recover-done,recover-operator,recover-other-account,recover-unavailable,recover-wallet-error,recover-found,recover-found-busy,recover-restart,recover-cancelled,recover-timeout,recover-prf,recover-new-wallet-error,recover-transfer,recover-transfer-busy,recover-transfer-progress,recover-transfer-error,recover-balance-error,recover-complete, andrecover-complete-missing, each a fixture view for@ada; a deployed build ignores them. - Returns / side effects:
{ view, scan, type, onWords, retry, resume, createPasskey, transfer, balanceLater, startOver, back }.scanandtypeshow those steps;onWordscallsrememberOldWords;retrycallsopenAndBegin;resumecallsresumeRecovery;createPasskeycallscreateNewPasskey;transfercallstransfer;balanceLatercallsfinishWithoutBalance;startOvercallsresetRecovery.back()returnstrueafter stepping fromscanortypetostart, otherwisefalse, so the arrow leaves. The recovery stays in memory when the page closes, also onblocked, so coming back resumes it; leaving the done step callsresetRecovery. - Used by:
RecoverScreen.
Function: useRecoveryStore
- Purpose: Zustand store of the view on
/recover, outside React, so a later visit to the page in this tab resumes the recovery. It holds the view only; the words, PRF bytes, and wallet connections stay in the recovery flow module's memory. - Inputs: Hook. Action
setView(view). - Returns / side effects:
{ view, setView }.view(RecoveryView) isstart,scan,type,opening(waiting),blocked(closed/outdated),refused(not_found,done,operator,otherAccount,noWallet),retry(unavailable/wallet),found(username,restart,error:cancelled,prf,timeout,wallet, ornull;busy),transfer(doneofaccount,address,signedIn,balance;busy;waiting;error:generic,balance, ornull), ordone(balanceMissing). Starts atstart. - Used by:
useRecoveryFlowand the recovery flow (rememberOldWords,openAndBegin,createNewPasskey,transfer,finishWithoutBalance,resumeRecovery,resetRecovery).
Function: defaultRecoveryDeps
- Purpose: The real effects of a social recovery, each replaceable in tests (
RecoveryDeps). - Inputs: None.
- Returns / side effects:
{ loadSdk, apiKey, host, now, sleep, randomUUID, createCredential, getCredential }:loadWalletSdk,getBreezApiKey(nulldisables the recovery),appHost,Date.now, asetTimeoutpause,crypto.randomUUID, andnavigator.credentials.create/get. - Used by:
rememberOldWordsandopenPreviousWallet(their defaultdeps).
Function: openWordsWallet
- Purpose: Opens a wallet from its 12 words beside the member's own wallet (the SDK keeps each wallet's state apart by its key), for the old and new wallets of a social recovery and for a previous wallet.
- Inputs: The started
WalletSdk, the words, the Breez API key, anddeps(host,sleep). - Returns / side effects:
{ connection, balanceSats }afterconnect(words, apiKey, host)and a syncedgetInfo({ ensureSynced: true }), both withinWALLET_CONNECT_TIMEOUT_MS(30 s, the same deadline as the member's own wallet). A failed synced read closes the connection and rejects. At the deadline it rejects withwallet-connect-timeout, and a connection that opens later is closed (a later failure is ignored). Closing is best effort. - Used by:
openAndBegin(the old wallet),createNewPasskeyandtransfer(the new wallet, and opening it again for a later address claim), andopenPreviousWallet.
Function: rememberOldWords
- Purpose: Starts a social recovery on
/recoverwith the old 12 words, typed or rebuilt from two share codes. The words stay in the module's memory only, never in the tab phrase. - Inputs:
words,ownerAccountId(named in the scanned codes, ornullfor typed words), and optionaldeps(defaultRecoveryDeps()by default). - Returns / side effects: Replaces a recovery already in progress in this tab (its wallets are closed in the background) and runs
openAndBegin. Resolves when the view shows the result. - Used by:
useRecoveryFlow(onWords, fromOldWordsInput).
Function: openAndBegin
- Purpose: Opens the old wallet, unless it is open, and finds its account, the app side of the concept's rule that the app asks again after the forward window.
- Inputs: The recovery in progress (none → no-op; a found account → no-op).
- Returns / side effects: Without a wallet in this build (
apiKeynull) the view isrefusednoWalletand no wallet code loads. Otherwiseopening; the old wallet's key is worked out offline (identityPubkey), the wallet connects withopenWordsWallet(which also lets the SDK look up the address it holds), and a failure isretrywallet. Each begin signs a fresh lookup (signAddressLookupwith the app host and the current second; a signing failure isretrywallet) and callsstartPasskeyRecovery. While it answersunavailablethe view isopeningwithwaiting, the flow waitsRECOVERY_SETTLE_WAIT_MS(31 s), and asks again, up toRECOVERY_BEGIN_TRIES(3) calls; thenretryunavailable.not_found,done, andoperatorarerefused;LoginsClosedErrorandAppOutdatedErrorareblocked;WrongAccountErrorisrefusedoperator; any other failure isretryunavailable. An account other than the scanned codes' owner isrefusedotherAccount; otherwise the begin is kept and the view isfoundwith the account's username. Results of a recovery that was replaced meanwhile are dropped, and a wallet that opens after that is closed. - Used by:
rememberOldWords, Try again onretry(useRecoveryFlow), andresumeRecovery.
Function: createNewPasskey
- Purpose: Create new passkey on
found(a user gesture): makes the new passkey and its wallet. - Inputs: The recovery in progress; no-op unless
foundis shown, idle, with an open old wallet and a begin. - Returns / side effects:
foundturns busy. The begin's creation options (creationOptionsFromJSON) get the PRF request (mergePrfExtension) and go tocreateCredential, timed aswallet.passkeywithprompt: recovery. No credential, a dismissed or failed prompt isfounderrorcancelled, a prompt that timed outtimeout(classifyWebAuthnError), and no PRF output (obtainPrfFirstnullunder the begin'srp.id, also when the confirming get() differs from create())prf. The 12 words come frommnemonicFromPrfFirst(neverrememberSessionPhrase), the wallet opens withopenWordsWallet, and its key (identityPubkey) and Spark address (receiveSparkAddress) are read; any failure there closes a half-open wallet and isfounderrorwallet, and nothing of the attempt is kept. Only then are the connection, words, PRF bytes, credential JSON (credentialToJSON, without PRF), credential id, key, and address kept together, with nothing of the move done, and the view istransfer. - Used by:
useRecoveryFlow(createPasskey).
Function: transfer
- Purpose: Transfer on
transfer: one press moves the account to the new passkey and wallet, resuming at the first part not done. - Inputs: The recovery in progress; no-op unless
transferis shown and idle with an attempt. - Returns / side effects: The view is busy throughout. Account: the old wallet signs
recoveryMessage(account id, the begin's challenge, the new credential id, the new key) withsignMessage; a failure or another key ends the press withgeneric.finishPasskeyRecoverystores the pending recovery;RecoveryErrorchallenge(the account did not move) begins again at once, which on a new begin restarts the attempt (foundwithrestart, the new wallet closed, every part of the attempt dropped); any other refusal ends the press (generic, orblocked/refused). Address: when the old wallet holds an address (hasAddress), it authorizes the move (authorizeAddressTransfer) and the new wallet (opened again if the sign-in closed it) claims it, timed aswallet.address.transfer; the moment the claim settled (resolved, threw, or was not needed) is kept, and a failure does not stop the press. Sign-in: the new wallet is closed, thenstartPasskeyAuthentication,getCredentiallimited to the new credential (wallet.passkey,prompt: recovery), andfinishPasskeyAuthentication, withoutsignalUnknownCredential. Success clears the tab phrase, startsrememberPhraseFromPrfwith the new PRF bytes, startsrelockHeldShareswith the old and the new words (the boxes the member keeps for others that open with the old words move to the new words; not awaited, and a failure never ends the press: the next words entered on a previous wallet's page try again), stores the session (setAuth), startsrefreshOwnerAccount(session.token)without awaiting it, logsloginandrecovery_done, and marks the account, address, and sign-in done.RecoveryPendingErrorwaits untilRECOVERY_SETTLE_WAIT_MSafter the claim settled and begins again;UnknownCredentialErrorbegins again at once. A begin again that answersdonesigns in once more (an unknown passkey then meansrefuseddone);operatorandnot_foundarerefused;unavailablethree times, a dismissed prompt, or another failure ends the press withgeneric. Balance: reads the old wallet's synced balance and sends all of it to the new Spark address (sendToSparkAddress,wallet.sendwithroute: spark). A send that throws keeps its idempotency key for the next press and is reported as a payment that did not go out (reportPaymentFailure: stagesend, methodspark, flowrecovery, the reason fromsdkFailureReason, the amount, under the session of the sign-in); after a send that went out the key is dropped and the balance read again; up toRECOVERY_SEND_TRIES(3) sends per press; any failure isbalance. A synced read of 0 closes the old wallet, drops every word and connection, and showsdone. - Used by:
useRecoveryFlow(transfer).
Function: finishWithoutBalance
- Purpose: Move the balance later after the
balanceerror: the account has moved and is signed in, so the recovery ends without the balance. - Inputs: The recovery in progress; no-op unless
transferwith errorbalanceis shown and idle. - Returns / side effects: Closes the old wallet, shows
donewithbalanceMissing, and drops every word and connection. The balance stays in the previous wallet, movable from/security. - Used by:
useRecoveryFlow(balanceLater).
Function: resumeRecovery
- Purpose: Try again under the closed-logins notice on
/recover: picks the recovery up where closed logins stopped it, so theblockedview, which outlives the page, never leaves the member stuck. - Inputs: The recovery in progress; no-op without one, and unless
blockedclosedis shown. - Returns / side effects: Before the account was found it runs
openAndBegin, which reuses an open old wallet and looks the account up again (closed logins show the notice again). During the move it showstransferwith the attempt's done parts and thegenericerror (recover.transferError, with Start over), so the next Transfer press resumes at the first part not done. With a begin but no new passkey yet it showsfoundfor the account. Resolves when the view shows the result. - Used by:
useRecoveryFlow(resume).
Function: resetRecovery
- Purpose: Start over, and leaving the done step: drops the recovery in progress.
- Inputs: None.
- Returns / side effects: Shows
startat once, drops the words, PRF bytes, begin, and attempt, and closes the old and new wallets (best effort). An answer of the dropped recovery that arrives later changes nothing. - Used by:
useRecoveryFlow(startOver, and the unmount of the done step), andRecoverScreen(Log in after a recovery done before).
Function: PreviousWalletPage
- Purpose: Next.js page for
/settings/previous-wallets/[sparkPubkey], Transfer remaining balance for one wallet the account used before a social recovery. - Inputs: Dynamic route
params(sparkPubkey). - Returns / side effects: Fill
AppShellwithProfileChromeLeftandSignedInChrome,OnboardingGate screen="profile"(like/settings), thenRemainingBalanceScreenfor that key. - Used by: Route
/settings/previous-wallets/[sparkPubkey].
Function: RemainingBalanceScreen
- Purpose: Body of the previous wallet's page: the steps of
useRemainingBalanceunder the title Transfer remaining balance. - Inputs:
sparkPubkey, the signed-in account (idfor the codes),useRemainingBalance,useSpotRate(while a balance shows),useFiatPreference, anduseNumberFormat. - Returns / side effects:
nullbefore the account and the list have loaded. Otherwise aCard surface={false}with h1remaining.title(sr-onlyover the camera) and one step: loadErrorpreviousWallets.loadErrorwith Try again; notFound the mutedremaining.notFoundwith nothing to press (the top-left arrow leaves); startremaining.intro, Scan two codes, Type my 12 words; scan / typeOldWordsInput(scan withexpectedOwnerAccountId= the account); openingBusyLinerecover.opening; mismatchremaining.mismatchand walletErrorwallet.balanceError, each with Try again; balance / sending the overlineremaining.balancewith ₿ and one fiat figure at the current spot (formatBitcoin,satsToFiatAmount,formatFiatDisplay), then Transfer (recover.transfer, disabled with a spinner while sending) above 0, or at 0remaining.emptyBody, the removal, and Done; error the balance,remaining.error, and Try again; doneremaining.done(role="status"), the removal, and Done. The removal is a secondary Remove previous wallet (previousWallets.remove), or the openInlineConfirm(previousWallets.removeConfirm, icon buttonspreviousWallets.removeYes/removeNo, busy spinner,previousWallets.removeError). The one top-left arrow runsback. No key or address is shown. - Used by:
PreviousWalletPage.
Function: useRemainingBalance
- Purpose: State and actions of Transfer remaining balance for one previous wallet of the signed-in account.
- Inputs:
sparkPubkey(lower-cased for the checks), the session fromuseAuthStore, and the client-side router. In a Playwright build only (visualPin),?visual=prev-opening,prev-mismatch,prev-balance,prev-empty,prev-sending,prev-error, andprev-doneopen that step (₿21'000, or 0) without reading the list or opening a wallet; a deployed build ignores them. - Returns / side effects:
{ step, balanceSats, removal, removable, reload, scan, type, onWords, retryOpen, transfer, askRemove, cancelRemove, confirmRemove, leave, back }. ReadsfetchPreviousWalletsonce per session andreload: the key not listed isnotFound, a failureloadError, otherwisestart.onWordsfirst startsrelockHeldShareswith the entered words and, once the running phrase derivations have settled (settlePhraseDerivations), the words of the open wallet in tab memory (ornullwhen there are none, which moves nothing; not awaited), then opens the wallet (openPreviousWallet):mismatch,walletError(the words stay forretryOpen, which opens again; aftermismatchit returns tostartand drops them), orbalancewith the synced balance.transfer(onbalanceorerror) runstransferRemainingBalancewith the session:done(balance 0) orerror.removableis true only with a synced read of 0 (balanceat 0, ordone); thenaskRemoveopens the confirm,cancelRemovecloses it, andconfirmRemovecallsdeletePreviousWallet(busy meanwhile; a wallet that is already removed counts as removed, so Remove after a lost answer still ends), thenclosePreviousWalletandreturnToView('/security', router), orerror.leave(Done) callsreturnToView('/security', router).back()steps fromscanortypetostart, otherwise returnsfalse. Unmount drops the words and callsclosePreviousWallet; answers after that are dropped. - Used by:
RemainingBalanceScreen.
Function: openPreviousWallet
- Purpose: Opens a previous wallet of the signed-in account from its old 12 words, beside the member's own wallet.
- Inputs:
words,expectedPubkey(the previous wallet's key), and optionaldeps(loadSdk,apiKey,host,sleep,randomUUID;defaultRecoveryDeps()by default). - Returns / side effects:
walletwithout a wallet in this build (no SDK loads) or when the SDK does not load. Words whose key (identityPubkey, offline; compared without letter case) is notexpectedPubkey, or that are no phrase, aremismatchbefore anything connects. Otherwise a wallet still open from an earlier call is closed, the wallet opens withopenWordsWallet(walleton failure), a fresh idempotency key is drawn for its sends (two wallets never share one), and it answers{ balanceSats }, a synced read. A page close (closePreviousWallet) or another open while the SDK loads or the key is read answerswallet, and nothing connects; a wallet that opens after the page closed it is closed and answerswallet. - Used by:
useRemainingBalance.
Function: transferRemainingBalance
- Purpose: Moves the whole balance of the open previous wallet to the signed-in member's own wallet.
- Inputs:
session, the session the move runs under (for the failure report), and the wallet opened byopenPreviousWallet. - Returns / side effects:
errorwithout an open wallet. Reads the member's Spark address (receiveWalletSparkAddress, opening the member's wallet from the tab phrase when needed) and the synced balance; while it is above 0, sends all of it (sendToSparkAddress,wallet.sendwithroute: spark) and reads again, with a new idempotency key after each send that went out, up toRECOVERY_SEND_TRIES(3) sends. A send that throws keeps its key, so Try again repeats that send and the SDK answers it instead of paying twice; it is also reported as a payment that did not go out (reportPaymentFailure: stagesend, methodspark, flowprevious_wallet, the reason fromsdkFailureReason, the amount, undersession). Answerssentonly once a synced read gives 0; any failure, or funds still arriving after the last send, answerserror. - Used by:
useRemainingBalance(Transfer and Try again).
Function: closePreviousWallet
- Purpose: Closes the open previous wallet and drops its connection and idempotency key.
- Inputs: None.
- Returns / side effects: Disconnects (best effort). A wallet still connecting from an earlier
openPreviousWalletis closed once it opens. - Used by:
useRemainingBalance(unmount, and after a removal) andopenPreviousWallet(before another wallet opens).
Function: BusyLine
- Purpose: A centred status line with a spinner, in place of a step's action while it runs.
- Inputs:
label, the translated sentence. - Returns / side effects:
p[role="status"](text-sm text-app-muted) with a hidden spinningLoader2and the label. - Used by:
SocialRecoveryScreen(checking, saving),RecoverScreen(opening), andRemainingBalanceScreen(opening).
Function: GrantsPage
- Purpose: Next.js page for
/grants. FillAppShellwithProfileChromeLeft,SignedInChrome, andOnboardingGate screen="profile"aroundGrantsScreen. - Inputs: None.
- Returns / side effects: The grants screen inside fill AppShell.
- Used by: Route
/grants.
Function: refreshOwnerAccount
- Purpose: Refreshes a sparse signed-in account with the owner-only fields from
GET /mewithout delaying the caller or replacing newer local account changes. - Inputs: The session token to refresh.
- Returns / side effects: Returns immediately. Gives the round a monotonically increasing sequence number and starts
fetchMe. An answer is used only while its session is still current, an account is in the store, and no answer with a higher sequence number has already been applied. A newer pending, failed, or null round does not block an older valid answer. Every used answer mergeswalletViewerPublicKeyand legacygrantPayoutTodayinto the current account. When the stored account has nofundingobject and the answer has one, the answer's wholefundingobject is taken. When both have one, the stored object and its locally writable fields stay, and onlyfunding.payoutToday,funding.shopPaymentDue,funding.shopPaymentSats, andfunding.shopPaymentRequiredSatsare copied from the answer (a field the answer omits is cleared, so an older api build never leaves stale shop sums). A null or absent answerfundingleaves the stored value unchanged. The whole account is never replaced, so local name, setup, and all other writable fields survive. A null or failed answer is ignored. - Used by:
GrantsScreen,usePasskeyLogin, the Social Recovery sign-in flow, andFundingWithdrawControlafter a successful withdrawal.
Function: discardOwnerRefreshes
- Purpose: Drops every
refreshOwnerAccountround still in flight after a caller stored a newer owner payout itself, so aGET /mestarted earlier (for example when/grantsopened) cannot copy its olderfunding.payoutToday,funding.shopPaymentDue,funding.shopPaymentSats, andfunding.shopPaymentRequiredSatsonto that newer funding. - Inputs: None.
- Returns / side effects: Returns nothing. Takes the next sequence number and marks it as applied, so every round started before the call fails the "no newer applied answer" check and its answer is ignored. A round started after the call applies as usual. Sends no request.
- Used by:
FundingWithdrawControl, right after it stores the withdraw answer (before its ownrefreshOwnerAccount) and right after the account reloaded on 409.
Function: GrantsScreen
- Purpose: Signed-in grants page. Renders
FundingStatusCard, then a visible Today's payout group with exactly one status sentence fromaccount.funding.payoutTodaywheneverfundingis an object (an explicit null stays unavailable), or fromaccount.grantPayoutTodayonly whenfundingis null or absent. Paid and due states explain the result; a blocked state names only its one missing step. Ashop_paymentblock with bothfunding.shopPaymentSatsandfunding.shopPaymentRequiredSatsnon-null links Your payments in 21.gifts shops yesterday and today must add up to at least {required}, half of your daily gift. (funding.payoutToday.shopPaymentAmount) and adds plain Spent so far: {paid}. Still missing: {missing}. (funding.payoutToday.shopPaymentProgress) in the same paragraph, with missing = max(0, required − paid). Each amount isformatBitcoin, a middle dot, andformatFiatDisplayofsatsToFiatAmountat the current spot (useSpotRate, enabled only while those amounts show) in theuseFiatPreferencecurrency; bitcoin stands alone while no spot is available. With either sum null or absent, or on thegrantPayoutTodayfallback, it links Your payments in 21.gifts shops yesterday and today must add up to at least half of your daily gift. (funding.payoutToday.shopPayment). Missing, null, and unknown state/reason combinations show Today's payout status is not available. When the account is non-null, a secondary large GoalsButtonLink(funding.goals.link) goes to/grants/goals, under the grant card and above the staff queue. A missing account shows no link. WhencanEditDailyPayoutRosteris true (at least initiator: initiator and founder), three secondary largeButtonLinks, Daily payment text to/grants/payments/comment, Daily payment amounts to/grants/payments/amounts, and Moderator payments to/grants/payments/moderators, do not fetch the roster. A moderator, a fond, or a software developer does not see those links. WhenroleAtLeast(role, 'moderator'), loads open applications. A count above zero is a secondary largeButtonLinkto/grants/applicationslabeled Open application (1) when the count is one and Open applications (2) otherwise (funding.applications.openCount). A count of zero is the plain sentence No open applications., not a link. Rendersnullwithout a session. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations; grouping viauseNumberFormat; currency viauseFiatPreference; current spot viauseSpotRate. Payout fixes reuse/trust-chain,/grants/apply,/wallet,/settings/social-recovery,/shops, and/welcomeplusrequestForumCompose. - Returns / side effects: React element or
nullwithout a session. The payout sentence itself is the link when that member can act: admission links only fornone/rejected, pending adds Your application is being reviewed. without a link, and a media-post block opens the existing forum composer after client-side navigation. FetchesGET /funding/applicationsonly whenroleAtLeast(role, 'moderator'), which includes a fond, a software developer, an initiator, and a founder. Roles below moderator do not fetch. Loading and a failed load (error sentence plus Try again) do not show the applications link. The Goals link does not fetch;/grants/goalsloadsGET /funding/goal. RendersGrantPlacesPanelunder the payout group for every signed-in account, with the owner's grant status (nonewhen missing) as itsreloadKey, so the panel loads again when that status changes on this page. - Used by:
GrantsPage.
Function: GrantGoalsPage
- Purpose: Next.js page for
/grants/goals. FillAppShellwithProfileChromeLeft,SignedInChrome, andOnboardingGate screen="profile"aroundGrantGoalsScreen. - Inputs: None.
- Returns / side effects: The goals screen inside fill AppShell.
- Used by: Route
/grants/goals.
Function: GrantGoalsScreen
- Purpose: Signed-in grant goal. Heading Goals, the sentence that the 10-active-shop goal is reached and the grant program is open again, the public
GrantPlacesPanel(free places of the round and the 20-shop goal for the next round), the sentence that a shop is active with at least one transaction on 5 of the last 7 days, and the sentence that defines a transaction as a till payment created at https://21.gifts/pos (creating it counts, including later expiry or cancel). When the load succeeds, shows how many shops meet that rule, the label Shops per UTC day,ShopActivityChartfor those 7 days, and the note that the lighter bar is today still open. Loading and error (error sentence plus Try again) keep the heading and those sentences. Rendersnullwithout a session and does not fetch then. - Inputs: Session from
useAuthStore; catalog and locale viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/goalthroughfetchGrantContinuationonly when a session exists. Does not callfetchShopActivity. - Used by:
GrantGoalsPage.
Function: DailyPaymentCommentPage
- Purpose: Next.js page for
/grants/payments/comment. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundDailyPaymentCommentScreen. Amounts are a separate page. Roster HTTP lives under/funding/daily-rosterbecause Next.js forbids aroute.tsbeside this page. - Inputs: None.
- Returns / side effects: The daily-payment comment screen inside fill AppShell.
- Used by: Route
/grants/payments/comment.
Function: DailyPaymentCommentScreen
- Purpose: Client editor for the daily payout comment only. A viewer at least initiator (initiator and founder) fetches
fetchDailyRosterand may save the comment. The comment is text until an icon-only pencil (funding.daily.editComment) opens it. The check (funding.daily.save) stores it and the X (funding.daily.cancel) restores the stored comment. An empty comment showsfunding.daily.commentEmpty. Words Save, Cancel, and Edit are not visible labels. A save in flight replaces the check with a spinner. This screen does not show the default-amount sentence, the payments switch, recipients, or Add. Everyone else who is signed in, including a fond and a software developer, sees the heading plusfunding.daily.forbiddenand does not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. A failed load showsfunding.daily.errorand Try again. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/daily-rosteronly whencanEditDailyPayoutRosteris true. The comment save goes toPOST /funding/daily-roster/comment. A save failure shows afunding.daily.*catalog sentence and leaves the field open. - Used by:
DailyPaymentCommentPage.
Function: DailyPaymentAmountsPage
- Purpose: Next.js page for
/grants/payments/amounts. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundDailyPaymentAmountsScreen. The comment is a separate page. Roster HTTP lives under/funding/daily-rosterbecause Next.js forbids aroute.tsbeside this page. - Inputs: None.
- Returns / side effects: The daily-payment amounts screen inside fill AppShell.
- Used by: Route
/grants/payments/amounts.
Function: DailyPaymentAmountsScreen
- Purpose: Client editor for daily payout amounts only. A viewer at least initiator (initiator and founder) fetches
fetchDailyRosterand may turn payments on or off and add, update, or delete a recipient. The loaded editor showsfunding.daily.defaultNotewith{amount}fromroster.defaultAmountUsdviaformatUsdDisplay. A row shows the display name, or Unnamed when the name is null or blank. When accountId is set the name is a link to/members/{accountId}. On a recipient row the formatted USD amount, the pencil (funding.daily.editplus that label), and the trash share one line. The pencil opens aField; the check saves and the X cancels. Amounts are the stored USD figure (Field, notAmountEntry). The total usesformatUsdDisplayand the visitor grouping style. The add field is Person. Typing@opens the first page of people from the same search as a forum mention. Further letters keep only usernames that start that way. Choosing one fills@username, keeps that person selected while the field equals that token, and leaves the list open. Add posts accountId. No address is rendered. The comment is not on this screen. Everyone else who is signed in, including a fond and a software developer, sees the heading plusfunding.daily.forbiddenand does not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. A failed load showsfunding.daily.errorand Try again. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations; grouping viauseNumberFormat. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/daily-rosteronly whencanEditDailyPayoutRosteris true. Saves go to the payments, add, update, and delete daily-roster POSTs. A save failure shows afunding.daily.*catalog sentence. - Used by:
DailyPaymentAmountsPage.
Function: DailyPaymentModeratorsPage
- Purpose: Next.js page for
/grants/payments/moderators. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundDailyPaymentModeratorsScreen. The comment and recipient amounts are separate pages. Roster HTTP lives under/funding/daily-rosterbecause Next.js forbids aroute.tsbeside this page. - Inputs: None.
- Returns / side effects: The moderator payments screen inside fill AppShell.
- Used by: Route
/grants/payments/moderators.
Function: DailyPaymentModeratorsScreen
- Purpose: Client editor for moderator stipend amounts only. A viewer at least initiator (initiator and founder) fetches
fetchDailyRosterand may turn moderator payments on or off and add, update, or delete a moderator. There is nofunding.daily.defaultNote. A row shows the display name, or Unnamed when the name is null or blank. When accountId is set the name is a link to/members/{accountId}. On a moderator row the formatted USD amount, the pencil (funding.daily.editplus that label), and the trash share one line. The pencil opens aField; the check saves and the X cancels. Amounts are the stored USD figure (Field, notAmountEntry). The total sumsmoderatorsonly, viaformatUsdDisplayand the visitor grouping style. The list label isfunding.daily.moderators. An empty list showsfunding.daily.moderatorsEmpty. The add field is Person. Typing@opens the first page of people from the same search as a forum mention. Further letters keep only usernames that start that way. Choosing one fills@username, keeps that person selected while the field equals that token, and leaves the list open. Add posts accountId. No address is rendered. The comment, the recipient list, and the daily payments switch are not on this screen. Everyone else who is signed in, including a fond and a software developer, sees the heading plusfunding.daily.forbiddenand does not fetch. Rendersnullwithout a session. The page chrome owns the back; this screen renders no back control. A failed load showsfunding.daily.errorand Try again. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations; grouping viauseNumberFormat. - Returns / side effects: React element or
nullwithout a session. FetchesGET /funding/daily-rosteronly whencanEditDailyPayoutRosteris true. Saves go to the moderator payments, add, update, and delete POSTs. A save failure shows afunding.daily.*catalog sentence. - Used by:
DailyPaymentModeratorsPage.
Function: GrantPlacesPanel
- Purpose: Public grant-places panel (
role="group", label Grant places): X of Y places are free., how many people moderators have admitted in the round, then either that applications are open and moderators admit up to Y people, or that all Y places are taken and applications stay open, then When G shops are active, the grant program opens for more people. LoadsfetchGrantPlaceswithout a session. Loading shows the shared Loading…; failure shows Could not load the grant places. Please try again. with Try again.data-grant-placesisloading,error, orreadyso screenshot tests wait for the load. - Inputs: Optional
reloadKey(on/grantsthe owner's grant status). A new value loads the numbers again while the last ones stay on screen, so a place freed by Leave the grant shows without a page load; a failed reload shows the same alert and Try again as a failed first load. - Returns / side effects: React element. One
GET /funding/placesper mount, per retry, and per newreloadKey; a late answer after unmount is ignored. - Used by:
GrantsScreen,GrantGoalsScreen.
Function: FundingStatusCard
- Purpose: Owner grant section on
/grants, not on the profile. The title is oneh121 gifts grant at the app page ramp, with no hairline above it.basissees not-verified copy and how in-person verification works (no apply). Verified and above see funding status fromaccount.funding(missing ornulltreated asnone):none/rejectedshow the daily-gift sentence, About link, and Apply link to/grants/apply(applications are open). Then pending, one-day trial, or admitted with Takes part in the 21.gifts funding program (since {date} whenadmittedAtis a number). Under those three status texts,FundingWithdrawControloffers the quiet way out: Withdraw my application for pending, Leave the grant for trial and admitted.noneandrejecteddo not show it. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session or account.none/rejectedoffer the daily-gift sentence, About, and Apply to every verified account (applications are open). - Used by:
GrantsScreen.
Function: FundingWithdrawControl
- Purpose: The way out of the 21 gifts grant on
/grants, under the owner's status text. Idle it is a small underlined text button (min-h-11 text-sm text-app-muted underline, the same look as Move Bitcoin from another wallet): Withdraw my application forpending, Leave the grant fortrialandadmitted. Pressing it opensInlineConfirmin its place. Pending asks Withdraw your application? with A moderator will no longer review it. You can apply again later.; trial and admitted ask Leave the grant? with Your daily payout stops today. Your place becomes free for someone else. You can apply again later, but a place is not guaranteed. The confirm action repeats the idle label; the other action is Cancel. Nothing is sent before the confirm action. - Inputs:
status(pending,trial, oradmitted); session and account fromuseAuthStore. - Returns / side effects: The idle button or the open question. On confirm, one
postFundingWithdraw: both actions are disabled and the confirm action spins until it answers, and a second tap sends nothing. 200 replacesaccount.fundingwith the answer (statusnone), soFundingStatusCardshows the apply state,GrantsScreenreloadsGrantPlacesPanel, andSignedInChromeand every other reader offunding.statusfollow without a page load. The answer carries nopayoutToday, so it first drops older owner refreshes (discardOwnerRefreshes, so theGET /mestarted when/grantsopened cannot copy the old payout back) and then callsrefreshOwnerAccount, and the Today's payout line ofGrantsScreentakes the new reason fromGET /mewithout blocking the card. 409 loads the account again (fetchMe), drops older owner refreshes the same way, and shows its state without error text; a 401 there signs out. 401 clears the session (clearAuth, as when/meanswers 401), so the login card shows. 403, 404, 503, a network failure, or a failed reload after 409 show Could not withdraw your application. Please try again. or Could not leave the grant. Please try again. inside the question, which stays open for another try or Cancel. A late answer after the session changed is dropped. - Used by:
FundingStatusCard.
Function: FundingApplyPage
- Purpose: Next.js page for
/grants/apply. FillAppShellwithProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="profile"aroundFundingApplyScreen./profile/applyredirects to this path. - Inputs: None.
- Returns / side effects:
FundingApplyScreeninside fill AppShell: the apply walk for a verified account with statusnoneorrejected, the pending, trial, or admitted card, or the not-verified card for a basis account. - Used by: Route
/grants/apply.
Function: FundingApplyScreen
- Purpose: Signed-in grant apply screen. Applications are open to every verified member, so this always renders the apply card: About me, photo, and location steps, then the two yes/no questions; Yes on the truth question posts apply. Pending, trial, and admitted keep their copy. A basis account sees You are not verified yet. and does not post.
- Inputs: Session and account from
useAuthStore. Uses translations. - Returns / side effects: The apply card, the not-verified card, or
nullwithout a session. - Used by:
FundingApplyPage.
Function: aboutMeFilled
- Purpose: True when About me is a real bio (not empty or the display-name auto note). Used by the apply walk. Every verified account with status
noneorrejectedsees that walk. - Inputs:
aboutMe,name. - Returns / side effects: boolean.
- Used by:
nextFillStep,FundingApplyScreen.
Function: locationFilled
- Purpose: True when location is a non-empty trimmed string. Used by the apply walk. Every verified account with status
noneorrejectedsees that walk. - Inputs:
location. - Returns / side effects: boolean.
- Used by:
nextFillStep,FundingApplyScreen.
Function: nextFillStep
- Purpose: First missing apply fill step: about, photo, then location, or
nullwhen all three are present. Used by the apply walk. Every verified account with statusnoneorrejectedsees that walk. - Inputs: Owner
Account. - Returns / side effects:
'about' | 'photo' | 'location' | null. - Used by:
FundingApplyScreen.
Function: ModeratorGroupPage
- Purpose: Next.js page for
/moderate/group(signed-in closed moderator group thread). HTML/moderate/groupis the group page, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left (the only back control: the arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none; the wordmark is not that control),SignedInChrometop-right, andOnboardingGate screen="welcome"aroundModeratorGroupScreen. Group HTTP lives under/conversations/moderator-group(noroute.tsbeside this page). - Inputs: None.
- Returns / side effects: The moderator group screen inside fill AppShell.
- Used by: Route
/moderate/group.
Function: ModeratorGroupScreen
- Purpose: Client closed staff-room thread. Moderators (
roleAtLeast(role, 'moderator')) fetchfetchModeratorGroupthen the newest 20-message page withfetchConversation(session, group.id)and reuseInboxScreenas the open thread (showFilterfalse;showAmountfalse;showAttachtrue; no in-card back; rownamereplaced by the catalogmoderate.groupLabelso the heading is always Moderators chat group). AnIntersectionObserveronInboxScreen'snearStartRef(the eighth grouped bubble from the start, or the first when fewer than eight render) attaches only after the thread end is in view or the thread fits, uses the active page scrollport as its root when one is mounted, then fetches a setnextCursorand prepends unique older messages. The first screen is the newest message. The cursor load does not blank the thread; while stuck to the bottom, InboxScreen keeps the newest in view. camera photos or JPEG/PNG/WebP gallery stills (cap 10) viaprepareForumPhoto; photo-only send allowed. Send is disabled while a pick is still preparing (posting || preparing). Thread stills load withfetchConversationMessagePhoto. Losing staff while mounted bumpspickGeneration, clears drafts/preparing, and revokes blob URLs (same cleanup as unmount); replacing the thread also revokes URLs for stills that are no longer on the message list. Also callsuseSpotRate()and passesrateDaytoInboxScreen. After a successful group+thread load:markConversationRead,bumpUnreadAppBadgeEpoch,refreshUnreadAppBadge(session, undefined, 0)(staff-room unread 0; inbox still fetched). Other signed-in visitors see heading Moderators chat group plusmoderate.groupForbiddenand do not fetch. Rendersnullwithout a session. The top-left arrow returns to the previous in-app view in this tab, or/welcomewhen this tab has none. One arrow. The wordmark is not that control. There is no in-card back. While the staff room is open and the tab is visible, the newest page is fetched every 5 seconds and unseen messages are appended; a hidden tab does not poll, and a failed poll keeps the thread. - Inputs: Session and account from
useAuthStore; catalog viauseTranslations. - Returns / side effects: React element or
nullwithout a session. FetchesGET /conversations/moderator-groupthenGET /conversations/:id?limit=20(optionalcursorfor older pages) only when the role is at least moderator. After a successful group+thread load:markConversationRead,bumpUnreadAppBadgeEpoch,refreshUnreadAppBadge(session, undefined, 0)(staff-room unread 0; inbox still fetched). Posts{ text, photo?, photos? }and GETs conversation photos. Losing staff (or unmount) revokes blob URLs and invalidates an in-flight pick. - Used by:
ModeratorGroupPage.
Function: fetchModeratorGroup
- Purpose: GET
/conversations/moderator-groupwith Bearer and parse{ conversation }viaconversationResponseSchema. Returns the singleton closed staff-room row (kindmoderator_group). - Inputs: Session token.
- Returns / side effects: Conversation row, or throws visitor copy.
- Used by:
ModeratorGroupScreen,InboxLoader(/messagesunlisted?c=guard for a moderator),useUnreadCount(staff unread),refreshUnreadAppBadge(whenmoderationUnreadOverrideis omitted androleAtLeast(account?.role, 'moderator')), andNotificationsLoader(remaining badge after mark-all-read, staff only).
Function: listHiddenMessages
- Purpose: GET
/forum/messages/hiddenwith Bearer and parsehiddenListSchema.messages. HTTP 401/403 throwFailed to list hidden notes: status; other failures visitor copyCould not load hidden notes. Please try again. - Inputs: Session token.
- Returns / side effects: Hidden-note array, or throws.
- Used by:
HiddenNotesScreen.
Function: HandbookScreensPage
- Purpose: Next.js page for
/handbook/screens. Loads screen-variant topics and renders the compact-cardHandbookImageViewer. English card text comes fromscreens.md. German, Spanish, and Filipino come from the screen-card locale file for the request locale. - Inputs: Request locale from
getRequestLocale(cookielocale, otherwiseAccept-Language). - Returns / side effects: The screens handbook screen inside
MarketingLayout. - Used by: Route
/handbook/screens.
Function: HandbookFunctionsPage
- Purpose: Next.js page for
/handbook/functions. Functions markdown only (id prefixfunctions). - Inputs: None.
- Returns / side effects: The functions handbook screen.
- Used by: Route
/handbook/functions.
Function: HandbookEndpointsPage
- Purpose: Next.js page for
/handbook/endpoints. Markdown only; no image switches. - Inputs: None.
- Returns / side effects: The endpoints handbook screen.
- Used by: Route
/handbook/endpoints.
Function: HandbookImageViewer
- Purpose: Nested handbook screens for the selected combo only (
makeCombo(viewport, theme)): three-level contents (chapter → screen → variant) and compactHandbookFigurecards. Left/Right arrows (and lightbox chevrons) step through every visible variant in a shared lightbox. A topic missing that combo is omitted. Global Desktop/Mobile and Light/Dark switches use the union of remaining topics and appear only when both sides exist. - Inputs:
topics(HandbookTopic[]with requireddescription). - Returns / side effects: React element or
nullwhen no topic has combos. Empty visible list still shows switches when remaining is non-empty. No network. - Used by:
HandbookScreensPage.
Function: HandbookOutline
- Purpose: Sticky three-level table of contents: chapter (first path segment), screen route, variant id. Links to
#chapter-…,#screen-…, and the figure hash. - Inputs:
chapters(HandbookOutlineChapter[]),title(already translated Contents label). - Returns / side effects: Nav labeled Contents, or
nullwhen empty. No network. - Used by:
HandbookImageViewer.
Function: HandbookSectionHeading
- Purpose: Chapter (
h2) or screen (h3) permalink heading withHandbookCopyLink. - Inputs:
level(2 or 3),id,label. - Returns / side effects: Heading row. No network.
- Used by:
HandbookImageViewer.
Function: buildHandbookOutline
- Purpose: Group topics into chapter → screen → variant, preserving catalog order. Skips empty
combos. Chapter isscreenChapter(first path segment;/stays/). - Inputs:
topics(HandbookTopic[]). - Returns / side effects:
HandbookOutlineChapter[]. No network. - Used by:
HandbookImageViewer.
Function: nextOutlineIndex
- Purpose: Next slide index for Left/Right gallery stepping. Closed gallery (
current === null): Right → 0, Left → last. Wraps. Empty list stays 0. - Inputs:
length,current(number | null),direction(1or-1). - Returns / side effects: Index. No network.
- Used by:
HandbookImageViewer.
Function: topicPath
- Purpose: Route half of a catalog topic id. An empty slice (
:variant) is/. - Inputs: Catalog topic id.
- Returns / side effects: Path string (
/when the slice is empty). No network. - Used by:
buildHandbookOutline.
Function: topicVariant
- Purpose: Variant half of a catalog topic id.
- Inputs: Catalog topic id.
- Returns / side effects: Variant string, or empty. No network.
- Used by:
buildHandbookOutline.
Function: screenChapter
- Purpose: Chapter key for a screen path (
/setup/rules→/setup;/→/). - Inputs: Screen route.
- Returns / side effects: Chapter label. No network.
- Used by:
buildHandbookOutline.
Function: pathAnchor
- Purpose: Hyphenated hash fragment for a screen path (
/→root,/setup/rules→setup-rules). Dynamic segments like[accountId]becomeaccountId. - Inputs: Route string.
- Returns / side effects: Anchor string. No network.
- Used by:
topicAnchor,buildHandbookOutline.
Function: HandbookFigure
- Purpose: Compact handbook image card: permalink label +
HandbookCopyLink, ~220px preview button that opensHandbookLightboxunlessonOpenis set, and a written description. Scrolls into view whenlocation.hashmatches#id. - Inputs:
id,label,description,src,alt, optionalonOpen(when set, the preview delegates and skips the local lightbox). - Visible UI: Label link, copy-link icon, thumbnail image inside an aria-labeled open button (no visible open-image catalog string), description paragraph, optional lightbox.
- Returns / side effects: An
<article>withid. Hash scroll on mount/hashchange. No network. - Used by:
HandbookImageViewerandHandbookMarkdown(image-only paragraphs).
Function: HandbookLightbox
- Purpose: Full-size handbook image overlay on marketing tokens (
bg-ink,border-paper/10,bg-app-overlayscrim, ghostIconButton+X). Close via X, backdrop click, or Escape. Optional previous/next chevrons whenonPrevious/onNextare set:ChevronLeftshows the previous image (handbook.previousImage) andChevronRightthe next image. Those chevrons stay in the overlay and are not the page-back arrow. Focuses the close control on open. Not a native<dialog>. - Inputs:
open,src,alt,onClose, optionalonPrevious, optionalonNext. - Returns / side effects:
role="dialog"overlay whenopen, otherwisenull. Document keydown while open. No network. - Used by:
HandbookFigure,HandbookImageViewer.
Function: topicAnchor
- Purpose: Stable DOM/hash id from a catalog topic id (
${route}:${variant}). Path/→root; other paths drop the leading/and replace remaining/with-; variant is the segment after the last:. - Inputs: Catalog topic id string (
/:default,/welcome:wallet-pay-unavailable,/handbook/screens:dark, …). - Returns / side effects: Anchor string (
root-default,welcome-wallet-pay-unavailable,handbook-screens-dark, …). No network. - Used by:
buildHandbookOutline.
Function: parseScreenVariantDescriptions
- Purpose: Parse
docs/handbook/screens.mdinto a map of catalog topic id → English description. Under each## Screen:/### Variant:, collect paragraphs (excluding image-only lines), unwrap**bold**and `code`, join with a blank line; skip empty strings. - Inputs: Raw screens handbook markdown string.
- Returns / side effects:
ReadonlyMap<string, string>keyed as<path>:<variantId>. No network. - Used by:
HandbookScreensPage(loadScreenTopics) and the screen-description tests.
Function: screenVariantDescription
- Purpose: Screen-card description for one catalog id in the request locale. English is the paragraph from
docs/handbook/screens.md. German, Spanish, and Filipino come from the screen-card locale file. A missing or blank English paragraph shows the catalog label in every locale. - Inputs: Locale (
en,de,es, orfil), catalog id (<path>:<variant>), the English paragraph when present, and the catalog label. - Returns / side effects: Locale text, unchanged English, or the catalog label. Throws when
de,es, orfilhas no non-blank text for that id. No network. No English fallback. - Used by:
HandbookScreensPage(loadScreenTopics).
Function: topicImageSrc
- Purpose: Public URL for one topic combo PNG under
/handbook-images/. - Inputs: Topic and combo id.
- Returns / side effects: Path string. No network.
- Used by:
HandbookImageViewer.
Function: comboViewport
- Purpose: Viewport half of a combo id.
- Inputs: Combo id.
- Returns / side effects:
'desktop'or'mobile'. - Used by:
HandbookImageViewer.
Function: comboTheme
- Purpose: Theme half of a combo id.
- Inputs: Combo id.
- Returns / side effects:
'light'or'dark'. - Used by:
HandbookImageViewer.
Function: makeCombo
- Purpose: Build a combo id from viewport and theme.
- Inputs: Viewport and theme.
- Returns / side effects: Combo id.
- Used by:
HandbookImageViewer.
Function: defaultCombo
- Purpose: First combo to show (
desktop-lightwhen present, else the first listed, elsenull). - Inputs: Combo id list.
- Returns / side effects: Combo id or
null. - Used by:
HandbookImageViewer.
Function: DeletePostControl
- Purpose: Inline moderator post or nested-reply deletion with confirmation, pending and error states.
- Inputs: messageId, onDeleted, optional kind (
'post'default,'reply'for nested replies); reads the current account and Bearer session. - Returns / side effects: Hidden for other roles; idle trash sits in the note footer icon row (parent) or the nested reply action row (
kind="reply"); confirming wraps to the next line viabasis-full w-fulland rendersInlineConfirm. Idle/confirm/error copy isforum.delete*for posts andforum.deleteReply*for replies. Calls deleteMessage on explicit confirmation, then onDeleted. Error keeps the post or reply and permits retry. When deleteMessage throwsOPEN_CREDIT_DELETE_ERROR(a credit post that has received sats and is not fully repaid), the alert isforum.deleteOpenCreditErrorinstead of the retry error; Cancel clears it. - Used by:
ForumBoardon the parent footer and on nested reply cards.
Function: InlineConfirm
- Purpose: Bordered confirm or cancel group shared by post delete, habit archive, habit comment delete, held-share delete, and leaving the grant. Callers keep their own idle button. This is only the open question, with an optional muted line that says what the action changes.
- Inputs:
label(the question and the group's accessible name), optionaldescription(a muted line under the question, linked to the group witharia-describedby),confirmLabel,cancelLabel,onConfirm,onCancel, optionalbusy, and optionalerror. - Returns / side effects: A
role="group"with the question, an optional alert, a check (a spinner whilebusy), and an X. Both actions are disabled whilebusy. It sends no request of its own. - Used by:
DeletePostControl,MemberHabits,HabitComments,HeldSharesScreen(the delete confirm of a kept share on/settings/held-shares),RemainingBalanceScreen(the removal of an empty previous wallet), andFundingWithdrawControl(withdrawing an application or leaving the grant on/grants).
Function: deleteMessage
- Purpose: Send a moderator hide request for a forum message (top-level note or nested reply).
- Inputs: sessionToken and messageId.
- Returns / side effects: DELETE
/forum/messages/:id; resolves on 204 or already-missing 404. A 409 whose body error is exactlyOPEN_CREDIT_DELETE_ERROR(An open credit cannot be deleted) throws anErrorwith that message, so the caller can name the reason. Other statuses throwMessage deletion failed; network errors propagate. Hide/omit semantics: the API keeps the row withdeleted_atand omits it from GET. - Used by:
DeletePostControl.
Function: setMessagePlace
- Purpose: Set or clear the place pin on a forum message for a moderator session.
- Inputs: sessionToken, messageId, and
place(ForumPlacePin, ornullto clear). - Returns / side effects: PATCH
/forum/messages/:id/placewith JSON{ place }. Resolves to the public message JSON (placeomitted when cleared). A 400 preserves its API reason for adjacent form feedback; other failures throwCould not save place. - Used by:
ShopPlaceControl.
Function: setMessageShopPhotos
- Purpose: Replace the stills on a shop note for a moderator session. An empty list clears stills. A video on the note stays.
- Inputs: sessionToken, messageId, and
photos({ contentType, data, takenAt? }[], at most 10). - Returns / side effects: PATCH
/forum/messages/:id/photoswith JSON{ photos }. A blanktakenAtis omitted. Resolves to the public message JSON. A 400 preserves its API reason for adjacent form feedback; other failures throwCould not save shop note. - Used by:
ShopNoteEditControl.
Function: setMessageShopText
- Purpose: Replace the text of a shop note for a moderator session. The API keeps the shop tag.
- Inputs: sessionToken, messageId, and
text(the visible draft; the shop tag may be omitted). - Returns / side effects: PATCH
/forum/messages/:id/textwith JSON{ text }. Resolves to the public message JSON. A 400 preserves its API reason for adjacent form feedback; other failures throwCould not save shop note. - Used by:
ShopNoteEditControl.
Function: fetchShopNoteEdits
- Purpose: Load the staff edit history of one shop note, newest first.
- Inputs: sessionToken and messageId.
- Returns / side effects: GET
/forum/messages/:id/edits. Resolves to theeditsarray (text, place, or shop account, with actor id, name, and role). ThrowsCould not load edit historyon a non-2xx status. - Used by:
ShopNoteEditControlwhen the pencil panel opens.
Function: setMessageShopAccount
- Purpose: Set or clear the shop account on a forum message for a moderator session.
- Inputs: sessionToken, messageId, and
username(string, ornullto clear). - Returns / side effects: PATCH
/forum/messages/:id/shop-accountwith JSON{ username }. Resolves to the public message JSON (shopAccountomitted when cleared). A 400 preserves its API reason. A 404 throwsNo account with that usernameonly when that is the API reason; another 404 and other failures throwCould not save account. - Used by:
ShopAccountControl.
Function: proxyForumMessageGet
- Purpose: Forward an authenticated GET
/messages/:idfor the app path/forum/messages/:id. Staff sessions receive soft-hidden rows. - Inputs: Incoming Request (Bearer) and
messageId. - Returns / side effects: Proxied GET
/messages/:idwith encoded id and authorization. - Used by: App Router
GETon/forum/messages/[id].
Function: proxyMessagesDelete
- Purpose: Forward a moderation DELETE to the API.
- Inputs: Incoming Request and messageId.
- Returns / side effects: Proxied DELETE
/messages/:id, with encoded id, authorization and upstream status. Upstream 204 hides the row (deleted_at); the row stays and is omitted from GET. - Used by: App Router
DELETEon/forum/messages/[id].
Function: proxyMessagesPlacePatch
- Purpose: Forward a moderator's PATCH of a message place pin to the API.
- Inputs: Incoming Request (Bearer JSON
{ place }) and messageId. - Returns / side effects: Proxied PATCH
/messages/:id/place, with encoded id, authorization and upstream status. 200 is the public message JSON; a cleared pin omitsplace. - Used by: App Router
PATCHon/forum/messages/[id]/place.
Function: proxyMessagesPhotosPatch
- Purpose: Forward a moderator's PATCH of shop-note stills to the API.
- Inputs: Incoming Request (Bearer JSON
{ photos }) and messageId. - Returns / side effects: Proxied PATCH
/messages/:id/photos, with encoded id, authorization and upstream status. 200 is the public message JSON. - Used by: App Router
PATCHon/forum/messages/[id]/photos.
Function: proxyMessagesTextPatch
- Purpose: Forward a moderator's PATCH of a shop-note body to the API.
- Inputs: Incoming Request (Bearer JSON
{ text }) and messageId. - Returns / side effects: Proxied PATCH
/messages/:id/text, with encoded id, authorization and upstream status. 200 is the public message JSON. The shop tag stays on the stored text. - Used by: App Router
PATCHon/forum/messages/[id]/text.
Function: proxyMessagesEditsGet
- Purpose: Forward a moderator's GET of shop-note edit history to the API.
- Inputs: Incoming Request (Bearer) and messageId.
- Returns / side effects: Proxied GET
/messages/:id/edits, with encoded id, authorization and upstream status. 200 is{ edits }newest first. - Used by: App Router
GETon/forum/messages/[id]/edits.
Function: proxyMessagesShopAccountPatch
- Purpose: Forward a moderator's PATCH of a message shop account to the API.
- Inputs: Incoming Request (Bearer JSON
{ username }) and messageId. - Returns / side effects: Proxied PATCH
/messages/:id/shop-account, with encoded id, authorization and upstream status. 200 is the public message JSON; a cleared account omitsshopAccount. - Used by: App Router
PATCHon/forum/messages/[id]/shop-account.
Function: detectNoteLanguage
- Purpose: Detect the language of a forum note after stripping URLs and bolt11 invoices. Scores
en/de/es/filstopwords (with extra weight for German umlauts and Spanishñ¿¡). - Inputs: Raw note
textstring. - Returns / side effects:
en/de/es/filwhen one UI locale wins,otherwhen the text is long enough but not those four, ornullwhen empty or fewer than 12 Unicode letters or digits after stripping URLs and invoices. No I/O. - Used by:
shouldOfferNoteTranslate.
Function: shouldOfferNoteTranslate
- Purpose: Decide whether to offer Translate for this note in the active UI locale.
- Inputs: Raw note
textand the active UIlocale. - Returns / side effects:
falsewhen detection isnullor equalslocale;trueforotheror a different UI locale. No I/O. - Used by:
NoteTranslate.
Function: fetchTranslateAvailable
- Purpose: Query same-origin GET
/translateand cache the shared promise. Failures and non-{ available: true }bodies resolve tofalse. - Inputs: None.
- Returns / side effects:
Promise<boolean>. One in-flight GET is reused for the module lifetime. Does not throw. - Used by:
NoteTranslateon mount.
Function: translateNote
- Purpose: POST
{ messageId, target }to same-origin/translate(api cache-first DeepL) and return the translated body. - Inputs:
translateNote(messageId, target, session?)— forum message UUID, the active UItargetlocale, and optional session Bearer. A non-empty string is sent asAuthorization: Bearer …(hidden staff permalink). Omitted, null, or empty leaves the request unsigned so public notes still work. - Returns / side effects: The
translatedTextstring. Throws when the route is non-2xx ortranslatedTextis missing, not a string, or empty after trim. - Used by:
NoteTranslateon Translate.
Function: proxyTranslateAvailableGet
- Purpose: Same-origin GET
/translate→ api GET/translate. - Inputs: Incoming
Request. - Returns / side effects: Upstream
{ available }, or 502. - Used by: App Router GET
/translate.
Function: proxyTranslateNotePost
- Purpose: Same-origin POST
/translate{ messageId, target }→ apiPOST /messages/:id/translate. - Inputs: Incoming
Requestwith JSON{ messageId, target }. - Returns / side effects:
{ translatedText, cached }or 400/404/503/502 from the 21.gifts api. - Used by: App Router POST
/translate.
Function: proxyTranslateConversationMessagePost
- Purpose: Same-origin POST
{ target }to apiPOST /conversations/:id/messages/:messageId/translate. - Inputs: Incoming
Request,conversationId, andmessageIdfrom the route segments. - Returns / side effects:
{ translatedText, cached }or 400 when the body is not JSON ortargetis not a string. Otherwise the upstream response. - Used by: App Router POST
/conversations/[id]/messages/[messageId]/translate.
Function: translateConversationMessage
- Purpose: POST
{ target }to the same-origin conversation translate route and return the stored-message translation. - Inputs:
conversationId,messageId, UItargetlocale, and the bearersession. An empty session omits Authorization. - Returns / side effects:
{ translatedText, cached }. Throws when the route is non-2xx ortranslatedTextis missing, not a string, or blank. - Used by:
NoteTranslatewhensource.kindisconversation.
Function: NoteTranslate
- Purpose: Control-only client: Translate, Show original, and Show translation are the same Languages
IconButton(aria-labelforum.translate,forum.translateShowOriginal, orforum.translateShowTranslation; no visible label). The error and the spinner stay. Does not renderForumNoteTextor the translated body — exclusive original XOR translation lives inTranslatableNoteBody. Offers the control when the note language differs from the active UI locale and GET/translatereports available. Identity issource + messageId + text + locale(nottext + localealone). Translate sits in the card footer icon row with react / pay / copy whenplacementisrow(ForumBoard supplies acontrolSlotIdtoTranslatableNoteBody, which portals this control there); otherwise under the body (unsigned cards, inbox, About me, funding, hidden notes). Failure shows Could not translate this note. Please try again. and keeps Translate. - Inputs: Required
messageId(stored forum or conversation message id) andtext(raw prose body). Optionalsource(default{ kind: 'message' }, or{ kind: 'conversation', conversationId }). Optionaltone(default|onButton, forbg-app-btnbubbles). Optionalplacement(blockunder the body, default;rowusesdisplay: contentsso the icon sits in a parent footer flex row). Parent-ownedshowingTranslation(true while the translated body is on screen).onTranslatedafter a successful POST. OptionalonTranslateRequest, called synchronously when Translate is clicked, before the request, and not from Show original / Show translation.onToggleShowingfor Show original / Show translation. Noplain,bodyClassName, oronShowingTranslation. - Returns / side effects: The control, or
nullwhen the text is blank, translation is unavailable, orshouldOfferNoteTranslateis false. CallsfetchTranslateAvailableon mount and, on click,translateNotefor a forum message ortranslateConversationMessagefor a conversation message. A change ofsource,messageId,text, or UI locale resets status and invalidates in-flight requests (identity = source + messageId + text + locale). Stops click/keydown so forum expand does not fire.onButtonpaints the control withtext-app-btn-fg. Does not mount the note body. UsesuseActiveSession: while a login is still opening its wallet, a translate click marks nothing read and sends no token. - Used by:
TranslatableNoteBody.
Function: TranslatableNoteBody
- Purpose: Exclusive original XOR translated body in the same React commit (not a parent
useEffectafter paint). Clicking Translate marks the note read-in-full so Show more is gone immediately (while loading, on error, and after Show original). A visible translation is the full text. Idle and error keep the original. Show original restores the original and hides the translation. Identity issource + messageId + text + locale. HoldstranslatedTextandshowingTranslation; a successful POST sets both so the original unmounts in that commit. - Inputs: Required
messageId(stored forum or conversation message id) andtext. Optionalsource(default forum message, or{ kind: 'conversation', conversationId }). Optionalplain. Optionaltruncate(default true; applies only to the original body —ForumNoteTextvsLinkedText). A visible translation is always the full text viaLinkedText(no Show more), including past 280 characters. Clicking Translate sets an internal read-full flag so a truncated original expands on that click and stays expanded when Show original restores it. A new identity clears that flag. OptionalclassName(defaultwhitespace-pre-wrap text-sm text-app-fg;text-app-btn-fgselects NoteTranslatetone="onButton"). OptionalformatTranslated(applied only to the visible translation, not the original; not part of the identity key). OptionalcontrolSlotId(when set, portalsNoteTranslatewithplacement="row"into that element; if the node is missing, the control is omitted rather than stacked). - Returns / side effects: Original or translated paragraph plus the translate control, or
nullwhentextis empty. MountsNoteTranslateunder the body, or portals it intocontrolSlotIdwhen that node exists. Visible body is original XOR translation in the same commit. Idle/error keep original; Show original restores original and hides translation. - Used by:
ForumBoard(notes and replies, includingvia === 'nostr'),PublicMessageLoader,ForumQuotedBody,QuotedForumNote(any caption whentranslateis true;plainonly whenvia === 'nostr'),AboutMeSection,HiddenNotesScreen,FundingApplicationDetailScreen, andFundingApplyScreen(apply walk for every verified account with statusnoneorrejected).
Function: HappylandSection
- Purpose: Presents Father Severin's account of Happyland after Why on the public homepage.
- Input: Receives the marketing page locale and reads the place portrait and observations from the shared English, German, Spanish or Filipino catalog.
- Output: Renders four photographs from the existing 21.gifts Happyland page, one place portrait and three photographs in equal frames, an unlinked source paragraph, and three observations.
Function: fiatDraftForSats
- Purpose: Fiat typing draft for an exact sat amount. Two decimals when they round-trip through
fiatToSats, otherwise more fraction digits so toggling back returns the same sats. Null when no digit count does. - Inputs: Whole
sats, giftdayor null, fiatcode. - Returns / side effects: A plain dot-decimal string, or null when the day or that currency cannot be used. No I/O.
- Used by:
AmountEntry,ForumLoader.
Function: fiatToSats
- Purpose: Inverse of
satsToFiatAmounton the same rate. A positive amount that rounds to 0 becomes 1 sat. - Inputs: Fiat
amount, giftdayor null, fiatcode. - Returns / side effects: Whole sats, or null when the day or that currency is missing or zero. No I/O.
- Used by:
parseAmountDraft.
Function: parseAmountDraft
- Purpose: Reads a bitcoin or fiat typing draft into whole sats. Blank is empty. Fiat allows a dot or comma and at most eight fraction digits, so a unit toggle can round-trip. A positive fiat amount whose rate for that currency is missing, not finite, or zero is
no-rate. A well-formed amount on a usable rate that does not become a safe sat count isinvalid, notno-rate, so a unit toggle can round-trip. A positive fiat amount whose rate for that currency is missing, or zero isno-rate. Zero fiat is 0 sats and does not need a rate. A well-formed amount on a usable total that does not become a safe sat count isinvalid. - Inputs:
unit(btcorfiat), rawdraft, giftdayor null, fiatcode. - Returns / side effects:
{ kind: 'empty' },{ kind: 'invalid' },{ kind: 'no-rate' }, or{ kind: 'sats', sats }. No I/O. - Used by:
AmountEntry,replySatsFromDraft,paySatsFromDraft,parseForumAskAmountInUnit,PayLinkScreen,PosAmount,WalletSend,payDraftProblem,replyDraftProblem.
Function: replySatsFromDraft
- Purpose: Reply and inbox amount. Blank stays empty. Zero is billed as 1 sat.
- Inputs: Raw
draft, typingunit, giftdayor null, fiatcode. - Returns / side effects: Whole sats,
empty, orinvalid. No I/O. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,InboxLoader.
Function: draftUnit
- Purpose: Unit a draft is read in. The amount field reports bitcoin when a fiat preference has no rate yet. A draft that is not a whole bitcoin amount stays fiat, so it waits for the spot rate instead of being rejected as sats. An empty draft and
1.00stay fiat.21,1000, and0stay the reported bitcoin unit. - Inputs:
shown(the unit the field last reported),accountUnit(the signed-in preference; missing means bitcoin), rawdraft. - Returns / side effects:
btcorfiat. No I/O. - Used by:
ForumLoader,InboxLoader,MemberProfileScreen,PublicMessageThread,MemberHabits,PosScreen.
Function: paySatsFromDraft
- Purpose: Pay-sheet amount. A blank field is 21 sats in either typing unit. Zero or a bad draft is invalid.
- Inputs: Raw
draft, typingunit, giftdayor null, fiatcode. - Returns / side effects: Whole sats, or
invalid. No I/O. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,MemberHabits.
Function: payDraftProblem
- Purpose: Pay-sheet problem for the draft on screen. A blank field is payable. Zero is invalid. A positive fiat amount with no rate stays quiet until the rate request has settled, then it is
no-rate. - Inputs: Typing
unit, rawdraft, giftdayor null, fiatcode, and whether the rate request has settled. - Returns / side effects:
quiet,no-rate,invalid, ornullwhen the draft can be paid. No network. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,MemberHabits.
Function: replyDraftProblem
- Purpose: Reply and inbox amount problem for the draft on screen. Blank is not a problem. Zero bills as 1 sat. A positive fiat amount with no rate stays quiet until the rate request has settled, then it is
no-rate. - Inputs: Typing
unit, rawdraft, giftdayor null, fiatcode, and whether the rate request has settled. - Returns / side effects:
quiet,no-rate,invalid, ornullwhen the draft can be sent. No network. - Used by:
InboxLoader,ForumLoader,MemberProfileScreen,PublicMessageThread.
Function: shownDraftPayError
- Purpose: Field error to render for a draft. A live no-rate or invalid draft wins. A stored amount or no-rate error drops once the draft is acceptable, including while the rate is still loading. Any other stored error stays.
- Inputs: Stored request error or
null, the live draft problem, the invalid code, and the no-rate code. - Returns / side effects: The error code to show, or
null. No network. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,InboxLoader,MemberHabits.
Function: shownPaySheetError
- Purpose: Pay-sheet or inbox error to render, including a submit that is waiting on the rate.
loadingstays until that request has settled, even when the draft is cleared, switched to bitcoin, or no longer quiet. After it settles, the live draft decides: no-rate, invalid, or nothing. - Inputs: Stored request error, or
loading, ornull; the live draft problem; the invalid code; the no-rate code; and whether the rate request has settled. - Returns / side effects: The error code to show, or
null. No network. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,InboxLoader,MemberHabits.
Function: typedFiatFigure
- Purpose: The fiat the member typed, kept as that string. A bitcoin unit returns null. A draft that is not a fiat amount returns null. A comma becomes a dot, and one trailing separator is dropped, so
12.is12and1,50is1.50. The spot of the sats is not this figure. - Inputs:
unit(btcorfiat), rawdraft, fiatcode. - Returns / side effects:
{ code, amount }ornull. No I/O. - Used by:
attachTypedFigure,WalletSend,PayLinkScreen.
Function: attachTypedFigure
- Purpose: Copies
valueand, when the draft is a typed fiat amount, adds that figure fromtypedFiatFigure. A bitcoin field, or a draft that is not a fiat amount, is returned unchanged. - Inputs:
value(an object),unit(btcorfiat), rawdraft, fiatcode. - Returns / side effects: The same object, or a copy with
figure. No I/O. - Used by:
ForumLoader,MemberProfileScreen,PublicMessageThread,MemberHabits,InboxLoader.
Function: addDecimalStrings
- Purpose: Sum of two non-negative dot-decimal strings. A missing dot is scale 0, so
12plus1.00is13.00. Either string that is not such a decimal returns null. The result has at least one fraction digit. It never prices a sat sum. - Inputs:
leftandrightdecimal strings. - Returns / side effects: The sum string, or
null. No I/O. - Used by:
WalletPaymentDetails(a shop total when the stored currency matches the fee spot),WalletSend(an on-chain total the same way).
Function: parseForumAskAmountInUnit
- Purpose: Ask amount in the active typing unit. Bitcoin uses
parseForumAskAmount. Fiat converts, then the same 1..10_000_000 range. - Inputs: Raw draft,
unit, rate or null, fiat code. - Returns / side effects: Whole sats in range, or null. No I/O.
- Used by:
ForumAskWizard,ForumLoader.
Function: setAmountUnit
- Purpose: POST
/me/amount-unitwith JSON{ unit }(btcorfiat) and the bearer session. - Inputs: Session token and
unit. - Returns / side effects: Parsed owner
Account. Throws when the response is not ok or failsaccountSchema. - Used by:
saveAmountUnit.
Function: setHeartSats
- Purpose: POST
/me/heart-satswith JSON{ sats }and the Bearer session. - Inputs: Session token and a whole sat amount from 1 through 10,000,000.
- Returns / side effects: Parsed owner
Account, includingheartSats. Throws'Could not save the heart amount.'on a non-ok response or the schema error when the body failsaccountSchema. - Used by:
saveHeartSats.
Function: saveAmountUnit
- Purpose: The one save of the member's default amount unit (
account.amountUnit). Shows the choice on the store account at once, then POSTs/me/amount-unitthroughsetAmountUnit. - Inputs: Session token, the store account before the choice, the chosen unit (
btcorfiat), and an optionalonRollback(unit)callback. - Returns / side effects: A promise that settles once the save did and never rejects. Saves from every caller share one order: a slower answer never overwrites a later choice, and an answer for a session that is no longer current changes nothing. A confirmed save writes the stored unit back; when the latest save fails, the account returns to the last unit the server stored and
onRollbackreceives that unit. - Used by:
AmountEntry,SettingsScreen.
Function: saveHeartSats
- Purpose: Stores the member's account-wide heart amount through
POST /me/heart-sats. Shows the chosen amount on the store account at once and writes the server amount back on success. - Inputs: Session, the store account before the choice, and whole sats from 1 through 10,000,000.
- Returns / side effects: Resolves true when the server stored the amount; resolves false after a failed latest save, rolls the account back to the last stored amount, and changes nothing for an earlier session. Saves share one order so a slower answer cannot overwrite a later choice.
- Used by:
SettingsScreen.
Function: setAccountLocale
- Purpose: POSTs an account language preference to same-origin
/me/locale. - Inputs: Bearer session token, locale code, and
onlyIfUnsetboolean. - Returns / side effects: Sends JSON
{ locale, onlyIfUnset }, returns the parsed ownerAccount, and throws on an invalid or failed response. - Used by: Language controls and
AccountPreferenceSync.
Function: setAccountFiat
- Purpose: POSTs an account fiat preference to same-origin
/me/fiat. - Inputs: Bearer session token,
CHF|EUR|USD|PHP, andonlyIfUnsetboolean. - Returns / side effects: Sends JSON
{ fiat, onlyIfUnset }, returns the parsed ownerAccount, and throws on an invalid or failed response. - Used by:
FiatPreferenceSwitcherandAccountPreferenceSync.
Function: proxyMeAmountUnitPost
- Purpose: Same-origin Bearer proxy of api POST
/me/amount-unitwith JSON{ unit }. - Inputs: Incoming
Requestwith Bearer session and JSON{ unit }. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/amount-unit.
Function: proxyMeHeartSatsPost
- Purpose: Same-origin Bearer proxy of api POST
/me/heart-satswith JSON{ sats }. - Inputs: Incoming
Requestwith Bearer session and a whole-sat JSON body. - Returns / side effects: Upstream
ResponseviaproxyApiRequest. - Used by: Route POST
/me/heart-sats.
Function: proxyMeLocalePost
- Purpose: Same-origin Bearer proxy of api POST
/me/locale. - Inputs: Incoming
Requestwith JSON{ locale, onlyIfUnset }. - Returns / side effects: Returns the owner-account upstream response;
onlyIfUnset=truepreserves a stored locale. - Used by: Route POST
/me/locale.
Function: proxyMeFiatPost
- Purpose: Same-origin Bearer proxy of api POST
/me/fiat. - Inputs: Incoming
Requestwith JSON{ fiat, onlyIfUnset }. - Returns / side effects: Returns the owner-account upstream response;
onlyIfUnset=truepreserves a stored fiat value. - Used by: Route POST
/me/fiat.
Function: HabitTrackerPage
- Purpose: Next.js server page for
/habit-tracker(public habit tracker). It does not read the auth store. Top-right isHabitTrackerTopRight.OnboardingGate screen="welcome"allowGuest. HTML/habit-trackeris the page, not a GET proxy. FillAppShell(align="center") withProfileChromeLefttop-left aroundMemberHabits. - Inputs: None.
- Returns / side effects: The habit-tracker screen inside fill AppShell.
- Used by: Route
/habit-tracker.
Function: HabitTrackerTopRight
- Purpose: Client boundary for the
/habit-trackerheader. Log in (loginHref('/habit-tracker'), so a login returns here) without a session, nothing while a session is held back (the login card is in the page), andSignedInChromewith one. The page stays a server component. - Inputs: None. Reads the auth store
sessionandlockedSession. - Returns / side effects: The top-right control. No request.
- Used by:
HabitTrackerPage.
Function: MemberHabits
- Purpose: Loads
GET /habitsand writesPOST /habits. Renders every member's public habits, periods, comments on the same note card as a living-room note. Internal notes render only for the owner. The owner rates every returned period of an open habit on a neutralSegmentedControland posts that period's key. An archived habit keeps its rows, comments, gift, has no rating pill, pencil, or archive control. The owner opens edit with the pencil and archives from the card while the habit is open. Any signed-in account can comment. Comments render inHabitComments. Comment and delete useSundayWritingGateand sendTime-Zone. Add sendsTime-Zoneand does not use that gate. Edit, log, archive do not. A gift on someone else's comment uses the same Gift control,ForumPaySheet, amount rules, Sunday zap pause as a forum reply, sendsTime-Zone. A blank Gift is 21 sats and can be sent while the spot rate is still loading. Continue stays available while a positive fiat amount is still waiting on that rate. Pressing it names the loading sentence under the button and then waits. After that request finishes with no price, the amount field names the missing rate and Continue stays off. The sheet does not show the raw invoice. A failed reload keeps a list that was already shown and puts the error above it. The open edit stays; a rating or a comment does not discard it. A successful edit or archive closes that habit's edit and does not close a different habit's open draft. The same action is not posted again while that reload is still failing. When a later reload settles, including one that Try again started, a rating, edit, archive, comment, deletion, or the same add can be sent again. An add is not posted again while its request or the reload that confirms it is still unresolved. Try again also closes an edit or archive whose save had already reached the server when that Try again load started. A rating or a comment does not. The archive confirmation stays open until a reload releases an archive that had already reached the server when that reload started. It stays open when that post fails or that reload fails. A reload releases only actions that had already reached the server when that reload started. A second submit does not send that same body while the first request is still waiting, including after another session's list has settled. When that request finishes after the session changed, it does not reload the list and it does not mark the body as posted for the new session. When that request fails after the session changed, or the reload it started fails after the session changed, the new session does not show that error. A request is ignored when the visit changed, including when the same account comes back: it does not reload the list, it does not mark the body as posted, it does not show an error. A gift request that finishes after the session changed does not show its invoice or its error, the sheet closes. A session change closes an open edit, an archive confirmation, a comment-deletion confirmation, clears the new-habit draft and unsent comments before paint, does not show the previous account's draft or private notes. The same gift body is not posted again while that request is still waiting. A failed request can be sent again. Try again reloads that list and does not send the action again. A different session may send it. A list load already started by a session change or Try again is not replaced by that save. A reload that a save started is not replaced by another save. The full-screen error is only when nothing has loaded. Does not log invoices, addresses, notes, or comment text. A gift the api refuses withcode: 'cannot_receive'(CannotReceiveErrorfrompostMemberHabit) shows the author-wallet error in the pay sheet. A reload that marks the open gift's commentcanReceive: falsecloses the sheet; an invoice request still waiting is discarded and does not come back when a later reload says the author can receive again, sendsTime-Zone. When the API rejects a name, description, or notes the form already accepted, that field says the text is not valid and does not name a length the text does not break. A comment post does that only for Invalid comment. Any other comment rejection stays the tracker alert. Cancel on an edit drops that habit's field rejection and the touched state of its name, so opening the edit again shows the saved habit with Save available. - Inputs: None. Reads the auth store session and account.
- Returns / side effects: The habit-tracker body. Posts add, edit, archive, log, comment, deleteComment, and invoice actions.
- Used by:
HabitTrackerPage.
Function: HabitComments
- Purpose: Public comments on one habit. An empty list says there are no comments yet. A signed-out visitor uses the header Log in and gets no second sign-in link. A signed-in account gets Write a comment and Post inside
SundayWritingGate. Delete is the same inline confirm as a forum note and only when the account is at least moderator (moderator,fond,software_developer,initiator, andfounder), also inside that gate, and sendsTime-Zone. Send Bitcoin on someone else's comment usesForumPaySheetinside the zap gate and sendsTime-Zone. A comment withcanReceive: falseshows Can't receive yet (CannotReceiveLabel) and a disabled Send Bitcoin inside the same zap gate, and never opens the sheet. Archived habits keep this block. - Inputs: The habit, the viewer account and session, the comment draft, and the pay-sheet state owned by
MemberHabits. - Returns / side effects: The comment block. Posts nothing itself;
MemberHabitsposts comment, deleteComment, and invoice. The gift on a comment is aForumPaySheetwith the commenter asrecipient, inside aCollapsewithholdMsPAY_SHEET_HOLD_MS, so the pay sheet's success step shows after the payment closed it. - Used by:
MemberHabits.
Function: fetchMemberHabits
- Purpose: Load the public habit tracker from same-origin
GET /habits. - Inputs:
sessionToken— bearer token, ornullwhen signed out. A blank string sends noAuthorizationheader. - Returns / side effects: The parsed habit list. Throws
'Could not load the habit tracker. Please try again.'when the response is not OK or the body fails the schema. - Used by:
MemberHabits.
Function: postMemberHabit
- Purpose: Post a habit-tracker action to same-origin
POST /habits. - Inputs:
sessionToken— bearer token;body— JSON action;timeZone— when true, also sends the deviceTime-Zoneheader. - Returns / side effects: The JSON body when the response is OK. Throws
CannotReceiveErrorwhen the body carriescode: 'cannot_receive'; otherwise throws the apierrorstring when that field is a string, otherwise'Could not save the habit tracker. Please try again.'. - Used by:
MemberHabits.
Function: localizedPublicPath
- Purpose: Builds a stable public URL for one supported language and one of Home, About, Donate, or Rules.
- Inputs: A supported locale and one localized public path.
- Returns: A language-prefixed path such as
/de/about; used by metadata, links, and the language switcher.
Function: parseLocalizedPublicPath
- Purpose: Recognizes only the sixteen supported language and public-page combinations.
- Inputs: A request pathname.
- Returns: Its locale and public path, or
nullfor app routes, unsupported languages, or extra path segments.
Function: publicPathFromUrl
- Purpose: Keeps the visitor on the same public page when they choose another language.
- Inputs: A legacy or language-prefixed pathname.
- Returns: The public page path, or
nullwhen the pathname belongs to the app.
Function: HomeShops
- Purpose: Marketing homepage section under the hero and before how it works. One heading is
homeShops.lead. The card uses the paper, ink, andbg-home-cardtokens. A shop is listed only when its tech provider is exactly 21.gifts. Country, name, blockchain, asset, and activity areFilterMenu, and each is shown only when its options split the unfiltered 21.gifts rows. Map | Table isSegmentedControltone="neutral". Country labels usecountryDisplayName. The map clusters pins closer than 44px below zoom 17. When a focused pin joins a cluster, focus moves to that cluster. When the focused pin or cluster leaves the visible map, focus moves to the map itself. Closing a shop card with focus inside returns focus to the pin's current cluster button when clustered, otherwise to the pin. It frames only after the container has a real size, snaps a later size change unless the visitor moved the map or opened a cluster or a shop window, frames again when the visitor returns from the table, and opens a popup with its own close button. The table sorts from its column headers and has no Tech provider column, because every listed row is 21.gifts. Belowsm, only Name, Location, and Activity columns are visible; when Shop and Country columns exist, their values are stacked under the name. Fromsm, those separate columns and their sort buttons are visible. Headers stay on one line, and cell contents wrap. Activity sorts known tokens by rank and unknown tokens by their label, honoring the chosen direction and breaking ties by ascending shop name. The CSV still includes Tech provider. The help panel is measured after it mounts and sits below the button when it fits, otherwise above it; when neither side fits, it is held 16px inside the window and may cover the button. Its natural height is the inner content'sscrollHeightplus the panel's computed vertical padding and border widths, measured with the pin in place. The live panel always sets top, bottom, left, and width. A fitting bottom is the space under the content. A panel taller than the window uses the 16px inset and scrolls its content. A full-page capture clears that edge. Opening the help panel moves focus into it without scrolling. Closing it with focus still inside returns focus to the help button without scrolling; an outside press on another focusable control leaves focus on that control. If an empty response removes help, its panel closes; focus on the help button or inside its panel moves without scrolling to the selected Map/Table button, and focus elsewhere stays put. A shop id that matches the shop npub pattern links to/{id}on this site. A failed map library, missing map container, or failed map construction opens the table and shows the load-error sentence. That failure is not an empty list. Try again beside that sentence reloads the filters the same way the first load does, and a failed retry does not request places or show the empty sentence. With zero shops the filters, the help button, and the legend are hidden. - Inputs: Translated labels from the server page, including the CSV button label, the URL column label, and the page locale. Place and filter data come from the public map API after mount. Filters are loaded once, before the first places request. Places reload when country, name, blockchain, or asset changes. Activity filters the places already loaded and is not a query parameter. A selection clears only when the shop-derived options no longer include it. A filters response that omits a value the shops still have does not clear it. A filters HTTP error does not wipe the unfiltered shop set.
- Returns / side effects: A section element with light control tokens in either theme. Fetches the place list and the positron style in the browser. Popup photos use only HTTPS origins matching a common HTTPS image source or the host-selected OpenCryptoPay origin. The popup's shop link opens the shop page client-side. Its decorative lucide
ArrowRightshares the close button's React root and teardown. The shop card moves down past an obstacle when it cannot move up or sideways and its bottom still fits inside the map's 16px inset. A cluster press frames its pins when that gains at least one zoom level; when the pins already fill the map, or no target zoom is available, it zooms in by two levels around the cluster instead, capped at 17.5. A cluster whose center is off the map uses the on-map members for its position when any are visible; keyboard activation returns focus to the previously focused member after splitting. Downloads a CSV of the visible rows, including Tech provider and localized country names, when the visitor asks and at least one row is visible. No server write. - Used by: The marketing page at
/.
Function: FilterMenu
- Purpose: Custom listbox for one homepage shop filter. Country, name, blockchain, asset, and activity all use it. The Map/Table control is
SegmentedControl, not this component. Belowsm, the closed pill shows the label above the selected value, with the chevron centered on the right, at least 44px height, androunded-2xlcorners. Fromsm, it keeps one line, 44px height,rounded-fullcorners, the label on the left, and the value beside the chevron on the right. The open panel is a floating list, not a page-flow list. More than eight options use columns when the window is wide enough. The panel flips to stay inside the window. When the flipped panel still crosses an 8px inset, it pins top, bottom, left, and width. When pinning narrows the width, the panel is measured once more at that width before deciding the bottom edge and scrolling state, so wrapped labels are included. A pinned list taller than the window scrolls on the active scrollport, revealing the selected option on opening and the active option after Arrow, Home, or End. Option labels wrap when necessary. Escape and a pointer press outside close it. Focus moving outside the menu closes it without moving focus; focus leaving the page does not close it. A scroll or resize closes a pinned list when its pill is outside the window, without moving focus. - Inputs: A visible label, the committed value, the All label, the options, and a change handler. An option may carry a decorative swatch. Activity options pass their colour class as that swatch.
- Returns / side effects: A combobox and, while open, a listbox. Choosing an option commits that value, closes the list, and returns focus to the trigger. Up and Down move by the column count, Left and Right within a grid row, and Home and End to the first and last option. All is a separate row: Down from All goes to the first option, and Up from the first grid row goes to All. The keys act on the trigger, which keeps focus. No network request.
- Used by: HomeShops on the marketing page at
/, andWalletUsageDashboardon/stats/wallet.
Function: MenuScroll
- Purpose: Wrap the homepage filter list or help panel content in a scrollport when its pinned panel needs scrolling.
- Inputs: The scrolling flag and the content.
- Returns / side effects: The content directly, or inside a
Scrollportwhen scrolling is needed. - Used by: FilterMenu and the HomeShops help panel on the marketing page at
/.
Function: FilterOption
- Purpose: Render one homepage filter option with its active and selected states and optional decorative swatch.
- Inputs: The option, its index, the active index, the selected value, an id builder, and a selection handler.
- Returns / side effects: An option button that stops click propagation and passes its value to the selection handler.
- Used by: FilterMenu on the marketing page at
/.
Function: getMyLoans
- Purpose: Loads the signed-in member's live loans from same-origin
GET /me/loans, including collecting asks, repayment totals, due shares, the next due day, and Sunday rest. - Inputs: Bearer session token. The request also carries the device
Time-Zoneheader when the browser can resolve one. - Returns / side effects: Returns validated
{ sundayRest, loans, lenderWaiting }. Each loan includesclosedAt,maxSats, andmaxAmountwhen supplied by the api; the max is the currently payable free amount. For a fiat loan without a usable rate,totalSats,due.payableSats,due.waitingSats, andnext.satsare valid null values while their stored fiat amounts stay available. Each loan'sdue.waitingSharescounts the shares waiting for a lender's wallet.lenderWaiting{ shares, loans, sats }counts the due shares owed to the caller while the caller cannot receive (satsnull when the api could not price one); compatibility fields stay optional while an older api omits them. Any non-success response, network failure, or invalid body throwsCould not load your loans. - Used by:
useMyLoansfor the loans card, the lender card, Menu row, and/loans/repay.
Function: postRepaymentDue
- Purpose: Requests all currently payable bills for one funded loan from
POST /messages/:id/repayment/due; at most 60 bills are returned by one api call. - Inputs: Bearer session token and credit-note message id. The request sends the device
Time-Zoneheader and no body. - Returns / side effects: Returns validated
{ bills, waiting }; each bill defaults a missingsparkInvoiceto null. Wallet codes become typed wallet errors, matching 409 bodies becomeMissingRequirementsError, and other refusals use the existing payment error mapping. - Used by:
useLoanRepayonce per payable loan before any wallet send.
Function: RepaymentWaiting
- Purpose: Public type of one due/prepay recipient whose wallet cannot receive their share yet.
- Inputs: Type-only export; fields are the share day, recipient identity, stored amount, and whole-satoshi amount.
- Returns / side effects: No runtime value.
useLoanRepay.prepayWaitingpreserves these rows from the prepay response for the muted waiting display. - Used by:
useLoanRepayandLoanPayMore.
Function: closeLoan
- Purpose: Permanently ends collecting for one credit note through
POST /messages/:id/repayment/close; repayment remains available. - Inputs: Bearer session token and credit-note message id. The request carries the device time zone and no body.
- Returns / side effects: Returns validated
{ fundedAt, closedAt, collectedSats, collectedAmount }. A matching 409 becomesMissingRequirementsError; other refusals are typedLoanRepaymentErrorvalues. - Used by:
useLoanRepay.closeCollecting, followed by a loans reload.
Function: LoanRepaymentError
- Purpose: Carries a stable typed refusal from close/free-repayment requests instead of reducing every api answer to display text.
- Inputs: Client error code, HTTP status, and optional current
maxSats/maxAmount. - Returns / side effects: An
ErrornamedLoanRepaymentErrorwith readonly code, status, and maximum fields; amount/share maximum refusals preserve both limits. - Used by:
closeLoan,prepayLoan, anduseLoanRepay.actionErrormapping.
Function: prepayLoan
- Purpose: Requests recipient bills for a freely chosen repayment amount, including future shares, through
POST /messages/:id/repaymentwith JSON{ amount }. - Inputs: Bearer session token, credit-note message id, and the validated amount string (
{ amount }JSON). - Returns / side effects: Returns validated
{ amountSats, amount, bills, waiting }with the same bill/waiting shape as the due endpoint.amountSatsis the non-negative sum of bills that can be paid now, not the waiting allocation; it is zero when all allocated shares wait. Known refusals are typed;amount_too_highandtoo_many_sharescarrymaxSatsandmaxAmount, wallet and missing-requirement refusals keep their established typed errors, and 429/503 remain distinguishable. - Used by:
useLoanRepay.prepaybefore the shared wallet preparation/send path.
Function: proxyMeLoansGet
- Purpose: Same-origin proxy helper for api
GET /me/loans. - Inputs: Incoming
Requestwith a Bearer session. - Returns / side effects: Returns the upstream
ResponsethroughproxyApiRequest. - Used by: Route GET
/me/loans.
Function: proxyMessagesRepaymentDuePost
- Purpose: Same-origin proxy helper for api
POST /messages/:id/repayment/due. - Inputs: Incoming
Requestwith a Bearer session and the credit-note message id. - Returns / side effects: Returns the upstream
Response; the message id is encoded as one path segment. - Used by: Route POST
/messages/[id]/repayment/due.
Function: proxyMessagesRepaymentClosePost
- Purpose: Same-origin proxy helper for api
POST /messages/:id/repayment/close. - Inputs: Incoming
Requestwith a Bearer session and the credit-note message id; there is no body. - Returns / side effects: Returns the upstream
Response; the message id is encoded as one path segment. - Used by: Route POST
/messages/[id]/repayment/close.
Function: parseLoanAmount
- Purpose: Parses positive free-repayment input without using floating point.
- Inputs: The typed string and loan currency. BTC accepts whole sats only; fiat accepts comma or dot and no more than two decimals.
- Returns / side effects: Returns
{ units, text }, where units arebigintsats or cents and text is trimmed while preserving its decimal separator; returns null for empty, zero, negative, or malformed input. It is pure. - Used by:
checkLoanAmountand the repayment screen's free-amount field.
Function: displayableNextAmount
- Purpose: Says whether a loan's next-payment part has an amount the repayment UI can show.
- Inputs: The next
sats(null when its rate is unavailable), the loan'sgoalCurrency, and the stored nextamountin that currency. - Returns / side effects: Returns true for known positive sats; when sats are null, returns true only for a non-BTC stored fiat amount that
creditSmallestUnitsreads as positive. A zero or negative sat amount, a BTC part without sats, and a missing, zero, or malformed fiat amount return false. It is pure and performs no I/O. - Used by:
summarizeLoans(which next part can set the next due day) andLoanRepayScreen(whether a same-day part contributes people to the next-payment line).
Function: loanMaxUnits
- Purpose: Converts the api-provided free-repayment maximum into integer comparison units.
- Inputs: One
MyLoan; BTC readsmaxSats, while fiat requires a non-nullmaxSatsexchange-rate signal and readsmaxAmountas cents. - Returns / side effects: Returns
bigintsats/cents, or null whenmaxSatsis unavailable, the fiatmaxAmountis unavailable, or that amount is malformed. It is pure. - Used by:
checkLoanAmountfor exact above-max validation.
Function: checkLoanAmount
- Purpose: Applies the complete client-side free-repayment input rule before a request is allowed.
- Inputs: The typed amount and its
MyLoancurrency/maximum. - Returns / side effects: Returns
{ ok: true, text }or{ ok: false, reason, max }, distinguishing empty, invalid, above-max, and unavailable-max states without floats. It is pure. - Used by: The repayment screen amount field, inline feedback, and pay-button disabled state.
Function: loanMaxInput
- Purpose: Supplies exactly what the free-repayment Max button inserts.
- Inputs: One
MyLoan. - Returns / side effects: Returns integer
maxSatstext for BTC, the api's unchangedmaxAmountfor fiat only whilemaxSatsis non-null, or null when unavailable. It is pure. - Used by: The repayment screen Max button and validation feedback.
Function: isCollecting
- Purpose: Identifies asks that are still accepting contributions.
- Inputs: One
MyLoan. - Returns / side effects: Returns true exactly when
fundedAtis null andclosedAtis null or omitted; a manually closed but unfunded loan remains repayable and is not collecting. It is pure. - Used by:
LoansCard,LoanRepayScreen,ForumBoard,LoanPayMore, anduseLoanRepay.
Function: summarizeLoans
- Purpose: Combines all loans into the totals and state needed by the loans card, Menu row, and repayment screen.
- Inputs: A validated
MyLoansbody and the visitor number format. - Returns / side effects: Returns counts, payable and waiting totals, the largest api
behindDays(not recomputed, so a share waiting for a lender's wallet never counts), the earliest next due day with its summednext.satsand its defined fiat amount, card tone, and whether payment is available. A payable or waiting total is null when any active part of any loan has a null sat price; a known zero elsewhere never replaces that null. The earliest next part is null in the same way when any loan on that day hasnext.sats: null, while its defined amount still sums the storednext.amountstrings per fiat currency and joins them in first-seen order (for example ₱2.00 + $3.00). There is no per-loan mixing and no separate fiat-only entries. There is no combined goal or collected total because every loan keeps its ownForumGoalBar. It is pure and performs no I/O. - Used by:
LoansCard,MenuAccountHeader, andLoanRepayScreen.
Function: validatedRepaymentPayment
- Purpose: Applies the one shared validity rule to a repayment row's partial payment before any screen derives progress, a remainder, or a repaid total.
- Inputs: The row's original
satsand fiatamountplus optionalpaidSatsandpaidAmount. - Returns / side effects: Returns paid sats as a
bigintonly when they are a whole non-negative value no larger than the original sats. It returns paid fiat as whole cents only when both fiat strings represent exact integer cents, the paid amount is non-negative and no larger than the original amount, and the satoshi relationship is usable. Equality is valid and represents a fully paid value; an overpayment is invalid. Missing paid fields represent zero only when no positive satoshi partial needs a stored fiat partner. ThehasAmountflag distinguishes a supplied paid-fiat value from that zero default. Invalid fiat remains independent from valid sats so consumers can fall back to bitcoin/current spot; invalid sats make the row's partial payment unknown. It is pure and performs no I/O. - Used by:
remainingRepaymentSats,dueShares,CreditLedger,LoanBlock, andLoanRepayScreen.
Function: remainingRepaymentSats
- Purpose: Resolves the bitcoin amount still owed on one repayment line without inventing a negative remainder.
- Inputs: A repayment line's original
sats, optionalpaidSats, and optional authoritativedueSats. - Returns / side effects: Returns
dueSatswhen the api provides it and the partial satoshi relationship is valid; for an older api body, returnssats - paidSats(with missingpaidSatstreated as zero), or null whensatsis unknown or less thanpaidSats. It is pure and performs no I/O. - Used by:
dueSharesandCreditLedger.
Function: dueShares
- Purpose: Builds one oldest-first list of every due ledger share across the member's loans.
- Inputs: Loans in list order and matching repayment ledgers, where a null or missing ledger contributes no rows.
- Returns / side effects: Returns due shares ordered by day, loan, and ledger row with
waiting(the line's apiwaiting; without it, the giver'scanReceiveis false), remainingdueSatsbefore the originalsats, and for matching fiat currencies the remainingamount - paidAmountin integer cents. MissingpaidAmountmeans zero cents only whenpaidSatsis null or zero; positivepaidSatswithout its stored fiat amount, or any supplied malformed or overpaidpaidAmount, makes the remainingamountnull so callers fall back to bitcoin/current spot. A foreign-currency ledger row also keeps its remaining sats and hasamount: null, so that figure never reaches the list, a send-now link, orshareAmounts/sentAmounts. It is pure and performs no I/O. - Used by:
LoanRepayScreento explain which people can be paid or are waiting.
Function: centsString
- Purpose: Writes whole cents (hundredths of a currency) as a two-decimal amount string, for example
30.00for 3000. - Inputs: A non-negative
bigintof cents. - Returns / side effects: The string. It is pure and performs no I/O.
- Used by:
definedDueLabelandLoanRepayScreen(plan slices of a fiat loan).
Function: definedDueLabel
- Purpose: The stored fiat figure of the payable or the waiting part across the member's loans, so a committed repayment share keeps the amount fixed in its currency (
docs/fiat-amounts.md) instead of being priced again. - Inputs: Loans of
GET /me/loans, the part (payablereadsdue.payableAmount,waitingreadsdue.waitingAmount), and the visitor number format. - Returns / side effects: The stored figures of every loan with an active part (positive known sats, or null sats with people or an amount), grouped by fiat currency, summed with
definedFiatSum, and joined in first-seen currency order with+(for example ₱30.00 + $3.00); null when any part is bitcoin, missing, or invalid, or when nothing is in that part. It delegates todefinedFiatAmounts. It is pure and performs no I/O. - Used by:
LoanRepayScreen(the due amount, Send, and the waiting notes),LoansCard(the due box and the waiting line), andMenuAccountHeader(its repayment row).
Function: definedFiatSum
- Purpose: One summing rule for stored fiat amounts: convert each string to cents, add them, and format the total in the same currency.
- Inputs: A loan currency (
BTC,USD,CHF,EUR, orPHP, or undefined), a list of stored amount strings (which may contain null), and the visitor number format. - Returns / side effects: The summed amount formatted by
formatDefinedGoalAmount, or null for bitcoin, a missing currency, any missing amount, an empty amount list, or any string thatcreditSmallestUnitscannot read. It is pure and performs no I/O. - Used by:
definedDueLabel,definedFiatAmounts, andLoanRepayScreen(the Repaid line of a fiat-defined loan).
Function: definedFiatAmounts
- Purpose: One display rule for stored amounts that may span currencies: group by currency, sum each group with
definedFiatSum, and join the formatted results in first-seen currency order. - Inputs: Stored amount and loan-currency pairs in display order, plus the visitor number format.
- Returns / side effects: For example ₱2.00 + $3.00 when both parts are stored fiat amounts. Null for an empty list, a BTC part, or any missing or invalid amount, so the caller keeps its bitcoin-and-spot fallback. It is pure and performs no I/O.
- Used by:
summarizeLoans(the same-day Next amount),LoanRepayScreen(send now, the sending status, Sent, and Repaid), anduseLoanRepayexposes the per-currency inputs assentAmounts.
Function: fittingPrefix
- Purpose: Keeps the longest leading sequence whose summed cost fits a satoshi budget, without skipping an item that does not fit.
- Inputs: Ordered items, a cost function returning sats or null, and the budget in sats.
- Returns / side effects: Returns a new prefix array; a null cost or the first over-budget cost stops selection. It is pure and performs no I/O.
- Used by:
LoanRepayScreenfor the send-now balance limit.
Function: useMyLoans
- Purpose: Keeps one shared, session-keyed
GET /me/loansbody for every mounted loans card, lender waiting card, Menu row, and repayment screen. - Inputs: No argument; reads the active Bearer session from
useAuthStore. - Returns / side effects: Returns
{ loans, reload }throughuseSyncExternalStore(server snapshotnull). The first mounted consumer reads only while that session has no loaded body; later consumers reuse it. Every explicitreloadperforms a read, and a successful answer updates every consumer. A new session or sign-out resets the body to null. A failed read resolves null but preserves the last good body; a stale-session response or a request older than the latest applied response resolves null and cannot replace shared state. - Used by:
LoansCard,LenderWaitingCard,MenuAccountHeader, andLoanRepayScreen.
Function: useLoanRepay
- Purpose: Runs due and free-amount repayment through one in-app wallet pipeline, sequentially and in oldest-first order, and can permanently end collecting. The named shares are taken from all due shares, or from the optional
onlyShareskeys when given; shares of that set another run already holds are skipped. A share (messageId, repayment day, recipient) is reserved from the start of its send and is skipped by any other run, including when/dueor a free-amount/repaymentrequest later returns a new invoice for that share; a send that did not go out releases it. The existing due behavior and settlement rules remain unchanged. - Inputs: A
reloadfunction fromuseMyLoans;payreceives current loans plus optional share keys and stored amounts,prepayreceives one loan and a validated amount string, andcloseCollectingreceives one still-collecting loan.prepaysubstitutesprepayLoanonly for bill acquisition and then enters the same baseline, prepare, balance, send, settlement, and reload path aspay. - Returns / side effects: Returns wallet phase and balance,
activeAction(due,prepay, orcloseplus the per-loanmessageId), sent amounts/names,prepayWaitingplus itsprepayMessageId,prepayAllWaiting(true only after a free-amount prepay whose response had no bills (every share waiting) returned to idle;LoanPayMoreclears the amount field only then), fees, shortage and catalog error state, top-up controls,pay,prepay,closeCollecting,actionError, and visual-pin state. The due box consumes sending, failure, unconfirmed, and shortfall only whenactiveAction.kindisdue; eachLoanPayMoreconsumes them only when the prepay/close message id matches its loan. The waiting recipients and message id come from the latest free-payment request soLoanRepayScreenpasses them only to that loan'sLoanPayMore.actionErrorincludes that samemessageId, typed close/prepay codes, and the api'smaxSats/maxAmountforamount_too_highortoo_many_shares; an untyped close or failed post-close reload becomes a scopedrequest_failedaction error. Closing posts once and reloads without touching the wallet. Each bill is prepared Spark first with the Lightning fallback ofpayInvoiceSparkFirst. Free repayment validatesamountSatsagainst bills only while still validating the requested BTC allocation or fiat amount against bills plus waiting rows. An all-waiting response (amountSats: 0, no bills) reloads as nothing payable now, preserves its waiting recipients, and performs no wallet work. Responses with bills take a freshrepaidSatsbaseline, prepare/send through the shared wallet path, and poll/reload settlement like due payment. - Failure report: Every prepare or send that does not pay (also
insufficient, a prepared amount other than the bill, asamount_mismatch, and a refused Spark invoice before its Lightning fallback) is reported withreportPaymentFailureunder the flowrepay; a send also after the screen closed, a prepare only while its run is current. - Used by:
LoanRepayScreen.
Function: LoansCard
- Purpose: Loan status card used directly under the welcome heading and between the ready wallet balance and payment history.
- Inputs:
place, eitherwelcomeorwallet; readsuseMyLoans, the preferred fiat and number format, and the current spot rate. - Returns / side effects: Returns
nullwhile loans are unavailable or empty. Otherwise shows funding totals, then aForumGoalBarfor each loan with exactly that loan'sgoalCurrency,goalAmount, goal snapshots, collected snapshots, andrateDay. A single loan shows only that bar, exactly as before. Several loans show each loan's non-linked truncated text above its own bar, with the same props; there is no combined bar. When at least one loan is funded, the due/behind/nothing-due/Sunday row links or sends to/loans/repay. A not-funded card instead has the clear Pay early or end collecting link for a collecting loan, or the ordinary Repay your loan link for a manually closed underfunded loan; on Sunday either shows the same Sunday-rest row as a funded card and hides the action. When every payable loan has known sats, the amount renders exactly as before:definedDueLabel(..., 'payable')followed by the payable bitcoin when every payable loan was defined in fiat, with each currency summed and joined in first-seen order (for example ₱30.00 + $3.00 · ₿1'000), otherwise bitcoin with the current spot. When any payable loan has null sats, the card shows only the combined stored fiat total of that part, without bitcoin, or omits the amount if no combined label exists; it also hides Send in favour of the icon-only Repayment details link. The next and waiting lines follow the same all-known-or-fiat-total rule. When nothing is payable but shares wait for a lender's wallet, the row reads Nothing to send now instead of Nothing due today. Both placements add the muted line {amount} is waiting for a lender to set up their wallet (or for N lenders … their wallets); that amount is never part of the amount to send. The Show loan(s) / Hide loan(s) disclosure remains for both cases; opened, it lists each linked loan text with its funding percentage and is closed by default. - Used by:
WelcomeScreenandWalletScreenView.
Function: LenderWaitingCard
- Purpose: Card on the welcome screen for a lender who is owed repayments but cannot receive them yet (no verified wallet), from
lenderWaitingofGET /me/loans. - Inputs: No props; reads
useMyLoans, the preferred fiat and number format, and the current spot rate. - Returns / side effects: Returns
nullwhile loans are unavailable, when the body has nolenderWaiting, or whenlenderWaiting.sharesis 0. Otherwise a neutralregionwhose heading is 1 repayment is waiting for you — open your wallet to receive it or N repayments are waiting for you — open your wallet to receive them, the sum as bitcoin with the current spot beside it whensatsis not null (nothing when it is null), and the labeledButtonLinkOpen your wallet to/wallet, the same action as the wallet requirement. When the account's wallet becomes verified (sparkWalletVerified) while the card shows, it reads the shared loans body again (useMyLoans().reload), so the card leaves once the api counts nothing. - Used by:
WelcomeScreen, directly afterLoansCard.
Function: LoanRepayScreen
- Purpose: Renders the all-loans repayment body: the unchanged due flow first, then per-loan progress and
LoanPayMorefree repayment / collecting controls. - Inputs: No props; reads the session account,
useMyLoans,useLoanRepay,GET /messages/:id/repayment, preferred fiat and number format, and the current spot rate. - Action scoping: The initiating
activeActionkeeps due status in the due box and prepay/close status in only the matching loan controls; a prepay shortfall cannot hide a covered due Send, and another loan's action error cannot alter this loan's field. Before both due pay and prepay, the current loans are remembered, so a final run whose reload empties the list still renders success. - Returns / side effects: Loads every loan ledger, derives payable and waiting shares, pays the available bills oldest-first, reloads settlement, and renders loading, load-error, empty, collecting, Sunday, ready, short-balance, sending, partial, completed, final-payment, unconfirmed, and failed states. A partially paid due row uses
dueSatsbefore the originalsats; its stored fiat due amount isamount - paidAmountin integer cents. Only the initial read and the load-error Try again control set the load-error flag; a failed settlement reload leaves the current shared loans and Sending… state in place. The send-now link appears only when every loan's repayment list has loaded, the run has not reported a shortfall, and the oldest complete shares fit the wallet balance; it pays exactly the shares it names. The send-now link, the full Send button, and their sending line use at most 60 shares per loan (one due request's limit). The full send derives its satoshi sum and stored amounts from that same capped list, so 61 PHP shares of one loan name ₱60.00 · ₿6'000 on the button and in the sending line, while 60 or fewer shares keep the whole payable. The capped list applies only when it is non-empty and every share's satoshi amount is known; an empty loaded ledger falls back to the summary payable and the loan's stored payable amounts. If any named share is missing from the due answer, nothing is sent and the screen reloads. Who gets paid and Top up your wallet are local disclosures; top-up reusesWalletOwnAddresswith its icon-only Copy control. For a funded loan with something due (payable or waiting) whose repayment list is missing, the opened Who gets paid list shows a muted loading line with a spinner while that list is in flight, and a danger error line when it failed to load; a loan with nothing due shows neither. Each list is applied as it arrives, so a failed one shows its error line without waiting for the others. A share the api markswaitingis a muted Who gets paid row with Waiting for {name} to set up their wallet, without the notice fill or a warning icon, and is not part of the amount to send; the waiting note in the due box is muted too and names the stored figure of a fiat loan (definedDueLabel) with the bitcoin beside it. A ledger row whosecurrencydiffers from the loan'sgoalCurrencykeeps its sats and carries no stored amount, so it shows bitcoin with the current spot and cannot feed a foreign figure into the list, a send-now link, orshareAmounts/sentAmounts. The per-loan Repaid line of a fiat-defined loan usesdefinedFiatSumover fully paid rows plus the positivepaidSats/paidAmountof partial due or scheduled rows only when the ledger currency matches the loan and their paid-satoshi sum equalsrepaidSats; then it adds the bitcoin fromrepaidSats(for example Repaid ₱120.00 · ₿4'800 of ₱300.00). A missing ledger, another currency, no paid value, a stale sats sum, or a row without a usable amount keeps the bitcoin-and-spot line. WhentotalSatsis null, the stored fiat goal remains visible and the sat-based progress bar is omitted. For a payable, waiting, or next part, every loan with known sats keeps the develop text; when one loan has null sats the part shows only its combined stored fiat total, with no bitcoin and no Send, and a part without a combined label shows no amount. A null payable total keeps the Pay more area available but without a due Send. The large due line still shows the stored per-currency sums alone for one payable fiat currency, but pairs them with the payable bitcoin when the payable loans span several fiat currencies (for example ₱30.00 + $3.00 · ₿1'000). The send now, sending, Sent, and success Repaid amounts usedefinedFiatAmountsover the affected shares when each has a stored amount (joined per currency, first-seen, for mixed currencies); otherwise they keep bitcoin with the current spot. The sent amounts come fromuseLoanRepay().sentAmounts, which records only bills that actually went out. When every due share waits, the due box reads Nothing to send now with no amount, no people count, and no Send. Behind uses the api'sbehindDaysas it is. - Correctness details: A positive partial
paidSatswith missingpaidAmounthas no derived remaining fiat and falls back to bitcoin/current spot. Free-payment waiting rows use onlyprepayWaitingfrom the matchingprepayMessageId; they never repeat under another loan or use another loan's currency. - Used by:
LoanRepayPageat/loans/repay.
Function: LoanPayMore
- Purpose: Per-loan free repayment form using the shared
AmountEntryin the fixed loan unit without a switch, with its live counter, exact Max, live smallest-unit validation, collecting-payment confirmation, and final end-collecting confirmation. - Inputs:
loan, sharedphase,activeAction, message-scopedactionError,errorKey,prepayWaiting,prepayAllWaiting,sundayRest, currentrateDay, flags for local wallet/shortfall status, wallet balance / shortfall / top-up state, username and preferred-fiat sats formatter, plus the open-top-up,onPayandonCloseCollectingcallbacks fromuseLoanRepay. - Returns / side effects: AmountEntry stays in ₿ sats for a BTC loan or the loan currency for a fiat loan, with no unit switch, and submits the validated typed string unchanged. It compares bigint sats/cents through
checkLoanAmount, fills a positive api maximum exactly in that loan unit, disables invalid, zero-maximum and over-max payment, and starts prepay only with validated loan-currency text. A fiat loan with missingmaxSatsreports the unavailable rate; whenmaxSatsexists butmaxAmountis absent, zero, or malformed it instead reports that the repayment maximum is unavailable. A BTC loan with a missing or zeromaxSatsalso gets maximum-unavailable copy. Every rendered BTC maximum, server correction, confirmation, waiting amount, balance, and shortfall uses the preferred-fiat sats formatter. Every fiat maximum, server correction, collecting confirmation, and returned waiting amount keeps the exact loan-currency figure and shows its corresponding bitcoin beside it. Only a matchingactiveAction.messageIdcan render shared prepay/close progress, failure, unconfirmed state, waiting rows, or shortfall, andactionError.messageIdmust match before a server maximum changes the field. A collecting loan confirms that its first payment permanently ends collecting and independently offers the final close dialog; both dialogs move and trap focus, close on Escape, make the AppShell background inert, and restore focus. If its open pay dialog becomes invalid, that dialog keeps a disabled pay action and Cancel and never exposes the close action. A closed loan keeps Pay more but neither collecting control. Max-related api refusals put a positive returned maximum in the field; other typed errors render specific messages. Returned waiting recipients remain as muted Waiting for {name} to set up their wallet rows with their stored amount. A matching all-waiting prepay (no bills, every share waiting) that returns to idle viaprepayAllWaitingclears the amount, its edited state, both exact amount fields, the attempted draft, the pending action, and the server error and invalid-amount flags. A shortfall keeps the typed draft and the top-up prompt. A wallet shortfall reuses the shared top-up state,WalletOwnAddress, copy control and balance polling. No direct network. - Used by:
LoanRepayScreenonce for every loan.
Function: LoanRepayPage
- Purpose: Next.js page for the signed-in all-loans repayment route
/loans/repay. - Inputs: None.
- Returns / side effects: Returns fill
AppShellwithWalletChromeLeft,SignedInChrome, andOnboardingGate screen="wallet"aroundLoanRepayScreen. The chrome supplies the only Back control. - Used by: Route
/loans/repay.
Function: WalletOwnAddress
- Purpose: Shared 21.gifts address block: the member's own address for adding Bitcoin to the in-app wallet, or a public account's address with another hint line.
- Inputs:
username, optionalcopy(default false), and optionalhintcatalog key (defaultwallet.payAddFunds, the own top-up sentence); reads the browser hostname and localized labels. - Returns / side effects: Returns
nulluntil the host is known or when no address can be formed. Otherwise shows thehintsentence, truncated monospaced address, and profile-style Open CryptoPay QR on every device;copyalso adds an icon-onlyIconButtonwhose accessible name is Copy. It writes the address, then changes to a green check with accessible name Copied for two seconds; neither label is visible. Clipboard refusal leaves the readable block unchanged. - Used by:
LoanRepayScreenafter Top up your wallet, andFondDeposit(Instant payment, withfond.depositLightningHint).
Function: fetchFondPayouts
- Purpose: GET
/fond/payouts(same-origin Bearer proxy of apiGET /fond/payouts) and parsefondPayoutListSchema. Lists today's open Fond payout rows in the api's order:{ id, kind, status, utcDay, paymentHash }per row, withkinddaily|moderator|welcomeandstatusowed|issuing|invoiced|settling.paymentHashisstring | nulland optional: the api sends the stored hash forinvoicedandsettlingrows andnullforowedandissuing, and an api without the field still parses. A row carries no amount: the app asks for its invoice and pays what it says. - Inputs: Bearer
sessionof the Fond account. - Returns / side effects:
{ ok: true, payouts }, or{ ok: false, status, error }without throwing on an HTTP status.statusis the HTTP status of the same-origin proxy answer (also for a 2xx whose body is unreadable or fails the schema, then witherror: null), or0when the request itself failed (network error);erroris the api'serrortext ornull. Status404means the api's Fond surface is off,403means the session is not the Fond account, and every other failure is retried by the next tick. - Used by:
FondPayoutSyncthroughrunFondPayoutTick. - Privacy: The tick never logs a BOLT11, Spark invoice, payment hash, or address from this body.
Function: postFondPayoutInvoice
- Purpose: POST
/fond/payouts/:id/invoice(same-origin Bearer proxy of apiPOST /fond/payouts/:id/invoice) and parsefondPayoutInvoiceSchemaas{ id, bolt11, paymentHash, sparkInvoice }. The api converts its stored USD amount at the current spot and owns the amount; the app never computes or rounds one.sparkInvoiceis the recipient's fee-free Spark invoice when the api has one, otherwise null. - Inputs: Bearer
sessionof the Fond account and the payout rowid, URL-encoded into the path. - Returns / side effects:
{ ok: true, invoice }, or{ ok: false, status, error }without throwing on an HTTP status (0for a network failure). A403stops the loop asforbidden. Every other non-200 (409in progress / not payable / below one sat,503, including a404for an unknown or gone row) skips the row for this tick;errorcarries the api text but is never shown or logged with the invoice. The loop payssparkInvoice, orbolt11without one or after the wallet refused it at prepare, once and sends no proof; the api detects the matching wallet payment by payment hash, BOLT11, or Spark invoice string. - Used by:
FondPayoutSyncthroughrunFondPayoutTick.
Function: fondE2eWallet
- Purpose: Playwright-build-only fake Fond wallet, gated by
getE2eNow(). It lets e2e driverunFondPayoutTick,runFondPayoutTickOnce, andFondDepositSyncthrough the running server without a Breez key or a real wallet. It is inert in production:getE2eNow()returns null there and the function returns null, soFondPayoutSyncandFondDepositSynckeep the real wallet functions. - Inputs: No arguments. Its
payFromWallettakes aWalletPayRequest; only{ type: 'input', input }is payable (the fixture Spark invoice, or the BOLT11 when the api returns no Spark invoice); the inputFOND_E2E_REFUSED_SPARK_INVOICE(spark1e2erefused) fails at prepare as an SDK refusal (sdk_error), so e2e reaches the Lightning fallback. ItslistWalletPaymentstakes aWalletPaymentPage. - Returns / side effects:
nulloutside a Playwright build. In a Playwright build,{ payFromWallet, listWalletPayments, receiveBitcoinAddress, listUnclaimedDeposits, claimDeposit }.receiveBitcoinAddressresolves the fixed BIP-86 mainnet addressbc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr;listUnclaimedDepositsreturns one open 50,000-sat deposit, andclaimDepositrecords its ceiling on it, as the SDK does. For payouts: prepare returnskind: 'confirm', and itssend()resolves{ kind: 'paid' }, records a completed sent payment for that input, and posts{ input }to/e2e/wallet-sendwithout waiting (the test reads it there; nothing serves it otherwise). History reads return those sends, so the loop's own history check finds the payment. The mock api returns a fixedspark1…fixture invoice unless a session fixture asks forsparkInvoice: null, and the api detects the send; the fake wallet sends no proof and has no preimage. - Used by:
FondPayoutSyncandFondDepositSync, when they detect this fake; no production caller.
Function: runFondPayoutTick
- Purpose: One pure, injectable step of the automatic Fond payout loop. It lists today's open rows, asks the api for each row's invoice, and pays it once from the in-app wallet:
sparkInvoicefirst, andbolt11when the api returned no Spark invoice or the wallet refuses it at prepare (payInvoiceSparkFirst; the refusal is reported, and a refusal that arrives after the tick was cancelled ends the row as cancelled without any report, whatever the fallback prepare gives). It sends no proof: the api detects the matching wallet payment by payment hash, BOLT11, or Spark invoice string. Asettlingrow is skipped. - Inputs:
session;isCancelled(true after unmount, sign-out, or an account change); the two api callsfetchFondPayoutsandpostFondPayoutInvoice;payFromWallet; andlistWalletPayments. - Returns / side effects:
{ paid, skipped, stop }. A list404setsstop: 'off'and a list403setsstop: 'forbidden'. A403from an invoice request also setsstop: 'forbidden'; a404there is skipped because the api answers an unknown id the same way. Any other list failure returns withstop: nullso the next tick retries. Rows are handled in list order, one at a time. Before paying, the newest 100 wallet sends are read and all matches by payment hash (case-insensitive), BOLT11, or Spark invoice string are collected: anycompletedorpendingmatch skips the row, and with no match or onlyfailedmatches the row is paid once. A row whose own send this tab saw aspaidis remembered for the tab and skipped while the api still lists it, even after that send left the newest 100; ids the list no longer returns are forgotten so the set stays small, and the history check remains the guard across reloads. A send that timed out (sentLate) is remembered until its outcome is known: while unresolved the row is skipped,truetreats the row as sent and joins the remembered paid ids, andfalseforgets it so a later tick may pay. Aninsufficientprepare or send stops the whole tick; every other outcome skips the row. Every prepare or send that did not go out is reported exactly once withreportPaymentFailureunder flowfond_payout, including thesentLateof a timed-out send, except a Spark refusal that arrives after the tick was cancelled, and the Lightning fallback prepare after it. A cancelled tick returns at its next check, before a row, beforepayFromWallet, and beforesend; a send already started is not aborted. Amounts come only from the invoice, and no BOLT11, Spark invoice, payment hash, or address is logged or reported. - Used by:
runFondPayoutTickOnce, andFondPayoutSyncthrough it.
Function: runFondPayoutTickOnce
- Purpose: Single-flight wrapper around
runFondPayoutTick. It returns the running tick's promise to a caller with the same session, so an effect re-run cannot start a second tick against the same payout row and pay its stored invoice twice. A caller with a different session waits for the running tick to settle, ignores its result or rejection, and then starts its own tick with its own deps. Ticks never overlap. - Inputs: The same
FondPayoutTickDepsasrunFondPayoutTick:session,isCancelled,fetchFondPayouts,postFondPayoutInvoice,payFromWallet, andlistWalletPayments. - Returns / side effects: The in-flight tick's
{ paid, skipped, stop }result when its session matches; otherwise the result of a tick started with these deps after the in-flight tick settles. The module-level guard is cleared infinallyafter the tick resolves or throws, so the next call starts a fresh tick. A cancelled tick ends at its next check, so the next interval tick starts a new one after it settles. It adds no other side effects. - Used by:
FondPayoutSyncfor every tick it starts.
Function: FondPayoutSync
- Purpose: Root-mounted,
null-rendering client loop that pays the Fond queue automatically while the Fond account is signed in and its in-app wallet is open. It has no screen. - Inputs: Reads the auth store (
session, account id, role) and the wallet store status. It callsfondE2eWallet()once on mount. It callsrunFondPayoutTickOncewith the real api functions, the fake wallet when that returned one and the real wallet functions otherwise, andisCancelled: () => stoppedfor that effect run. - Returns / side effects:
null. Active only when signed in,roleAtLeast(account.role, 'fond'), a session token is present, and either the wallet isreadyorfondE2eWallet()returned the Playwright fakes. In that build the fakes replacepayFromWalletandlistWalletPayments; in every other buildfondE2eWallet()is null and the real wallet functions stay. It runs one tick on activation and then everyFOND_PAYOUT_INTERVAL_MS(60 s). Each tick payssparkInvoice, orbolt11without one or after the wallet refused it at prepare, once and sends no proof; the api detects the payment. Single flight: the module-level guard makes an effect re-run with the same session share the running tick, while a new session waits for it to settle and then runs its own tick; a cancelled tick ends at its next check without scheduling another. A tick resultforbidden(403) oroff(404) stops the loop only for therunKey(session:accountId) of the effect run that started that tick, and the stopped key survives a wallet reconnect in the same tab. Unmount, sign-out, a locked wallet, or an account change cancels the running tick and clears the timer. A rejected tick is swallowed and retried on the next interval. - Used by:
RootLayout, right afterWalletSync.
Function: FondDeposit
- Purpose: Deposit block of the public Fond page, so anyone can top up the Fond by scanning. Heading Top up this Fond (
fond.depositTitle), then the existing neutralSegmentedControl(groupfond.depositMethod,aria-pressed) with Instant payment (Lightning) and On-chain deposit: the wallet's existing labels for those methods (wallet.payment.method.lightning,wallet.payment.method.deposit), since no screen says Lightning (docs/ui.md). Then the selected target. - Inputs:
username(the Fond handle) andonchainAddress(the summary'sonchainAddress, or null). - Returns / side effects: A
section. Instant payment is selected on every load and rendersWalletOwnAddresswithcopyandhint="fond.depositLightningHint": the Fond'susername@domain, its Open CryptoPay QR, and the icon-only Copy. On-chain renders the mutedfond.depositOnchainHint, the address in mono type broken anywhere (break-all) within the QR width, a plainQrCodeof the BIP21 URIbitcoin:<address>(no amount, labelfond.depositOnchainQr), an icon-only Copy / Copied (useCopied) that copies the bare address, and the muted linefond.depositOnchainConfirmations. The selector is shown only whenonchainAddresspassesisMainnetBitcoinAddress; a null or malformed value shows Instant payment alone, with no disabled option, and is never rendered or encoded. QRs show on every user agent (public view rule). - Used by:
FondSummaryLoader, between the KPI tiles and the paid grant-payout line.
Function: isMainnetBitcoinAddress
- Purpose: Shape check of a Bitcoin mainnet address before it is shown or encoded: lowercase bech32
bc1q(42 or 62 characters) orbc1p(62), or base581…/3…(26 to 34 characters). No checksum; it keeps free text, a testnet address, or a URI out of the deposit QR. - Inputs:
valuestring. - Returns / side effects:
truefor a plausible mainnet address, otherwisefalse. No side effects. - Used by:
FondDeposit.
Function: putFondDepositAddress
- Purpose: PUT
/fond/deposit-address(same-origin Bearer proxy of apiPUT /fond/deposit-address) with JSON{ address }and parsefondDepositAddressSchema. - Inputs: Bearer
sessionof the Fond account and the wallet's static depositaddress. - Returns / side effects:
{ ok: true, address }, or{ ok: false, status, error }(FondPayoutFailure) without throwing on an HTTP status;0for a network failure, and a 2xx body that fails the schema keeps its status witherror: null. 400 is an address the api refused, 403 another account, 404 a Fond surface that is off, 503 an api that cannot store it now. The address is never logged. - Used by:
FondDepositSyncthroughregisterFondDepositAddress.
Function: proxyFondDepositAddressPut
- Purpose: Proxies PUT
/fond/deposit-addressto the api. - Inputs: Incoming
Requestwith Bearer session and JSON{ address }. - Returns / side effects: Upstream
Responsewith the api's status and body, or 502 when the api is unreachable. It forwards theAuthorizationheader and the body and logs neither. - Used by: Route PUT
/fond/deposit-address.
Function: registerFondDepositAddress
- Purpose: One registration attempt of the Fond wallet's on-chain deposit address with the api.
- Inputs:
session,receiveBitcoinAddress(the wallet's static address read), andputFondDepositAddress. - Returns / side effects:
registeredwhen the api stored the address;stopon 403 or 404, so the caller sends nothing more for that session (as the payout loop stops);retryon every other answer (400, 401, 503, a network failure, an unreadable body) and when the wallet could not read its address, in which case nothing is sent. - Used by:
FondDepositSync.
Function: claimFondDeposits
- Purpose: Makes the Fond wallet claim its on-chain deposits under a bounded fee. With
defaultConfig('mainnet')the SDK (@breeztech/breez-sdk-spark0.26.0) claims a deposit by itself only while the claim fitsmaxDepositClaimFee, which defaults to 1 sat/vbyte; a dearer deposit stays unclaimed until the app claims it. This pass calls the SDK'sclaimDepositwith a fixedmaxFeeper deposit. The SDK records that ceiling on the deposit and applies it to its own later attempts, early or at maturity. - Inputs:
listUnclaimedDepositsandclaimDepositof the wallet, andisCancelled, checked before each claim. - Returns / side effects: How many claims it asked for. The ceiling is a tenth of the deposit, at most
FOND_DEPOSIT_CLAIM_MAX_FEE_SATS(2,000 sats). A deposit that is claimed, submitted, or refunded (done), that already carries this ceiling, or whose ceiling would be 0 sats is skipped, so a deposit is claimed once per ceiling and not on every pass. A failed claim (for example a matured deposit that costs more than the ceiling) is swallowed and the next deposit is handled; a cancelled pass stops before its next claim; a failed list rejects. - Used by:
FondDepositSync.
Function: FondDepositSync
- Purpose: Root-mounted,
null-rendering client sync of the Fond's on-chain deposits. Only the Fond member's signed-in app can read the Fond wallet's deposit address, so this registers it with the api and claims the wallet's deposits while that wallet is open. A sibling ofFondPayoutSyncso each stays single-purpose: that one pays, this one receives. - Inputs: Reads the auth store (
session, account id, role) and the wallet store status; callsfondE2eWallet()once on mount. - Returns / side effects:
null. Active on the same condition asFondPayoutSync: a session,roleAtLeast(account.role, 'fond'), and areadywallet or the Playwright fake. On activation it callsregisterFondDepositAddressonce persession:accountId:registeredandstop(403 / 404) settle that key, so a wallet reconnect sends nothing again;retryor a thrown error leaves it open for the next activation (a reconnect or a new session), never on a timer, and an attempt in flight blocks a second one. A registration answer that arrives after the session or account changed is dropped. Only afterregisteredfor the currentsession:accountIddoes it runclaimFondDeposits, then again on everynewDepositsorunclaimedDepositsreport (onWalletDeposits), so an account at rankfondor above that the api refuses (403) never claims and keeps the SDK default. Reports that arrive while a pass runs start exactly one more pass after it, a failed pass waits for the next report, and the effect cleanup cancels a running pass before its next claim. In a Playwright build the fake'sreceiveBitcoinAddress,listUnclaimedDeposits, andclaimDepositreplace the wallet functions. Sign-out, a locked wallet, or unmount stops listening. - Used by:
RootLayout, right afterFondPayoutSync.
Function: receiveWalletBitcoinAddress
- Purpose: Reads the static Bitcoin deposit address of the connected wallet (
receiveBitcoinAddressof the connection: the SDK'sreceivePaymentwith{ type: 'bitcoinAddress' }and nonewAddress, so the existing address). - Inputs: None.
- Returns / side effects: The address. Throws
wallet-connectwithout a connection, otherwise the SDK's error. It does not open the wallet. - Used by:
FondDepositSyncthroughregisterFondDepositAddress.
Function: listWalletUnclaimedDeposits
- Purpose: Lists the on-chain deposits the connected wallet tracks and has not finished claiming (the SDK's
listUnclaimedDeposits), asWalletDepositrows:txid,vout,amountSats,done(claim submitted or claimed, or refunded), andmaxClaimFeeSats(a recorded fixed ceiling, else null). - Inputs: None.
- Returns / side effects: The deposits. Throws
wallet-connectwithout a connection, otherwise the SDK's error. - Used by:
FondDepositSyncthroughclaimFondDeposits.
Function: claimWalletDeposit
- Purpose: Claims one deposit of the connected wallet with a fixed fee ceiling (the SDK's
claimDepositwithmaxFee: { type: 'fixed', amount }). - Inputs:
{ txid, vout }andmaxFeeSats. - Returns / side effects: Resolves once the SDK answered (settled, submitted, or deferred). Throws
wallet-connectwithout a connection, otherwise the SDK's error (for example a matured deposit whose claim exceeds the ceiling). - Used by:
FondDepositSyncthroughclaimFondDeposits.
Function: onWalletDeposits
- Purpose: Subscribes to the SDK's
newDepositsandunclaimedDepositsevents of the current wallet connection. - Inputs:
listener, called once per such event. - Returns / side effects: An unsubscribe function. Other events (
synced, payments,claimedDeposits) do not call it. - Used by:
FondDepositSync.
Function: proxyFondPayoutsGet
- Purpose: Proxies GET
/fond/payoutsto the api. The route answers the Fond payer's session the open rows for today. - Inputs: Incoming
Requestwith Bearer session. - Returns / side effects: Upstream
Responsewith the api's status and body, or 502 when this proxy cannot reach the api. It forwards theAuthorizationheader and never logs the body. - Used by: Route GET
/fond/payouts.
Function: proxyFondPayoutInvoicePost
- Purpose: Proxies POST
/fond/payouts/:id/invoiceto the api. The api issues or returns the row's BOLT11, payment hash, and fee-free Spark invoice (or null). - Inputs: Incoming
Requestwith Bearer session and the pathid, URL-encoded upstream. - Returns / side effects: Upstream
Response, or 502 when the api is unreachable. No body is read or logged. - Used by: Route POST
/fond/payouts/[id]/invoice.
Function: proxyFondSummaryGet
- Purpose: Proxies public
GET /fond/summaryto the api for the Fond page. It adds no auth header and copies the api's status,cache-control, and body. - Inputs: Incoming
Request(no auth required). - Returns / side effects: Upstream
Response, or 502 when this proxy cannot reach the api. The routeGET /fonds/[username]/summarythen compares the body'susernamewith the path handle. - Used by: Route GET
/fonds/[username]/summary.
Function: fetchFondSummary
- Purpose: Reads the same-origin
GET /fonds/:username/summaryproxy and validates the body withfondSummarySchema. A body withoutonchainAddress(an api that does not send it yet) reads asonchainAddress: null. - Inputs:
username— Fond handle from the route. - Returns / side effects: The
FondSummary, ornullon 404 (no Fond, or another handle). Throws on any other non-2xx status or a body that fails validation. - Used by:
FondSummaryLoaderon/fonds/[username].
Function: FondPage
- Purpose:
/fonds/[username]page. WrapsFondSummaryLoaderin the unsigned publicAppShell(one top-left back arrow with the home wordmark, light language switcher). - Inputs: Dynamic route params (
username). - Returns / side effects: The public Fond screen. No server fetch; the loader calls the same-origin proxy after hydration.
- Used by: App Router route
/fonds/[username].
Function: FondSummaryLoader
- Purpose: Client loader for the public Fond card. A new component because
StatsDashboardis the ink marketing stats page with charts and a fiat picker, andViewProfileScreenrenders a member profile with gift charts; neither shows Fond totals. - Inputs:
username. FetchesfetchFondSummary(username)on mount and after Try again. - Returns / side effects: Loading (
forum.loading), not-found (fond.missing), error (fond.errorwith Try again), or the card: the handle with the FondForumRoleTagand hint, three KPI tiles (fond.received,fond.paidOut+fond.fees,fond.balance+fond.balanceAsOf/fond.balanceNotReported),FondDepositwith the handle and the summary'sonchainAddress, andfond.payoutsPaid. Every amount usesformatBitcoinwith the preferred fiat from the current spot (useFiatPreference+useSpotRate+formatFiatDisplay) under it; the spot is not stored. - Used by:
FondPage.