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 as tl. The URL prefix stays /fil.
  • Inputs: Unprefixed path, English title, English description, and an optional locale for Home, About, Donate, and Rules. HREFLANG_BY_LOCALE maps each UI locale to its hreflang code (fil → tl; en, de, and es stay themselves).
  • Returns / side effects: Next.js Metadata; no I/O. Localized Home, About, Donate, and Rules alternates use that map, so the Filipino alternate is hreflang="tl" with href /fil…, plus x-default on the unprefixed path.
  • Used by: Home, About, Donate, Rules, Stats, Legal, and Handbook pages.

Function: PosPage

  • Purpose: App Router page for /pos. Wraps PosScreen in AppShell and OnboardingGate 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. Wraps PosAmount in AppShell and OnboardingGate screen="profile". The top-left arrow returns to the previous in-app view in this tab, or /welcome when 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. Renders PosTill.
  • 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 /pos opened this page, otherwise a replace. A WalletRequiredError (api code wallet_required) shows the pos.needWallet alert, a CannotReceiveError (api code cannot_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 /pos only. 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/amount when no charge is open, otherwise the open charge (countdown, including 0:00, sat amount, the currency figure stored with the charge (committedFiatFigure with 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, memo pos:<id>, which the wallet reads as info.chargeId) and carries its amount (or that amount plus the fee), or when a read of the api returns the charge paid. 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 as pos_charge_paid_seen; the charge stays open, and the api lists such a payment under received, where it shows as a Received row. GET /pos does 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's paid: 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 asks GET /pos/charge at once and then PAY_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 by applyRead, 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's paidAt), 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 reads GET /pos/charge once 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 with PosAmount: 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 reads GET /pos/charge once: 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 /pos confirms 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 as paid opens 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 shows PosPaidOverlay over 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 as paid opens 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 /wallet payment 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), every PAY_POLL_MS after 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 (memo pos:<id>, which the wallet reads as info.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-received pin, honoured only in a Playwright build (visualPin), a payment of the open charge's Spark invoice (its amount, naming the charge) is reported through announceReceivedForE2e to 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 (sparkWalletVerified not true), it shows the pos.needWallet link to /wallet; if background wallet setup has exhausted its retries, WalletSetupNote replaces 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), and useWalletSetup (due, failed).
  • Returns / side effects: React element. Calls fetchPosState and cancelPosCharge. Once the till has loaded, renders PosHistory under the card's other content with the history and the received payments 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 from WalletSetupNote; setup due or failed suppresses the address and QR.
  • Interaction log: A paid charge shown on this card is recorded as pos_charge_paid_seen with 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-success green (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.vibrate with POS_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; null while 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 /pos QR 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; PosTill may already show a row the api still has open as paid, with paidAt the 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 valid paidAt; Expired; or Cancelled), the amount in bitcoin with the currency figure stored with that charge (committedFiatFigure with 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 order PosTill gives; 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 green ArrowDownLeft with 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 (kind lightning, wallet.payment.method.lightning) or Wallet transfer (kind spark, wallet.payment.method.spark). A payment that was not in the list when it first showed eases in with animate-fade-in, the animation of a new forum reply. The open charge is shown above the list and is left out of it. Any other pending row is shown as Expired, because the api has at most one open charge and returns it as charge. 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[] from GET /pos/charge), received (PosReceived[] from the same answer, newest first), and openChargeId (the charge shown as open above, or null). Each charge row calls committedFiatFigure with the visitor's fiat as preferred; a charge row without a stored figure takes the current spot from useSpotRate (rateDay) through preferredFiatSuffix, and that figure is not written onto the charge. A received row has no stored figure and calls only preferredFiatSuffix with 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: PosScreen tests.

Function: fetchPosState

  • Purpose: GET /pos/charge for the signed-in till.
  • Inputs: Bearer sessionToken.
  • Returns / side effects: { charge, history, received }. A charge is pending, paid, cancelled, or expired, with paidAt (ISO string, or null; null also when the api does not send it). charge is the pending charge, or one paid within the last minute. received lists the payments the wallet received without a till charge, { id, amountSats, receivedAt, kind } (kind lightning or spark), 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 or charge / history are 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 }. amount is that typed draft, so 12.00 stays 12.00.
  • Inputs: Bearer sessionToken, a whole sat amount, and an optional typed pair { amountCurrency, amount } (amountCurrency is USD, CHF, EUR, or PHP).
  • Returns / side effects: The created charge. Throws WalletRequiredError or CannotReceiveError on a 400 whose code is wallet_required or cannot_receive (via throwIfWalletAnswer), recognised by the body's code only; otherwise throws with the API error string or a status fallback. Records pos_charge_created with 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 amountCurrency is USD, CHF, EUR, or PHP and amount is a string, that pair is the figure and the viewer's currency does not replace it. Without that pair, preferred is used only when the stored snapshot for that code is a string (an empty string counts; null and a missing field do not). preferred omitted or null returns null even when snapshots exist. A null return 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 calls satsToFiatAmount and never takes a rate.
  • Inputs: stored (amountCurrency, amount, amountUsd, amountChf, amountEur, amountPhp) and optional preferred (FiatCode or null).
  • Returns / side effects: { code, amount } with the exact stored decimal, or null. 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. amountCurrency and amount are 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 } with code USD, CHF, EUR, or PHP) or undefined.
  • Returns / side effects: A StoredFiat, or undefined. 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/key use export function GET (/maps/key is always 200 { key: string | null }); same-origin api proxies re-export unique functions as GET (including /forum/messages, /forum/messages/places which re-exports proxyMessagesPlacesGet, /forum/messages/hidden which re-exports proxyMessagesHiddenGet, /forum/notifications which re-exports proxyNotificationsGet, /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}.jpg from the api), /messages/[id]/[file], /messages/[id]/repayment which re-exports proxyMessagesRepaymentGet, /me/loans which re-exports proxyMeLoansGet, /me/previous-wallets which re-exports proxyMePreviousWalletsGet, /me/held-shares which re-exports proxyMeHeldSharesGet, /view-key/[viewKey], /push/vapid-public, /trust/graph, /trust/proposals which re-exports proxyTrustProposalsGet, /funding/applications which re-exports proxyFundingApplicationsGet, /funding/daily-roster which re-exports proxyFundingDailyRosterGet, and /funding/applications/[accountId] which calls proxyFundingApplicationGet). /translate re-exports proxyTranslateAvailableGet (api GET /translate). HTML /messages is the inbox page, not a GET proxy. HTML /notifications is the notifications page, not a GET proxy. HTML /moderate is the moderation hub, not a GET proxy. HTML /moderate/hidden is the hidden-notes page, not a GET proxy. HTML /moderate/proposals is the confirm/reject queue, not a GET proxy. HTML /moderate/applications is the grant-application queue, not a GET proxy. HTML /grants/payments/comment and /grants/payments/amounts are the daily payment pages, not GET proxies. HTML /moderate/applications/[accountId] is the grant-application review, not a GET proxy. HTML /moderate/group is the closed staff-room page, not a GET proxy. /wallets/usage re-exports proxyWalletUsageGet. The signed-in HTML page /trust-chain is TrustChainPage, not this GET. GET /l/[code] redirects an 8-hex short code or calls notFound(). GET /links/[code] re-exports proxyShortLinkGet. HTML /pos is the till page, not a GET proxy; GET /pos/charge re-exports proxyPosGet. /forum/messages/[id]/edits re-exports proxyMessagesEditsGet.
  • Inputs: Incoming Request on proxy routes (plus async params on dynamic photo, /messages/[id]/photo/[file] (id + file matching {1-9}.jpg), /conversations/[id]/messages/[messageId]/photo (id + messageId), /conversations/[id]/messages/[messageId]/photo/[file] (id + messageId + file matching {1-9}.{jpg|jpeg|png|webp}; proxy always requests {n}.jpg from the api), file, and view-key); none on healthz or /maps/key; /translate takes the incoming Request.
  • Returns / side effects: Response. Healthz is { status: 'ok' } 200; /maps/key is always 200 { key: string | null }; /translate is 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, getMyLoans via GET /me/loans, fetchPreviousWallets via GET /me/previous-wallets, fetchHeldShareBoxes via GET /me/held-shares, and fetchTranslateAvailable via GET /translate. GET /.well-known/nostr.json proxies NIP-05. GET /.well-known/lnurlp/[username] proxies LUD-16. GET /lnurlpay/[pubkey]/metadata (async pubkey) calls proxyLnurlpayMetadataGet for the in-app wallet; GET /lnurlp/[username]/invoice (async username, query unchanged) and GET /verify/[paymentHash] (async paymentHash) call proxyLnurlpInvoiceGet and proxyVerifyGet for payers' wallets and answer with Access-Control-Allow-Origin: *.

Function: OPTIONS

  • Purpose: CORS preflight for /.well-known/nostr.json and /.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/.m4v name).
  • Inputs: File.
  • Returns / side effects: boolean.
  • Used by: ForumLoader attach 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 } with file, JPEG poster, and previewUrl; 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/messages with video + optional poster, optional goalCurrency and goalAmount (trimmed draft, comma stays; omitted from the form when either is missing, and on replies), optional placeLat / placeLng / placeLabel plus placeStreet / placeHouseNumber / placePostalCode / placeCity / placeCountry when the pin has an address (place fields are top-level only; replies must not send them), and optional shopUsername (leading @ stripped; omitted when blank). Not goalSats.
  • 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 throws Could not post your message. On 403 (the post needs a Bitcoin payment) throws PostFeeRequiredError with Could not post your message.
  • Interaction log: A created note is recorded as post_created with its id, video: true, and whether it is an Ask. The text is never recorded.
  • Used by: ForumLoader submit.

Function: forumVideoSrc

  • Purpose: Build the same-origin forum video path for a message from its MIME type so playback uses .mp4, .webm, or .mov correctly.
  • Inputs: messageId string and optional contentType (video/mp4 | video/webm | video/quicktime | null | undefined).
  • Returns / side effects: /messages/{id}/video.mp4 | .webm | .mov (defaults to .mp4 when type is missing or unknown). No I/O.
  • Used by: ForumBoard playback src when 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: messageId string, optional index (0 or omitted or negative is photo.jpg; 1–9 are photo/{n}.jpg), optional version (a non-empty string appends ?v=).
  • Returns / side effects: The path string. No I/O.
  • Used by: ForumBoard, QuotedForumNote, PublicMessageLoader.
  • Purpose: Client button beside a handbook heading, chapter, screen heading, or figure-card permalink. Copies origin + pathname + #id to the clipboard, sets location.hash, and flashes a check icon for 1.2s (textarea execCommand fallback).
  • Inputs: targetId (DOM id without #) and label (interpolated into handbook.copyLink via useTranslations as { label }). Optional tone ('app' | 'dark', default 'dark'). Copied Check uses text-accent when dark and text-app-fg when app.
  • Visible UI: Idle Link2 icon; copied Check icon. No visible "Copy link" or "Copied" text (title and aria-label keep 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, and ModerateHandbookScreen.

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-side next/link; a hash or another site stays a plain anchor. Every heading has a sibling HandbookCopyLink. A paragraph whose only inline is an image becomes a HandbookFigure (thumbnail, lightbox, deep link) instead of <p><img>.
  • Inputs: markdown string and idPrefix for heading ids.
  • Returns / side effects: React fragment. No network.
  • Used by: HandbookFunctionsPage and HandbookEndpointsPage.

Function: HandbookIntro

  • Purpose: Server-presentational chrome for the /handbook title, intro sentence, and section-nav aria-label (already-translated copy).
  • Inputs: title, introBefore, introAfter, navAria (already-translated strings), headingAction (node beside the h1, e.g. copy-link), and children (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 via getRequestLocale and links to /handbook/screens, /handbook/functions, and /handbook/endpoints without dumping those markdown files. Title copy-link uses handbook.title; intro chrome via already-translated props on HandbookIntro.
  • 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 one Promise.all on mount and retry, ignores stale responses after unmount, and renders StatsDashboard. 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, and fetchWalletStats; a gift-stats failure keeps the existing error and retry state.
  • Used by: StatsPage.

Function: StatsDashboard

  • Purpose: Renders gift KPIs (formatBitcoin(totalSats) plus formatFiatDisplay of the preferred fiat from useFiatPreference; a null fiat total is —, not CHF 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-side next/link (no prefetch). Each of Total spend over time and By month uses SegmentedControl 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) over formatFiatDisplay(satsToFiatAmount(totalSats, rateDay, fiat)), Wallets with balance = formatCount(fundedWalletCount)), the self-reported UTC-day-end caption, and a line/area chart of balanceOverTime[].totalSats with ₿ ticks. The wallet fiat is the current spot from useSpotRate (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 shared OverTimeChart drawing 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, optional posts (null or omitted hides the Posts section), optional wallets (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. With wallets, a Wallets section shows the self-reported wallet totals, the daily chart, and the link See how the wallet is used to /stats/wallet. Reads useFiatPreference and, only when wallets are present, useSpotRate (the spot read of GET /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) and style (NumberFormatStyle).
  • Returns / side effects: Grouped decimal string from formatGroupedNumber with zero fraction digits. No network.
  • Used by: StatsDashboard (wallets with a balance) and WalletUsageDashboard (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 is role="group". The caller supplies formatTick and renderPoint.
  • Inputs: points (OverTimePoint[]), formatTick (axis tick label), ariaLabel, and renderPoint (required marker for one OverTimePointLayout).
  • 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: StatsDashboard for gift spend over time and the /stats wallet balance, and WalletUsageDashboard for wallets with a balance per day.

Function: StatsPage

  • Purpose: Next.js page for /stats. Renders StatsLoader.
  • Inputs: None.
  • Returns / side effects: The statistics screen inside MarketingLayout. Renders StatsLoader.
  • Used by: Route /stats.

Function: WalletUsagePage

  • Purpose: Next.js page for /stats/wallet. Sets metadata through marketingMetadata and renders the marketing main frame with the heading Wallet usage and WalletUsageLoader. 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. Fetches GET /wallets/usage and GET /wallets/stats together, ignores a late answer after unmount, and renders WalletUsageDashboard. 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 fetchWalletUsage and fetchWalletStats. The wallet-stats rejection becomes null and 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 Day FilterMenu and 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 the sm breakpoint up it is the six-column table (From, To, Purpose, Payments, Sats, Fee; hidden below sm, w-full table-fixed text-xs sm:table). Below sm it 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 from useSpotRate beside 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 Day FilterMenu, 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), and loading (boolean).
  • Returns / side effects: React element. Reads useNumberFormat, useFiatPreference, and useSpotRate (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 (ResizeObserver on 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 when spot can price it, otherwise ₿ alone. An amount-mode row shows the same bitcoin figure, with fiat beside it when spot can 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. When spot can 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 (fund or members), accountLabel, flows, startSats, endSats, metric (amount or count), numberFormat, and optional spot (rateDay plus the preferred fiat).
  • Returns / side effects: React element. The SVG and the compact list each have role="img" with aria-label equal to accountLabel. The line under either layout is role="status". No network.
  • Used by: WalletUsageDashboard for 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 (fund or members), days (UTC days in order), and flows (rows for other days are ignored).
  • Returns / side effects: One AccountBalanceDay per day (startSats, inflowSats, outflowSats, endSats). Empty when days is empty. No network.
  • Used by: WalletUsageDashboard for 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 call notFound(). Valid days render DayLoader.
  • Inputs: params Promise { day }.
  • Returns / side effects: The day screen inside MarketingLayout.
  • Used by: Route /stats/[day].

Function: DayLoader

  • Purpose: Client loader for /stats/[day]. Fetches GET /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: day UTC YYYY-MM-DD.
  • Returns / side effects: React element. Calls fetchGiftDay. Reads useFiatPreference and useNumberFormat and passes both into GiftDayTable.
  • 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 required numberFormat (ch / us / de) for ₿ and fiat cells.
  • Returns / side effects: React element. Fourth column header is the selected code; cells use formatBitcoin and formatFiatDisplay with numberFormat. No network.
  • Used by: DayLoader.

Function: FiatPicker

  • Purpose: Four-way CHF | EUR | USD | PHP control, no ₿. Optional shell default 'dark' AND optional tone default 'gift' (unsigned stats and day). The /settings Display row (FiatPreferenceSwitcher) passes tone="neutral" and shell="app". Required ariaLabel (Settings passes catalog profile.fiatCurrency; unsigned stats and day pass Fiat currency). Chart scale stays a separate ₿ | selected fiat control. Unsigned stats / day mounts mean useHydrateSession().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) and onChange; optional shell ('app' | 'dark', default 'dark'); optional tone ('gift' | 'neutral', default 'gift'); required ariaLabel.
  • Returns / side effects: React element. No network.
  • Used by: FiatPreferenceSwitcher (always, signed-in /settings); StatsDashboard and DayLoader when unsigned.

Function: fetchGiftDay

  • Purpose: GET /gifts?day= and parse the per-day gift list payload.
  • Inputs: UTC day string.
  • 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: true only for a real calendar date. No I/O.
  • Used by: GiftDayPage, DayLoader.

Function: proxyGiftsGet

  • Purpose: Same-origin proxy helper for api GET /gifts (forwards day).
  • 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: projectDonateAddress gives <platform username>@<request host>, the platform account's own in-app wallet address, shown as a generic lightning: link from lightningHref, for running 21.gifts itself — distinct from /donate forum gifts; without a platform username the section is left out), FAQ, CTAs to /login (Ask for help) and /donate (Send help), plus PwaInstall (tone="dark" placement="hero") after Send help, all via translate for the negotiated locale. HomeShops sits under the hero, and HappylandSection is the place portrait. The same page is /, /en, /de, /es, and /fil.
  • Inputs: None. Calls getRequestLocale() and reads the request host (x-forwarded-host first, then host, without a port); only 21.gifts and its subdomains are taken from the request, any other or missing host yields 21.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 locale cookie 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, or fil).
  • Returns / side effects: Sets document.cookie to locale=<code>; Path=/; Max-Age=31536000; SameSite=Lax, and appends ; Secure when the page is HTTPS. Returns void. Does not navigate or refresh.
  • Used by: LanguageSwitcher, LanguagePreferenceSwitcher, AccountPreferenceSync, and LocaleRouteSync.

Function: readLocaleCookie

  • Purpose: Read the supported language stored in the locale cookie.
  • Inputs: None. Reads document.cookie.
  • Returns / side effects: That locale when the value is exactly en, de, es, or fil; otherwise null (missing or unsupported). Does not write.
  • Used by: LocaleRouteSync and AccountPreferenceSync.

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 on pageshow when persisted is true, a language URL whose cookie differs is stored with writeLocaleCookie when the account has no saved language. On a path without a language prefix, the saved account language is stored with writeLocaleCookie when 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. A pageshow that 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 a locale cookie, 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 (dark for marketing chrome, light for login, donate, unsigned /rules, unsigned /messages/[id], and /view/[viewKey]). Reads current locale via useTranslations and an optional session token from storage. No embedded prop.
  • 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(), then setAccountLocale(token, next, false); failure, a stale generation, or a response for a different account writes no cookie and does not navigate, while success merges only locale onto 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 calls writeLocaleCookie. 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 call router.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 in middleware when the browser opens that URL as a page. The switcher does not watch the path and does not listen for pageshow. LocaleRouteSync aligns 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.label kicker and SegmentedControl tone="neutral" (default one-row rounded-full track, same as ThemeSwitcher) for English / Deutsch / Español / Filipino. Always visible on the signed-in /settings page. Not page chrome, not a Menu disclosure.
  • Inputs: None. Reads current locale via useTranslations and an optional session token from storage. Catalog keys language.label, aria.language. Option labels are native endonyms (not catalogized).
  • Returns / side effects: Settings row matching PushToggle chrome. A same-locale click is a no-op. With a session token, a new locale first calls bumpLocaleGeneration(), then setAccountLocale(token, next, false); failure, a stale generation, or a response for a different account writes no cookie and does not refresh, while success merges only locale onto 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, including Secure on HTTPS, then refreshes as before, while success merges only locale onto the current same-id account before writeLocaleCookie and refreshing. Without a token it does not bump or POST and calls writeLocaleCookie.
  • Used by: SettingsScreen.

Function: NumberFormatSwitcher

  • Purpose: Settings Display row: uppercase numberFormat.label kicker and SegmentedControl 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 /settings page. Not page chrome, not a Menu disclosure.
  • Inputs: None. Reads numberFormat / setNumberFormat from useNumberFormat. Catalog keys numberFormat.label, aria.numberFormat. Option labels are samples from formatGroupedNumber.
  • Returns / side effects: Settings row matching PushToggle chrome. Pressing an option calls setNumberFormat (cookie write via NumberFormatProvider); 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). Optional besideName and belowName place the public role and funding marks on that resting row. Optional onSaved after a successful save.
  • Inputs: Reads useAuthStore. User input: name string. Visitor-facing copy via useTranslations. 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 null when logged out. POST /me/name on save; POST /me/setup/skip on Skip. Merges name, setup, and missing.
  • Used by: NameSetup on /setup/name, MemberProfileScreen on /profile, /members/:id, and /view/:viewKey when the signed-in account id matches, and RequirementsOverlay.

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. Optional startEditing opens the field on mount. User input: location string. Visitor-facing copy via useTranslations (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 uses location.errorRequest. Blank after trim is a valid clear.
  • Returns / side effects: React element or null when logged out. POST /me/location on save or clear. Merges only location so a concurrent name write is not overwritten.
  • Used by: MemberProfileScreen on /profile, /members/:id, /view/:viewKey when the signed-in account id matches. FundingApplyScreen renders it in the apply walk, which every verified account with status none or rejected sees (applications are open).

Function: LocaleProvider

  • Purpose: Client context provider that exposes the negotiated locale and a bound t helper to visitor-facing components.
  • Inputs: locale, messages for that locale, and children.
  • Returns / side effects: React provider element. No network; does not write cookies.
  • Used by: RootLayout wraps every page; consumed via useTranslations (see that function).

Function: NumberFormatProvider

  • Purpose: Client context provider that exposes the negotiated number-format style and a setter that writes the numberFormat cookie. Nest is LocaleProvider → NumberFormatProvider initial={numberFormat} → FiatPreferenceProvider initial={fiat} → ThemeProvider.
  • Inputs: initial (NumberFormatStyle from getRequestNumberFormat) and children.
  • Returns / side effects: React provider element. setNumberFormat writes numberFormat=<id>; Path=/; Max-Age=31536000; SameSite=Lax and ; Secure on HTTPS. Same-id is a no-op when the cookie is already ch/us/de; selecting ch while the cookie is absent still writes so the choice persists.
  • Used by: RootLayout wraps every page; consumed via useNumberFormat (see that function).

Function: FiatPreferenceProvider

  • Purpose: Client context provider that exposes the preferred fiat and a setter that writes the fiat cookie. Nest is LocaleProvider → NumberFormatProvider → FiatPreferenceProvider initial={fiat} → ThemeProvider.
  • Inputs: initial (FiatCode from getRequestFiat) and children.
  • Returns / side effects: React provider element. Syncs in-memory code to initial when that prop changes and no valid cookie is set (locale default after router.refresh() with no cookie). A valid fiat cookie wins over a stale initial. setFiat does not rewrite the cookie when it already equals next; in-memory state still syncs to next if it is stale. Otherwise writes fiat=<code>; Path=/; Max-Age=31536000; SameSite=Lax and ; Secure on HTTPS.
  • Used by: RootLayout wraps every page; consumed via useFiatPreference.

Function: useFiatPreference

  • Purpose: Reads preferred FiatCode and setFiat from {@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.fiatCurrency kicker plus FiatPicker shell="app" tone="neutral" (same chrome as ThemeSwitcher / NumberFormatSwitcher / LanguagePreferenceSwitcher; selected is bg-app-btn, not orange). The only signed-in control that writes the fiat cookie. Unsigned stats and day FiatPickers still write that cookie and keep default tone="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(), then setAccountFiat(token, next, false); failure, a stale generation, or a response for a different account does not call setAccount or setFiat, while success merges only fiat onto the current same-id account before setFiat. Without a token it does not bump or POST and only calls setFiat. Unsigned FiatPicker instances 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 session and account, screen locale, fiat context, preference generations, and the router.
  • Returns / side effects: Returns null; fills explicit null values with onlyIfUnset=true only 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 through writeLocaleCookie and refreshes when readLocaleCookie() is not that language, discards a stale response without replacing the other preference.
  • Used by: RootLayout inside FiatPreferenceProvider.

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: FiatPreferenceSwitcher before 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: FiatPreferenceSwitcher and AccountPreferenceSync.

Function: parseFiatCode

  • Purpose: Accept a raw cookie/option string if it is exactly one of CHF|EUR|USD|PHP; otherwise return fallback.
  • Inputs: value (optional string) and fallback (FiatCode).
  • Returns / side effects: A FiatCode. No side effects.
  • Used by: getRequestFiat, FiatPreferenceProvider.

Function: getRequestFiat

  • Purpose: Cookie fiat if valid; otherwise defaultFiatForLocale(locale). Never writes.
  • Inputs: Request locale.
  • Returns / side effects: FiatCode for 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, and origin + pathname as 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 then navigator.clipboard.
  • Used by: LoginCard (in-app / unsupported branch) and ViewProfileClaim (same branch under the public view card).

Function: LoginCard

  • Purpose: Login UI used both on /login and in place of a signed-in screen through WalletLoginCard: an idle card with the single primary Log in (authenticate-first), an account-choice card after browser NotAllowedError (Log in with existing account / Open a new account), an unknown-passkey card after authenticate finish Unknown credential (heading login.unknownHeading, muted login.unknownBody, Try again as the first control, calling passkey.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 via InAppBrowserView (Open in browser + Copy link, no passkey ceremony). After success, OnboardingGate leaves /login; in WalletLoginCard, 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 greeting login.heldGreeting (Welcome back, {name}, from lockedName) above the heading, the muted line login.heldConfirm (Confirm to open your wallet) directly above Log in, and, below Log in, the muted line login.newHere (New to 21.gifts?) with secondary Open a new account (opens the name form without a passkey prompt); its Log in calls passkey.authenticateHeld (one prompt for the account's wallet passkey, never the account-choice card). When that prompt ends without an answer (walletPasskeyMissed) the card shows login.heldPasskeyMissed above 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 with login.error above Log in (a refused account shows login.wrongAccount and keeps the held session, and the next Log in clears that hint); heldProblem from WalletLoginCard shows wallet.prfUnsupported (noPrf) or login.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 uses login.error plus Try again, except a wrong-account 403 (wrongAccount or passkey error equal to that api string) which uses login.wrongAccount with the same layout. Try again on that hint calls clearWrongAccount then passkey.login (never retry, so it cannot create another account). Generic errors still call passkey.retry. When a new account's passkey gives no PRF output (passkey.error is wallet.prfUnsupported), the alert is wallet.prfUnsupported (This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.) instead of login.error; Try again still calls passkey.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 muted login.iosVersion line (installed version and minimum iOS 18). When the mounted user agent is Android below 9, Start, Choice, and Unknown show a muted login.androidVersion line (installed version and minimum Android 9). iOS is chosen when both would match. The alert is that same sentence when passkey.error is login.iosVersion or login.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, and InAppBrowserView. Optional heldProblem (noPrf / failed / null) from WalletLoginCard. Optional showRecover (default true; WalletLoginCard passes false).
  • 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 showRecover is true (WalletLoginCard passes 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 through WalletLoginCard today, 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 secondary ButtonLink as its third control, and the unknown-passkey card adds the same control under its buttons. When passkey.recoveryPending is set (authenticate finish answered 409 recovery_pending), the error view shows login.recoveryPending with Try again (passkey.retry) and the same Recover account via Social Recovery link under it, whatever showRecover is, 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 is login.recoveryPending instead of login.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. Status closed (api logins_closed) or outdated (api app_outdated) shows LoginBlockedNotice instead of every other view, also over a held-back session, which stays held.
  • Used by: Screen /login and WalletLoginCard.

Function: WalletLoginCard

  • Purpose: Shows the ordinary LoginCard in 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 session and lockedSession, visualPin, and finishWalletOpen.
  • Returns / side effects: A LoginCard, given the last wallet-open problem as heldProblem and showRecover={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 /login card has; a passkey of an unfinished social recovery still shows login.recoveryPending with 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 lets OnboardingGate reveal the screen and background setup proceeds independently. Failure calls lockSession: noPrf shows wallet.prfUnsupported, another failure or a cancelled wallet-opening prompt shows login.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 shows login.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 /login while the wallet is not open) and ViewProfileClaim (after Log in instead on the public profile).

Function: LoginPage

  • Purpose: Next.js page for /login. The visible heading lives in LoginCard (login.heading).
  • Inputs: None.
  • Returns / side effects: AppShell with ProfileChromeLeft (wordmark HomeWordmark: / unsigned, /welcome when a session is hydrated) and LanguageSwitcher top-right, wrapping OnboardingGate around LoginCard. The arrow returns to the previous in-app view, or /welcome when 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: AppShell with ProfileChromeLeft (wordmark HomeWordmark: localizedPublicPath(locale, '/') when unsigned, /welcome when a session is hydrated) and LanguageSwitcher top-right; heading, lead, Open the forum ButtonLink. The arrow returns to the previous in-app view, or /welcome when 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, and missing into the auth-store account.
  • Inputs: chapters — ordered server-rendered RulesDocument elements (one per RULES_CHAPTER_IDS id).
  • 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, a next/link to /terms labelled nav.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 /terms lands 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 /welcome when this tab has none, through goToPreviousView with 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-agreement via agreeToRules only on the last chapter. Renders null without a session or when chapters is empty.
  • Used by: Screen /setup/rules.

Function: RulesSetupPage

  • Purpose: Next.js page for /setup/rules.
  • Inputs: None. Calls getRequestLocale() / getCatalog for the rules body.
  • Returns / side effects: Fill AppShell (align="start") with SignedInChrome top-right, a fallback ProfileChromeLeft top-left (shown only while OnboardingGate shows the login card in place of RulesSetup, whose AppShellTopLeft arrow replaces it otherwise), and OnboardingGate around RulesSetup (RULES_CHAPTER_IDS mapped to RulesDocument chapters, showNav={false}, chapter={id}). RulesSetup portals the one top-left arrow: chapter 0 returns to the previous in-app view, or /welcome when 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, and logLogout.
  • 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, records logout and 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 calls returnToView('/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: SignedInChrome Menu dropdown, SettingsScreen.

Function: NameSetup

  • Purpose: Display-name form when account.setup === 'name'.
  • Inputs: None besides NameForm store reads.
  • Returns / side effects: Heading Your name at the top and NameForm (variant="onboarding") with Continue at the bottom of the screen. No LogoutButton.
  • 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.gifts username. 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: AppShell with ProfileChromeLeft top-left (non-link Wordmark span) and SignedInChrome top-right, and OnboardingGate around UsernameSetup. The arrow returns to the previous in-app view, or /welcome when this tab has none.
  • Used by: Route /setup/username.

Function: NameSetupPage

  • Purpose: Next.js page for /setup/name.
  • Inputs: None.
  • Returns / side effects: AppShell with ProfileChromeLeft top-left (non-link Wordmark span) and SignedInChrome top-right, and OnboardingGate around NameSetup. The arrow returns to the previous in-app view, or /welcome when 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 https login url, and optional SystemBrowserHost (win; defaults to globalThis.window). Missing window is a no-op.
  • Returns / side effects: On Android, sets location.href to a Chrome Intent URL with an encoded fallback. Else if Telegram.WebApp.openLink is a function, calls it. Else on iOS Telegram (JS bridges or UA Telegram), sets location.href to x-safari- + url. Otherwise calls host.open(url, '_blank', 'noopener,noreferrer'). No network of its own.
  • Used by: InAppBrowserView Open in browser (via LoginCard and ViewProfileClaim), the /login and /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 optional allowGuest. Members use screen="profile". /wallet and /loans/repay use screen="wallet". /welcome, /statistics, and /habit-tracker pass allowGuest.
  • Returns / side effects: After hydration, returns WalletLoginCard instead of children while useWalletOpen is false for an account or lockedSession exists; it does not redirect until the wallet is open. Then it returns children on the correct onboarding screen, otherwise a spinner while returnToView follows nextOnboardingPath (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. /wallet itself stays on screen when setup is '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 gets WalletLoginCard. 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 to loginHref of that screen (/login?next=…, plain /login for the forum home). Other redirect targets are /setup/name, /setup/username, /setup/rules, or /welcome. On /login a fresh login is sent on only once its wallet is open; until then, and while a session is held back, /login shows WalletLoginCard in 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 (nextOnboardingPath is /welcome) opens loginReturnPath of the login page's query (the next view) instead of /welcome when that is a safe in-app path; a missing or unsafe next keeps /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 children unchanged. metadata.robots is { 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 (lucide Menu 24px in text-app-fg, accessible name aria.menu, no visible word). While the move-funds sheet is open the Menu closes and its trigger and panel host are inert, 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 with MenuAccountHeader (photo, name, @username, balance) and a divider, then icon+label dropdown rows (Home /welcome lucide Home nav.home first — an unmodified primary click first clears this tab's in-app view stack with resetViewHistory, then the link opens /welcome client-side (no document load, so the open wallet stays); when the path is already /welcome, Home preventDefaults, records the current /welcome path as the only view with recordCurrentView, and dispatches FORUM_HOME_EVENT instead 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, lucide Wallet, wallet.balanceHeading); Shops (/shops, lucide Store, nav.shops); Point of sale (/pos, lucide Banknote, pos.nav); User Profile (/profile, lucide User, profile.title) with no given or received amounts; Grants (/grants, lucide HandCoins, nav.grants) for every signed-in member; Account security (/security, lucide ShieldCheck, nav.security); Settings (/settings, lucide Settings, nav.settings); ScrollText Living room rules /rules; Habit-Tracker (/habit-tracker, lucide ListChecks, nav.habitTracker); Trust Chain; Statistics (/statistics, lucide BarChart3, nav.statistics) for every signed-in account, immediately after Trust Chain, with no unread count; Moderation (/moderate, lucide Shield, nav.moderate) only when roleAtLeast(account?.role, 'moderator') — aria-label nav.moderateUnread with { count } when moderationUnreadCount > 0 (staff-room unread plus open-proposal count) else nav.moderate; visible nav.moderate plus ml-auto tabular-nums count when > 0; Notifications (/notifications, lucide Bell, nav.notifications, unread count ml-auto only when unreadCount > 0, aria-label nav.notificationsUnread then); Messages /messages (nav.inbox, unread count ml-auto only when inbox unread > 0, aria-label nav.inboxUnread then); MessageCircle Contact /contact; optional Download Install app via PwaInstall placement="menu" when install is offered; LogOut log out; then a quiet Version line (app.version, getAppVersion())). On mount with a session, calls resyncPushSubscription. Clicking Notifications asks for OS permission via enablePush when it is not already granted and Service Worker plus PushManager exist (otherwise resync, which no-ops without those APIs). On the forum home (/welcome) only, when account.setup is null and account.hasPosted is false, also mounts IntroduceYourselfOverlay; it never covers /wallet, /wallet/*, /pos*, /profile*, /messages*, the setup flow, or any other screen (Close dismisses this mount only; Write an introduction calls requestForumCompose, so the next mount starts with the dialog dismissed). On the same screen, and only there, it mounts SocialRecoveryPromptOverlay for a grant member (account.funding.status admitted or trial) whose socialRecoverySetUp is false (missing on an older api shows nothing) while account.setup is 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 account and session from useAuthStore, lockedSession, wallet-open state from useWalletOpen, and the path from usePathname. The introduce overlay and the social-recovery prompt mount only on /welcome. Home clears the view stack through resetViewHistory and recordCurrentView. Push resync uses resyncPushSubscription. Composes useUnreadCount(open) (writes the home-screen badge), PwaInstall (placement="menu", closes the Menu via onMenuAction), and LogoutButton inside the Menu dropdown. Renders nothing, and starts none of those reads, while lockedSession is set or the wallet is not open.
  • Returns / side effects: A flex items-center row with the relative Menu button (44×44, round, hover:bg-app-hover, the same background while aria-expanded is 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; until frameWidth is measured, matchMedia('(max-width: 36rem)'), and a missing matchMedia counts as wide): it portals to the trigger parent as absolute 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 uses mt-0, px-2 py-0, and the version line uses py-0. Rows stay min-h-11. If that compact panel still passes the window and a non-negative lift keeps the bottom inside, it is a fixed overlay. Its style sets the measured top, left, and width so the bottom sits on the window and the top is never less than 0. That left is 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 is relative 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 to mt-2 and p-2 only when the compact box still has 48px of room under the window, so the two layouts do not alternate. The scrim #signed-in-menu-scrim portals to [data-menu-scrim-host] inside [data-app-frame] as absolute inset-0 z-40 rounded-3xl (the radius is set on the scrim; the host is display: contents, so inherit would 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 as w-full and stays in that host while closed (hidden), reads the scrollport scrollTop before it sets html[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. While html[data-menu-sheet='1'] is set, the host is height: 100% with padding-bottom: 1.25rem and the panel max-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 carries data-scrollport and is bound with bindScrollport in 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 with releaseScrollport and clears its data-scroll-active / data-scroll-locked marks, and the page port is active again. The panel is not wrapped in Scrollport, which would bind for as long as the panel is mounted. Not a body portal. PwaInstall stays mounted via the hidden class when closed. When open: MenuAccountHeader (mounted with the panel, also while closed, so its data loads when the chrome mounts; tight follows the compact wide layout; following its balance link closes the Menu) and an aria-hidden border-t divider 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, lucide Home, nav.home) first, Balance (/wallet, lucide Wallet, wallet.balanceHeading), Shops (/shops, lucide Store, nav.shops), Point of sale (/pos, lucide Banknote, pos.nav), Profile link (/profile, lucide User, profile.title) with no given or received amounts, Grants (/grants, lucide HandCoins, nav.grants) for every signed-in member, Account security (/security, lucide ShieldCheck, nav.security), Settings (/settings, lucide Settings, nav.settings), Living room rules (/rules), Habit-Tracker (/habit-tracker, lucide ListChecks, nav.habitTracker), Trust Chain (/trust-chain), Statistics (/statistics, lucide BarChart3, nav.statistics) for every signed-in account, immediately after Trust Chain, with no unread count, Moderation (/moderate, lucide Shield, nav.moderate) only when roleAtLeast(account?.role, 'moderator') — aria-label nav.moderateUnread with { count } when moderationUnreadCount > 0 (staff-room unread plus open-proposal count) else nav.moderate; visible nav.moderate plus ml-auto tabular-nums count when > 0, Notifications (/notifications, lucide Bell, 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. Local useState dismissed flags for IntroduceYourselfOverlay (initialized from consumeSkipIntroduceOverlay) and SocialRecoveryPromptOverlay (set by its Close); does not write forumLawsDismissed or any account field. It renders nothing and starts none of the Menu's reads while lockedSession is present or useWalletOpen is 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, and retrying), useSpotRate (asked only while the balance is known), useFiatPreference, useNumberFormat, and useIncomingPayment(2400).
  • Returns / side effects: One next/link to /wallet (data-wallet-tour="balance", min-h-9, rounded-lg px-2, hover:bg-app-hover, whitespace-nowrap, an sr-only Balance (wallet.balanceHeading) before the figures). While the balance is on its way (the wallet is connecting, is ready without a balance yet, or is at error with retrying because it is opened again in the background), a skeleton stands in its place: a div with the link's box (mr-1 min-h-9 px-2, right-aligned column) and two bars in the Menu's skeleton look (SKELETON_CLASS from MenuAccountHeader: bg-app-border, animate-pulse, still with reduced motion), one in a 17.5px row and one in a 12.5px row, the heights of the two text lines, so the header does not move when the amount replaces it. The skeleton is aria-hidden (the screens that need the wallet announce its state themselves, so the header does not announce it a second time), carries data-balance-skeleton, is not a link, and does not carry data-wallet-tour. null without 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 is text-app-success and an aria-hidden text-[10px] line under it shows + plus formatBitcoin (+₿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-10 round) or, without one, the first letter of the name (else of the username) in a round bg-app-border badge; the display name (text-sm semibold) and @username (text-xs muted), both truncated. The photo or initial and the name block are together one next/link to /profile (the same target as the Menu's Profile row) that closes the Menu: its accessible name starts with nav.openProfile (Open your profile) from a sr-only span, followed by the name and @username; the photo inside it has an empty alt and the initial is aria-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-visible ring and hover bg-app-hover. It is not nested with the balance link. And in the right corner the wallet balance small: the formatBitcoin amount (text-base semibold) over the default-fiat amount (text-xs muted, empty only without a usable rate), right-aligned and never wrapping, as a next/link to /wallet that 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 name wallet.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. When summarizeLoans reports a payable amount, a rounded-lg bg-app-card row under the first row (gap-3) says Loan repayment due today or the danger-colour You're behind on your loan, shows the stored definedDueLabel(..., '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 (formatBitcoin plus preferredFiatSuffix, bitcoin alone only when the spot is not loaded), and has Send to /loans/repay; onNavigate closes the Menu before navigation. The row is absent when nothing is payable. Compact (tight) adds mt-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, and open (whether the Menu is open). Reads session and account from useAuthStore, the stored session (loadSession), useWallet, useMyLoans, useSpotRate, useNumberFormat, and useFiatPreference.
  • Returns / side effects: The card while the Menu is open, or null while 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 reloads useMyLoans once, 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 round h-10 w-10 skeleton for the photo, skeleton bars in the h-5 name line and the h-4 @username line (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 only GET /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. useMyLoans supplies 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: AppShell with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate around ProfileScreen.
  • 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 /welcome when 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 a next/link: it opens that view with the client-side router, never with a document load, so tab memory such as the open wallet stays. Optional onBackClick runs on an unmodified click and returns true when it took an in-page step (wallet hides the words, closes a send step, or returns from Send or Receive to the wallet home); false lets the arrow leave. Optional wordmark replaces the default wordmark. Optional wordmarkHref defaults to /welcome and is ignored when wordmark is set. tone="dark" is the ink marketing header. hideHistoryArrow omits the history arrow whatever this tab's view stack holds (/welcome); a wizard override still shows, unless hideOverride is set as well, which leaves no arrow at all (the root info page /).
  • Inputs: Optional onBackClick (() => boolean), wordmark, wordmarkHref, tone, hideHistoryArrow, and hideOverride; catalog via useTranslations; previous path via previousViewPath.
  • Returns / side effects: A link (profile.back when this tab has no earlier view, otherwise nav.back), the override button, or no arrow when hideHistoryArrow is set and no override is armed or hideOverride hides it, plus the wordmark. The first client render matches SSR (/welcome, profile.back) unless hideHistoryArrow hides that arrow. An unmodified primary click calls onBackClick first; when it returns true the link does not follow its href. Otherwise, when this document pushed the current entry on top of that view (takeStepBack) and ViewHistoryRoot provides its back step, the click takes that step (router.back()), so the arrow and the browser's back agree; else it marks the href with markBackNavigation and 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 /wallet Back, via AppShellTopLeft), ShopsPage, GrantsPage, FundingApplyPage, MemberProfilePage (/members/[accountId]), ContactPage, MessagesPage (via MessagesChromeLeft), MessagesChromeLeft, NotificationsPage, ModeratePage, HiddenNotesPage, ProposalsPage, FundingApplicationsPage, FundingApplicationDetailPage, ModeratorGroupPage, TrustChainPage, RulesPageChrome, PublicMessageChrome. WalletPage mounts WalletChromeLeft as page topLeft; the card's registration wins while Wallet is shown.

Function: resetWalletReturn

  • Purpose: Clear the stored /wallet return path. The top-left arrow does not read this slot. It returns to the previous in-app view in this tab, or /welcome when this tab has none.
  • Inputs: None.
  • Returns / side effects: void. Drops the shared tab slot and sessionStorage key 21gifts.walletReturn. Does not touch localStorage.
  • Used by: Wallet return tests, RememberWalletReturn tests, WalletChromeLeft tests (afterEach).

Function: rememberWalletReturn

  • Purpose: Remember a safe in-app path (not Wallet itself) as the /wallet back target. Rejects protocol-relative URLs, .., whitespace, #, overlong paths, and /wallet itself without clobbering a previous good path.
  • Inputs: path string (pathname, optionally with a query string).
  • Returns / side effects: void. Writes a globalThis slot and sessionStorage (21gifts.walletReturn) so every copy of the module in this tab sees the same path. No localStorage. No-op during SSR.
  • Used by: RememberWalletReturn.

Function: walletBackHref

  • Purpose: Read the path rememberWalletReturn stored, or /welcome when 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 sessionStorage the 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.
  • 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 with requestMoveFunds, 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. MoveFundsSheet removes the parameter once the flow opened.
  • Inputs: None. Reads move from useSearchParams (mounted in the root layout inside Suspense).
  • Returns / side effects: null. Calls requestMoveFunds when move is 1. No network.
  • Used by: Root layout.

Function: RememberWalletReturn

  • Purpose: Client recorder mounted in the root layout. On each pathname/search change, calls rememberWalletReturn with the current in-app path. The top-left arrow does not read this slot.
  • Inputs: usePathname and useSearchParams. Non-empty query is appended as ?….
  • Returns / side effects: null. Calls rememberWalletReturn during render and again from an effect. No network.
  • Used by: RootLayout (inside ThemeProvider, wrapped in Suspense).

Function: PushOpenListener

  • Purpose: Listens for 21gifts-push-open from the service worker and calls router.push only 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 the 21gifts-push-open cache (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: MessageEvent on navigator.serviceWorker, plus a JSON { url, at, id } cache record at /push-open/{id}. Accepts only data.type === '21gifts-push-open' with a string data.url that 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 with router.push when the path is a same-origin in-app URL; ignores anything else. No network.
  • Used by: RootLayout (inside ThemeProvider, after AccountPreferenceSync).

Function: WalletChromeLeft

  • Purpose: Page /wallet and /loans/repay chrome. Renders ProfileChromeLeft only. The arrow returns to the previous in-app view in this tab, or /welcome when 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 /messages chrome. Always renders ProfileChromeLeft. 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 /welcome when 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.viewHistory and restores it. An empty store stays missing.
  • Returns / side effects: The previous path, or null on 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 /welcome when 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(), its push and back). Reads previousViewPath and takeStepBack.
  • 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 with markBackNavigation, then push of the previous path, or push('/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. resetViewHistory drops 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 pushState is a push, even when history.length does not grow. A URL-changing replaceState replaces 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 stampHistory defaults to true. False updates the stack and does not write giftsView, so the history entry being left keeps its stamp.
  • Returns / side effects: Updates the module slot and sessionStorage (stack and cursor, plus base after a capped drop). When stampHistory is true, stamps giftsView with history.replaceState without pushing a history entry. A stored stack that contains an unsafe path is ignored. Each stamp also writes giftsBelow (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-URL replaceState without its own giftsView (Next's refresh) keeps the entry's giftsView and giftsBelow. 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(), its back and replace).
  • 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) calls router.replace(path); recordCurrentView then 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 /login after a recovery done before), useRemainingBalance (Done and the removal back to /security), and every in-app redirect that used router.replace: OnboardingGate (/login carrying the gated screen, the next view after login, and the next onboarding step), LogoutButton (/login), ViewProfileClaim (the next onboarding step), ForumLoader (/login carrying the current view, /setup/rules), and ProfileScreen, MemberProfileScreen, MemberProfileLoader, FundingApplyScreen, ShopTable (/setup/rules).

Function: loginHref

  • Purpose: Build the /login href 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 /login for / and /welcome (where a finished login lands anyway), for /login itself, and for any path that is not a safe in-app path (the same rule as loginReturnPath). 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 /statistics Log in link. LogoutButton and RecoverScreen open a plain /login on purpose.

Function: loginReturnPath

  • Purpose: Read the view /login was 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 next path, or null. 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 /login itself (with or without a query or subpath). //evil.com, a backslash path, https://…, javascript:…, /login?next=…, /./login, and an empty value are null. No storage, no network.
  • Used by: OnboardingGate (the login screen, once the wallet is open and setup is finished; null keeps /welcome).

Function: canStepBack

  • Purpose: Preview whether a plain click toward a path will step back with router.back(). Same conditions as takeStepBack, without clearing the claim, so the arrow can still claim the step on the same click. ShopsScreen uses 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 takeStepBack would tell the caller to call router.back(). Does not clear pushed. 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 pushed flag, and the caller then calls router.back(). The current entry must also carry this document's stamp for the current view (giftsView and giftsBelow), 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 as giftsBelow (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 /welcome until 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 removes 21gifts.viewHistory from sessionStorage. 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 /welcome when this tab has none. One arrow. The wordmark is not that control.
  • Inputs: children — the page tree.
  • Returns / side effects: ChromeBackProvider around children, with router.back() as its stepBack. A location recorder writes the stack during render without stamping history, and stamps giftsView from 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 from window.location.search when 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, inside ThemeProvider, beside RememberWalletReturn.

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 (label nav.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 ChromeBackProvider context when it is present.
  • Returns / side effects: { override, setOverride, stepBack }; stepBack is the root's router.back(), or null without ViewHistoryRoot. 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; optional stepBack, the client-side back step the arrow takes (default null).
  • Returns / side effects: Context provider. Each caller has its own slot. useChromeBack hands out stepBack. 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-sm identity card showing the public profile a visitor sees on /members/:id, plus edit controls, with a resting header (round profile photo from GET /pictures/me and wide image from GET /banners/me when 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, then LoanBalanceChart directly under it (same failed flag; missing loan fields → nothing drawn / saldo 0), About me (AboutMeSection owner: empty prompt + Write your About me, or filled text and/or photo + edit; Languages Translate on the filled read-only text when aboutMessageId is 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 sends role: 'software_developer') and the funding-program icon, then location, then the same public facts a visitor sees on /members/:id and 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 shows forum.loading on the card. The signed-in menu Profile row shows no amounts. Back + wordmark live in ProfileChromeLeft.
  • Inputs: Session and account from useAuthStore. One MemberProfileScreen (no factsOnly, no omitPills). 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 via useTranslations. Preferences stay on /settings. The owner About me editor inside MemberProfileScreen passes omitEmptySlotAdds and imageEpoch, 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 account viewKey as shareViewKey, 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.chartEmpty with no chart FiatPicker, no SVG / no ₿|fiat scale; loan empty or in-flight renders nothing; a thrown activity load shows profile.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 is funding-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 failed fetchMember shows forum.error and Try again and leaves the editors up. MissingRequirementsError goes to /setup/rules with returnToView. No Message button and no staff actions. Back + wordmark live in ProfileChromeLeft. 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.empty Tell others who you are. and labeled Write your About me). Filled means trimmed aboutMe is a real bio (not the display name) or hasPhoto is true. Owner mode can edit (write / pencil, save, cancel) via onSave. 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 via prepareForumPhoto, no video), the round profile photo, and the wide image. When omitEmptySlotAdds is 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.copyLink Copy link to this profile) when profileUrl is set; the URL is never shown as visible text. Public mode with no filled text, no photo, and no copy URL renders null. A filled read-only body uses TranslatableNoteBody when messageId is a non-empty string; otherwise LinkedText. The editor is not translatable.
  • Inputs: aboutMe (string | null), mode (owner | public), optional name (string | null) for the filled comparison ((name ?? '').trim(); blank name applies only the trimmed-non-empty check), optional hasPhoto, optional loadPhoto (() => Promise<Blob>), optional profileUrl, optional messageId (stored About me note id; omitted or blank keeps LinkedText), optional onSave(text, photo?) (photo omitted keeps, null clears, object sets), optional loadPicture / onSavePicture for the round profile photo and optional loadBanner / onSaveBanner for the wide image (neither is the About me note photo; a non-image blob stays empty), optional startEditing to open the owner editor on mount, optional omitEmptySlotAdds (boolean, default false) to hide empty portrait and wide-image adds, optional imageEpoch (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. Calls onSave on owner save, onSavePicture when the profile photo changes, and onSaveBanner when the wide image changes. Loads a blob URL when hasPhoto and loadPhoto are set and revokes it on unmount. Loads and revokes the profile-photo and wide-image blob URLs the same way when loadPicture or loadBanner is set. imageEpoch reloads those stored slots while the editor stays open.
  • Used by: MemberProfileScreen (owner passes omitEmptySlotAdds and imageEpoch when the account id matches; public otherwise), ViewProfileScreen (public, name={profile.name}), FundingApplyScreen renders it in the apply walk, which every verified account with status none or rejected sees (applications are open), ProfileScreen (owner, name={account.name}, omitEmptySlotAdds).

Function: PushToggle

  • Purpose: Settings Notifications sections (the section heading is profile.push.heading on SettingsScreen): uppercase heading profile.notify.heading, a Hearts On / Off SegmentedControl (profile.push.on / off, group profile.heartNotify.label, fullWidth false), and one compact Posts SegmentedControl (fullWidth false, group profile.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, heading profile.device.heading, shows Notifications On / Off (profile.device.label, not aria.push) only when serviceWorker / PushManager are ready. No Bell / IconButton / trailing slot. Changing the level POSTs /me/notification-level via postNotificationLevel and merges notificationLevel into 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 shows profile.push.level.error. Hearts display account.notifyHearts ?? true; changing them POSTs /me/heart-notifications via postHeartNotifications with { enabled } and merges notifyHearts; a second change while that POST is in flight is ignored; failure keeps the previous value and shows profile.heartNotify.error. The device pill calls enablePush / disablePush; same-value or busy is a no-op. Renders nothing without a session. On iPhone Safari outside standalone, shows profile.push.installHint under the device row.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations; postNotificationLevel, postHeartNotifications, accountNotificationLevel, and setAccount; enablePush, disablePush, pushRenewalPending, pushTurnedOff, isIosSafari, and isStandaloneDisplay.
  • 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 section profile.device.heading with Notifications On/Off. Level change calls postNotificationLevel then merges notificationLevel; Hearts change calls postHeartNotifications then merges notifyHearts; On calls enablePush when not subscribed, Off calls disablePush when subscribed; may show profile.push.unavailable on push failure, profile.push.level.error on level failure, or profile.heartNotify.error on 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, plus GET /conversations/moderator-group and GET /trust/proposals when roleAtLeast(account?.role, 'moderator')). refreshKey retriggers the fetches (Menu open). Does not mark notifications or conversations read.
  • Inputs: refreshKey boolean; optional options?: { writeBadge?: boolean } (omit the object to default). Default writes the home-screen badge. writeBadge: false fetches and returns the four counts but does not call setUnreadAppBadge (including the logout / session-null 0 write).
  • Returns / side effects: { unreadCount, inboxUnreadCount, moderationUnreadCount, proposalCount }. unreadCount is the notifications unread count. inboxUnreadCount is the number of conversation rows with unread: true. proposalCount is the open-proposal list length. moderationUnreadCount is staff-room unread (0 or 1) plus proposalCount, for the Menu Moderation row. Hub Open proposals uses proposalCount alone. When badge writes are enabled (the default), the home-screen badge is notification unread + inbox unread + staff-room unread (0 or 1) — 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 contributes 0. A thrown staff-room or proposals fetch contributes 0 without failing the other sides. Either of the other sides failing contributes 0 to the sum; the other sides still write. Epoch skip applies to that sum write. No session → all four counts 0; badge 0 only when writes are enabled and loadSession() === null (real logout). A hydrating store (session null, 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). When count > 0 and setAppBadge exists, sets that number; otherwise clears when clearAppBadge exists. 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 (0 or 1). 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 setUnreadAppBadge if 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 (0 or 1). Signature refreshUnreadAppBadge(sessionToken, inboxUnreadOverride?, moderationUnreadOverride?). Fetches GET /forum/notifications and, unless an inbox override is passed, GET /conversations. When the moderation override is omitted, fetch GET /conversations/moderator-group only when roleAtLeast(account?.role, 'moderator') (unread true → 1, else 0; throw/404 → 0); a role below moderator contributes 0 without 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 or loadSession() is not still sessionToken. Never rejects.
  • Inputs: sessionToken (string). Optional inboxUnreadOverride (number) — when set, skip the conversations fetch and use that inbox unread count (e.g. the local list after mark-read). Optional moderationUnreadOverride (number) — when set, skip the staff-room fetch and use that count (0 or 1). 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>. Calls setUnreadAppBadge with the sum only when the epoch is unchanged and loadSession() === sessionToken. Fire-and-forget safe.
  • Used by: InboxLoader after a successful thread load and mark-read (inbox override only; fetches staff-room only when the account is at least moderator). ModeratorGroupScreen after opening the room (moderation override 0).

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, including moderator_proposal, is null.
  • Inputs: type, parentId, and replyId.
  • Returns / side effects: Tag string or null. No network.
  • Used by: NotificationsLoader before it closes the local banner for a row that is not a proposal, and ForumLoader after the welcome appointment pill's markNotificationRead succeeds.

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 on ready.
  • Inputs: None. Uses navigator.serviceWorker when it exists.
  • Returns / side effects: The endpoint string, or undefined when Push APIs are missing, the lookup rejects, or the endpoint is empty. Never throws.
  • Used by: markNotificationRead, markAllNotificationsRead, markNotificationsReadForMessage, and markVisibleForumNoteRead.

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 on ready.
  • Inputs: Tag strings. An empty list is a no-op.
  • Returns / side effects: Nothing. Missing serviceWorker or getNotifications is a no-op. Never throws.
  • Used by: markAllNotificationsRead, markNotificationsReadForMessage, markVisibleForumNoteRead, NotificationsLoader when a row is opened, and ForumLoader after the welcome appointment pill's markNotificationRead succeeds.

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: enablePush only. disablePush and resyncPushSubscription look up an existing registration with getRegistration() and never register the worker.

Function: push service worker

  • Purpose: Push-only service worker at /sw.js. A payload whose type is dismiss closes the named tags, shows and closes a silent dismiss-ack, sets the badge to max(0, floor(unreadCount)) including 0, and returns before the Sunday check. On the device's local Sunday, a push whose type is not exactly conversation does not stay on screen and does not change the badge: it calls showNotification with tag sunday-quiet and closes that note in the same waitUntil, so the browser does not invent its own banner. Every other push, including a private message, shows a notification (registration.showNotification) and, when navigator.setAppBadge (or registration.setAppBadge as fallback) exists, sets the home-screen badge: floor payload.unreadCount first, use it when that integer is greater than 0, otherwise 1. setAppBadge rejections are swallowed so waitUntil still follows showNotification. Missing setAppBadge still shows the notification. A thrown weekday lookup does not pause notifications. No asset or offline cache. A notification click stores a short-lived 21gifts-push-open entry so a reloaded page can still open the path when postMessage was missed. On pushsubscriptionchange the worker subscribes again with the lost subscription's application server key (skipped when the browser already supplies newSubscription or 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 open SignedInChrome runs resyncPushSubscription(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 event with optional JSON payload (type, title, body, url, tag, tags, unreadCount).
  • Returns / side effects: When type is dismiss, closes the named tags, shows and closes a silent dismiss-ack, sets the badge to max(0, floor(unreadCount)) when unreadCount is finite, and returns before the Sunday check. On a non-conversation Sunday push, event.waitUntil shows and closes sunday-quiet. Otherwise event.waitUntil of showNotification plus optional setAppBadge via Promise.all. Install skips waiting; activate claims clients. Notification click closes the note, stores the in-app path in the 21gifts-push-open cache, 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 with navigate when that function exists and the URL differs (rejection or null still focuses), otherwise clients.openWindow opens the href. No window: clients.openWindow on the same-origin href. Empty, invalid, or foreign data.url becomes /welcome.
  • Used by: Browser Web Push runtime (registered by registerPushWorker).

Function: isStandaloneDisplay

  • Purpose: Detect installed / standalone display mode (display-mode: standalone or iOS navigator.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: PushToggle only.

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: userAgent string (navigator.userAgent).
  • Returns / side effects: { installed, required } where required is 18 and installed is major.minor or major.minor.patch, or null. No network and no DOM writes.
  • Used by: LoginCard (muted line after mount) and usePasskeyLogin (a new account that cannot finish fails with login.iosVersion and is not stored).

Function: iosInstalledVersion

  • Purpose: Read the installed iOS version from an iPhone, iPad, or iPod user agent, including iOS 18 and newer. iosPasskeyBlock still returns null on those newer versions.
  • Inputs: userAgent string.
  • Returns / side effects: Installed string (major.minor or major.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: userAgent string.
  • Returns / side effects: { installed, required } where required is 9 and installed is major, major.minor, or major.minor.patch, or null. No network.
  • Used by: LoginCard (muted line after mount) and usePasskeyLogin (a new account that cannot finish fails with login.androidVersion and is not stored).

Function: androidInstalledVersion

  • Purpose: Read the installed Android version, including Android 9 and newer. androidPasskeyBlock still returns null on those newer versions.
  • Inputs: userAgent string.
  • 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.userAgent plus isStandaloneDisplay and isInAppBrowser. Does not call isIosSafari.
  • 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-step role="dialog" sheet (Share → Add to Home Screen → if Open as Web App is shown, leave it on). On Chromium, listens for beforeinstallprompt (preventDefault, store event), shows the control, and on click calls event.prompt() then drops the event (hides) regardless of accepted/dismissed; appinstalled also hides. Placements: header (compact secondary), hero (secondary md), menu (SignedInChrome Download + label row).
  • Inputs: placement (header | hero | menu); optional tone (app | dark, default app); optional onMenuAction (menu row closes the Menu after click). Catalog via useTranslations.
  • Returns / side effects: Install button and optional iOS sheet, or null. No new dependencies; Tailwind only.
  • Used by: MarketingHeader (tone="dark" placement="header"), Home hero (tone="dark" placement="hero"), SignedInChrome Menu (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-off flag a previous Off stored. Shares a serial queue with resyncPushSubscription and disablePush; a later disable no-ops a queued enable.
  • Inputs: sessionToken.
  • Returns / side effects: void. Throws Notification permission denied or Push is not configured (and other api errors).
  • Used by: PushToggle, SignedInChrome.

Function: resyncPushSubscription

  • Purpose: When Notification.permission is already granted, a service worker is already registered (getRegistration(); never registers one), and a local pushManager subscription exists, fetch the current VAPID key and POST that endpoint to the api. When the subscription's options.applicationServerKey differs 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 stores 21gifts-push-renew in localStorage and removes it after a successful POST, so when subscribe() 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 not granted, it removes a pending marker, so granting permission later does not subscribe on its own. With subscriptionChanged true (the worker's 21gifts-push-subscription-change message), a missing local subscription is not an opt-out either: the worker could not subscribe again, so the resync stores the 21gifts-push-renew marker before it fetches the key and subscribes with the current key. While disablePush's 21gifts-push-off flag is set (Off or log out in this or another tab, until enablePush), 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, after subscribe(), and after each POST, and finishes the Off for whichever subscription it holds then. Never calls requestPermission. 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 with enablePush and disablePush; a later disable no-ops a queued resync so it cannot POST after DELETE.
  • Inputs: sessionToken; optional subscriptionChanged (default false).
  • Returns / side effects: void. Without granted permission, only removes a pending 21gifts-push-renew marker. While 21gifts-push-off is set, only DELETEs and unsubscribes a subscription still present. No-op when Push APIs are missing, no worker is registered, or getSubscription() is null with no pending renewal and no reported change. Throws api errors from fetchVapidPublicKey / postPushSubscription without unsubscribing, the browser's PushManager.subscribe rejection, and Invalid subscription when a new subscription omits endpoint or keys.
  • Used by: SignedInChrome (mount, Notifications click when permission is already granted, and the worker's 21gifts-push-subscription-change message).

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-renew in localStorage). The next resync finishes it unless push is turned off, so the device counts as subscribed until then. Counts only while Notification.permission is granted, because without it the resync cannot finish the renewal.
  • Inputs: None (reads Notification.permission and localStorage).
  • 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-off in localStorage, stored by disablePush and removed by enablePush). 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 then unsubscribe() 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 pending 21gifts-push-renew key renewal and stores 21gifts-push-off at once (log out waits only briefly for the queue), and clears the renewal again inside the queue. No-op when serviceWorker is missing, no worker is registered, or there is no subscription, so log out never installs a worker. Local unsubscribe() still runs if the api DELETE fails.
  • Used by: PushToggle and LogoutButton.

Function: fetchVapidPublicKey

  • Purpose: GET /push/vapid-public with the bearer session and return the VAPID public key string.
  • Inputs: sessionToken.
  • Returns / side effects: string. Throws Push is not configured on 503; other non-2xx throw with status.
  • Used by: enablePush, resyncPushSubscription.

Function: postPushSubscription

  • Purpose: POST /me/push-subscriptions with bearer + { endpoint, keys } and validate the response.
  • Inputs: sessionToken, subscription endpoint + p256dh/auth keys.
  • Returns / side effects: void. Throws Push is not configured on 503; 400 uses api error when present.
  • Used by: enablePush, resyncPushSubscription.

Function: deletePushSubscription

  • Purpose: DELETE /me/push-subscriptions with bearer + { endpoint }.
  • Inputs: sessionToken, endpoint.
  • Returns / side effects: void. 404 is success (already gone). Throws Push is not configured on 503.
  • Used by: disablePush, resyncPushSubscription (old endpoint after a VAPID key change).

Function: proxyPushVapidPublicGet

  • Purpose: Bearer proxy GET /push/vapid-public to the 21.gifts api.
  • Inputs: Incoming Request with Bearer session.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /push/vapid-public.

Function: proxyMePushSubscriptionsPost

  • Purpose: Bearer proxy POST /me/push-subscriptions to the 21.gifts api.
  • Inputs: Incoming Request with Bearer session and JSON body.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/push-subscriptions.

Function: proxyMePushSubscriptionsDelete

  • Purpose: Bearer proxy DELETE /me/push-subscriptions to the 21.gifts api.
  • Inputs: Incoming Request with Bearer session and JSON body.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route DELETE /me/push-subscriptions.

Function: manifest

  • Purpose: Next.js MetadataRoute.Manifest for installable 21.gifts (/manifest.webmanifest).
  • Inputs: None.
  • Returns / side effects: Manifest with name/short_name 21.gifts, start_url /welcome, display standalone, theme/background colors, apple-touch-icon at 180×180, plus icon-192.png and icon-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 from useFiatPreference (the Settings Display row when signed in, otherwise the cookie or the locale default). Empty/all-zero sats is profile.chartEmpty role="status" (no SVG, no ₿|{fiat} scale). Empty/all-zero sats and failed show profile.chartError (role="alert", text-app-danger) instead of profile.chartEmpty. In-flight and successful empty stay profile.chartEmpty, never Loading…. Null usd/cumulativeUsd with 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 is ActivityScale 'sat' | 'fiat'. Ticks: sat formatBitcoin; fiat formatFiatTick (USD may use formatUsdTick); em dash when fiatUnsummable holds for both series (USD: any raw cumulativeUsd is null; other codes: every source cumulative is null). Wrapper role="group" uses profile.chartTitle as aria-label. No title heading; page heading is Profile. Given is donatedOverTime from account activity (no longer a hardcoded zero series).
  • Inputs: received (AccountActivity.receivedOverTime); optional donated (default []) from AccountActivity.donatedOverTime; optional failed (default false).
  • Returns / side effects: When the series is empty or all zeros: profile.chartEmpty (role="status") — no legend, ₿|{fiat} scale, FiatPicker, or SVG — or profile.chartError (role="alert", text-app-danger) when failed. In-flight and successful empty stay profile.chartEmpty, never Loading…. Null usd/cumulativeUsd with 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 the fiat cookie. No network.
  • Used by: MemberProfileScreen and ViewProfileScreen (no route renders ViewProfileScreen).

Function: LoanBalanceChart

  • Purpose: Compact dual-line open-balance SVG of Debt (owedOverTime) and Credit (creditOverTime), mounted directly under AccountActivityChart on the same three profile surfaces. Does not mount FiatPicker. Fiat code comes from useFiatPreference (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 local SegmentedControl 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 and failed show profile.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 via loanAxis and may extend below zero. Fiat ticks are an em dash when fiatUnsummable holds for both series; loan days from the api carry null in 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. Wrapper role="group" uses profile.loanChartTitle. No title heading.
  • Inputs: optional owed (default []) from AccountActivity.owedOverTime; optional credit (default []) from AccountActivity.creditOverTime; optional failed (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 the fiat cookie. No network. Missing API loan fields are already normalized to [] by callers.
  • Used by: MemberProfileScreen (not in factsOnly) and ViewProfileScreen (no route renders ViewProfileScreen).

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). Optional tone app (default) or dark for marketing-ink shells (same class split as ButtonLink). Size sm / md / lg (lg is full width). All sizes min-h-11.
  • Inputs: Native button props plus optional variant (default primary), optional size (default md), optional tone (default app), optional leading icon, optional ref (the rendered <button>, to move focus to it), and children label. Default type="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.
  • Purpose: Labeled pill link matching Button anatomy (primary / secondary / accent, sm / md / lg, tone app or dark). size="chrome" is the compact page-chrome pill (min-h-11 gap-1 px-1.5 py-1 text-xs, from sm gap-1.5 px-3 text-sm); the other sizes keep gap-2 text-sm.
  • Inputs: href, optional variant / size (chrome / sm / md / lg) / tone / icon / className / aria-label, optional onClick, and the visible children label.
  • Returns / side effects: A Next.js <Link> for internal paths, or a native <a> for protocol hrefs (https:). When supplied, onClick runs before navigation; the Menu loan row uses it to close the Menu before /loans/repay opens. No network of its own.
  • Used by: Home, MarketingHeader, DonatePage, RulesDocument, LoansCard, and MenuAccountHeader.

Function: SegmentedControl

  • Purpose: Mutually exclusive option group with tone gift (compact ₿|USD cells, optional shell app/dark) or neutral (pills for staff inbox and Settings notifications). Optional fullWidth defaults to true and is ignored for gift; false makes the neutral track inline-flex w-auto shrink-0 so the pill hugs its labels and can sit beside a row label. Gift hit target is min-h-11 min-w-11 on mobile and desktop. shell is ignored for neutral. Neutral role="group" is the pill; the forum composer Post/Ask !grid grid-cols-2 !rounded-2xl still lays out those option buttons via className on the group. The four forum view filters are ForumModeSelect, not this control. No trailing slot.
  • Inputs: value, options (value + label, optional badge / badgeAriaLabel; chip omitted when badge is missing or ≤ 0; optional disabled), onChange, ariaLabel, tone, optional fullWidth (default true, ignored for gift), optional shell (default app, gift only), optional className (on the group).
  • Returns / side effects: A role="group" track of type="button" options with aria-pressed. A disabled option renders a native disabled button, dimmed with disabled:opacity-50 in both tones, and pressing it does nothing. Neutral is that group as the pill (className lands 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 with fullWidth false: 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", fullWidth false: 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-full pill with a 44px minimum hit target and a truncating label; below sm the 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, optional badge, optional badgeAriaLabel); onChange(value); ariaLabel (the caller's catalog label: forum.modeLabel in ForumBoard, shops.countryLabel in ShopsCountryFilter); optional variant ('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 uses overflow-clip and 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 optional tone app (default) or dark for marketing-ink shells (ghost+dark is paper hover and focus-visible:outline-paper). sm is 24px paint with a 44px ::before hit slop; md is 44px; lg is 48px; xl is 56px (the floating + on the forum home).
  • Inputs: Native button props; aria-label is required for accessible naming. Default variant="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). surface default true draws that nested visual panel. surface={false} is a width + flex + gap column for page body inside the AppShell frame (no radius, border, bg, shadow, or p-8). Card never hosts page chrome.
  • Inputs: children, optional className, optional maxWidth (default sm), optional surface (default true; false omits panel classes).
  • Returns / side effects: A <section> wrapper. No network. Nested panel for public notes and overlays; page-body columns (LoginCard, profile, welcome, inbox) use surface={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. fixedUnit is 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/amount page 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 shows formatBitcoin. 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 saves account.amountUnit through saveAmountUnit (POST /me/amount-unit), the same save as the Settings Default amount row. No session keeps the choice on the control and starts at ₿. rateDay is 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 when account.amountUnit is fiat, 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 follows account.amountUnit again. 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 or null), optional id, disabled, fixedUnit (btc or fiat; suppresses the switch), placeholder, className, lockedSats, counterSats, onUnitChange, layout (field default, composer, or inline), optional keypad (default false; the /pos/amount page only), and optional fiatCode. Without fiatCode the 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. When counterSats is not null, it is the authoritative bitcoin counter: it takes precedence over spot conversion and over the no-rate copy. LoanPayMore uses 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 keypad a non-focusable amount plus the keypad and no input. The keypad does not show the label again. The switch unless fixedUnit is 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 calls saveAmountUnit; 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 from useActiveSession: while a login is still opening its wallet, the chosen unit stays local and is not saved on the account.
  • Used by: ForumAskWizard, ForumBoard pay sheet and reply, InboxScreen, PayLinkScreen, PosAmount, WalletSend, and LoanPayMore.

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, optional id / className / hint / error, optional errorAnnounce (adds role="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 sets aria-invalid and extends aria-describedby with the message id. The error span gets role="alert" only when errorAnnounce is true. No network.
  • Used by: Shared labeled text primitive, including shop name, address, and account fields. Amount fields use AmountEntry instead.

Function: APP_HEIGHT_BOOTSTRAP_SCRIPT

  • Purpose: Blocking bootstrap IIFE string injected as a raw head script before paint. Sets --app-height to the visible viewport (visualViewport.height, else innerHeight) and writes visualViewport.offsetTop to --app-offset-top. The offset is never added into the height and the script does not take max with innerHeight. A taller frame would be a second scroll. Scale guard: skips both writes when visualViewport.scale is 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 mention Math.max and it does not add the offset into the height.
  • Used by: RootLayout <head> script.

Function: AppHeightViewport

  • Purpose: Minimal visual-viewport fields (height, optional offsetTop, optional scale) used to resolve --app-height and --app-offset-top without depending on the DOM VisualViewport type in tests. offsetTop positions the body and is not part of the height.
  • Inputs: height in CSS pixels; optional offsetTop; optional scale (omit when unknown — do not pass undefined).
  • Returns / side effects: A structural type only — no runtime value. Callers pass { height } or { height, offsetTop, scale } into resolveAppHeight and resolveAppOffsetTop.
  • Used by: resolveAppHeight, resolveAppOffsetTop; useAppHeight (live window.visualViewport).

Function: resolveAppHeight

  • Purpose: Chooses the pixel value for --app-height. The result is visualViewport.height (else innerHeight). offsetTop is not added. A frame taller than the visible viewport would scroll the document under the one scrollport. Pinch-zoom skip: returns null (caller must not write) when scale is present and not ≈ 1 (|scale - 1| > 0.01). Null/undefined visualViewport falls back to innerHeight.
  • Inputs: innerHeight (window.innerHeight); visualViewport (window.visualViewport or a stub; null/undefined allowed; offsetTop optional and not added into the result).
  • Returns / side effects: Rounded CSS-pixel height, or null to 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 fixed body on the visual viewport. The value is rounded visualViewport.offsetTop, or 0 when the viewport or the offset is missing. It is never added into --app-height. Pinch-zoom returns null so the caller skips both writes.
  • Inputs: visualViewport (AppHeightViewport or null/undefined). scale present and not ≈ 1 (|scale - 1| > 0.01) skips the write.
  • Returns / side effects: Rounded CSS-pixel offset, 0 when there is no viewport, or null while 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-height equal to visualViewport.height (else innerHeight) and --app-offset-top equal 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 / innerHeight inside a useEffect).
  • Returns / side effects: void. Sets --app-height and --app-offset-top on document.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 layer ForumBoard renders with writer): 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 useAppHeight so --app-height stays the visible viewport height and --app-offset-top keeps 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> in RootLayout.
  • 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. fill and flow share that geometry: locked height, frame grow shrink basis-0 self-stretch (not flex-1), frame-header chrome row, then one positioned frame body ([data-app-body], a Tailwind group/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 no overflow-hidden. The frame ([data-app-frame]) publishes its content-box width as frameWidth. [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 is px-5 and the footer host px-5 with a bottom padding of calc(1.25rem - 0.5rem * var(--footer-collapse, 0)): 1.25rem (as pb-5) wherever the frame body carries no --footer-collapse, 0.75rem when it is 1 (WalletFooterActions), gliding (duration-320 ease-glide) only while the body carries data-footer-snap; 0 while the body carries data-footer-fold (the forum home's folded Receive / Send), gliding there and back (duration-280 ease-glide) only while it carries data-footer-folding. Card never hosts page chrome. Never justify-center on <main> or the scrollport. The center wrapper sets justify-content: center and then safe center, so content that fits stays centered, and where safe is supported a thread taller than the frame starts at the top and remains scrollable inside that one scrollport.
  • Inputs: children, required mode (fill | flow; both values render the same frame), optional topLeft / topRight, optional className, optional align (start | center). The <main> inset is px-3 py-2, below 360px px-2, and the chrome row px-5, below 360px px-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. useAppShellScroller reads that scroller from context; the context also carries the frame body (bodyEl) and the overlay host (overlayEl, a display: contents element 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. Mounts PasskeyRenewNotice while walletRequired === 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 the globals.css rule, not a Tailwind utility: clip until data-scroll-active, then the active port scrolls vertically only (overflow-x: clip and overflow-y: auto). The innermost bound port scrolls. Among siblings, the most recently bound one scrolls and gets data-scroll-active. Every other port gets data-scroll-locked. html and body stay overflow: clip.
  • Inputs: children, optional className, optional scrollRef, optional onClick.
  • 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-active on the port that may scroll and data-scroll-locked on the others, and clips stray scrolling elements. No network.
  • Used by: Scrollport on 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-active on the port that may scroll and data-scroll-locked on the others, and clips stray scrolling elements. No network.
  • Used by: Scrollport on unmount.

Function: syncScrollSurfaces

  • Purpose: Leave exactly one scrollport unlocked. Every other element whose computed overflow can scroll (auto, scroll, or legacy overlay, 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-active on the one port that may scroll and data-scroll-locked on the others, and may set inline overflow or textarea height. No network.
  • Used by: bindScrollport, releaseScrollport, and ScrollSurfaceGuard.

Function: ScrollSurfaceGuard

  • Purpose: Root watcher. On mount, and whenever class, style, or children change, it runs syncScrollSurfaces so 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. Observes document.body and listens for input. Disconnects on unmount. No network.
  • Used by: RootLayout, mounted once for every page.

Function: useAppShellScroller

  • Purpose: Returns the AppShell inner [data-scrollport] element, or null outside 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 AppShell page frame (DOM portal into the shell <header> host). Without an AppShell ancestor, renders children inline.
  • Inputs: children (typically an onboarding h1).
  • 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 AppShell page frame (DOM portal into the shell <footer> host; px-5 pb-5 on that host). Without an AppShell ancestor, 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 an AppShell ancestor, 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 AppShell via DOM portal; child registration wins over the page topLeft prop. The host is the frame chrome row ([data-app-chrome]), not a Card. Without an AppShell ancestor, 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 AppShell ancestor, 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 (still mode="flow") with optional top-left (wordmark) and top-right (menu / language) slots. Chrome is the page-frame header, not page-absolute. Prefer AppShell directly on app routes.
  • Inputs: children, optional topLeft, optional topRight, optional className on 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 the ui barrel. Fill routes use AppShell directly.

Function: Wordmark

  • Purpose: Text brand mark 21.gifts (header 17px/700, footer 15px/700). Link when href is set; otherwise a <span> (marketing footer).
  • Inputs: optional href, optional tone (app / dark), optional size (header / footer, default header), optional className, optional onClick forwarded 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, and RulesPageChrome.

Function: ForumHomeWordmark

  • Purpose: Welcome-page wordmark: linked 21.gifts to /welcome that preventDefaults and dispatches FORUM_HOME_EVENT so ForumLoader can scroll to top and apply new notes without a full reload.
  • Inputs: None. Uses Wordmark and FORUM_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.gifts to /welcome when useHydrateSession is ready and useAuthStore has a session, otherwise publicHref. When publicHref is omitted, the unsigned target is /. Real navigation (no preventDefault, unlike ForumHomeWordmark).
  • Inputs: Optional tone, size, className, onClick forwarded to Wordmark when set. Optional publicHref: the target without a session; with a session the link is still /welcome. Uses useHydrateSession and useAuthStore.
  • Returns / side effects: A client Wordmark link. 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); otherwise ProfileChromeLeft with wordmark href / and light LanguageSwitcher. The arrow returns to the previous in-app view, or /welcome when this tab has none.
  • Inputs: children (public note/author/ledger content or ShopScreen). Uses useHydrateSession and useAuthStore for session.
  • Returns / side effects: Fill AppShell (align="center") with the matching top-left / top-right slots around children. 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 uses notFound and 410 renders the anonymous unlisted state. Only an exact answer renders the shop: status 200 (not any 2xx) for an npub whose shop.npub equals 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 npub route segment. Calls public api GET /shops/:npub with manual redirect handling, no session, and AbortSignal.timeout(API_FETCH_TIMEOUT_MS) (2500 ms, from src/lib/api-timeout.ts) — the same limit as metadata; a timeout or abort renders the retryable unavailable state. The loader is wrapped in React cache, so generateMetadata and the page share one api call and one answer per request.
  • Returns / side effects: ShopScreen inside PublicMessageChrome, or a 308 permanentRedirect from a known hex key to /{npub} after the api's 301. Also exports shop generateMetadata. Every photo URL goes through resolveShopPhotoUrl against getApiUrl(): a relative path becomes an api URL, and a photo that is not http(s) is dropped before the page and og:image use 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, the giftsLightningAddress(payUsername, host) line, then the Open CryptoPay QR with profileQrLogo; 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. When place is 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. When address is null the street lines are omitted.
  • Inputs: Discriminated state: ready with a parsed Shop, gone, or unavailable. Uses translations and browser hostname; asks fetchMapsKey only while ready and place is non-null. Renders only absolute http(s) photos (resolveShopPhotoUrl without 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.) plus view.retry. Retry calls router.refresh; a non-empty maps key mounts GoogleMapCanvas for one point. When the canvas calls onUnavailable (script failure, missing google.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 url from GET /shops/:npub and an optional api base. With the base (trailing slashes trimmed), a root-relative /path is 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: or https: URL, or null for every other scheme (javascript:, data:, …) and for an unparsable value. No side effects.
  • Used by: ShopPage (with getApiUrl()), 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.jpg or /messages/{id}/photo/{n}.jpg. The extension is .jpg because 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: npub string and the existing forum.externalProfileCopy / forum.externalProfileCopied catalog keys.
  • Returns / side effects: IconButton; writes through navigator.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 optional onUnavailable callback. A null key leaves its frame empty and does not call onUnavailable; ShopScreen omits that frame entirely.
  • Returns / side effects: Bounded map frame. Loads Google's script through the shared loadGoogleMaps, subscribes to a rejected key through onGoogleMapsAuthFailure (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 missing google.maps after the load, or a rejected key calls the latest onUnavailable; a failure that settles after unmount does not. ShopScreen passes it and removes the map; PlacesMapScreen does 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 through PublicMessageLoader → PublicMessageThread. No OnboardingGate, top-level composer, or envelope. Wrapped in PublicMessageChrome (signed-in or unsigned chrome depending on hydrated session).
  • Inputs: Dynamic route params (id).
  • Returns / side effects: PublicMessageLoader inside PublicMessageChrome (chrome is no longer always unsigned Wordmark + LanguageSwitcher). Also exports generateMetadata for per-note Open Graph / Twitter tags. Unsigned chrome is ProfileChromeLeft with 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 via loadPublicMessageForOg and maps it through publicMessageOgMetadata so 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 with getRequestLocale() and calls marketingMetadata with that locale, an English title, and an English description that stay the same on every language URL. Home title Help people with Bitcoin | 21.gifts, description Read 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 title What 21.gifts stands for | 21.gifts, description In the forum, people can ask for help and donate Bitcoin to one another. Three convictions stand behind 21.gifts. Donate title Donate Bitcoin and help someone | 21.gifts, description Sign 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 title Living room rules | 21.gifts, description You 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 api GET /shops/:npub through the same request-cached loader as ShopPage, uses AbortSignal.timeout(API_FETCH_TIMEOUT_MS) (2500 ms), inherits root metadata on missing, invalid, timed-out, or unusable responses, and builds description, og:description, and twitter:description with ogDescriptionText and the default image alt OG_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 calls getRequestLocale() and passes that locale into marketingMetadata with 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), reciprocal hreflang links for en, de, es, and tl (Filipino pages; the URL prefix stays /fil) plus x-default to 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.gifts when blank, cut above 300 code units with …), the first photo (or /og.png), and the relative canonical/open-graph URL /{npub} resolved by root metadataBase, 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/:id for Open Graph. Invalid UUIDs skip the network. Timeouts, non-OK responses, JSON/schema failures, and thrown errors (getApiUrl, network, abort) all return null and never throw.
  • Inputs: id string from the route (forum message UUID).
  • Returns / side effects: ForumMessage or null. Uses cache: 'no-store', Accept: application/json, and AbortSignal.timeout(API_FETCH_TIMEOUT_MS) (2500 ms; the constant lives in src/lib/api-timeout.ts and also bounds ShopPage and the /l/[code] lookup).
  • Used by: generateMetadata on /messages/[id].

Function: ogDescriptionText

  • Purpose: Shared link-preview description for a public note and a public shop: trimmed text, or ` ${name} on 21.gifts when 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) and name (author or shop name).
  • Returns / side effects: Description string of at most 300 code units. No I/O.
  • Used by: publicMessageOgMetadata, shop generateMetadata on /[npub].

Function: publicMessageOgMetadata

  • Purpose: Maps a loaded public note (or null) to Next.js Metadata. Found notes use the author name as title and never the marketing layout description, even when text is empty. Photo notes set og:image to /messages/{id}/photo.jpg; others keep /og.png. A note with any via value (written without a 21.gifts account) gets fully generic metadata instead: title External author on 21.gifts, description A reply from someone outside 21.gifts who sent bitcoin to a post., and always the default /og.png image — nothing from the note's name, text or photo reaches a link preview. Both strings are plain English constants, not from the catalog.
  • Inputs: Route id and note (ForumMessage | null).
  • Returns / side effects: {} when note is null. For a note with a via value 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, url https://21.gifts/l/ plus the first 8 hex of a UUID id (otherwise https://21.gifts/messages/{id}), siteName 21.gifts), and Twitter summary_large_image`.
  • Used by: generateMetadata on /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) use fetchForumMessage(session, routeId) and fetchReplies(session, root.id) so a soft-hidden row can load; others use fetchPublicMessage(routeId) / fetchPublicReplies. If parentId is 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 hydrate ready, only forum.loading (no fetch, no cards). After ready, when the loaded root or the highlighted reply has deletedAt / deletedBy, a role="status" forum.hiddenNotice line sits above the thread (permalink target). Unsigned visitors (no session or no account) keep the PublicThreadCard stack (no pay/copy): vertical stack parent Card then reply Cards with pl-4. Gift-only replies (empty text, sats > 0): sats line via formatBitcoin plus optional preferred-fiat · formatFiatDisplay of the amount stored when the payment was made (a stored string as-is, a null or missing field on a passed stored object 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) has data-permalink-target="true" and ring-1 ring-app-fg. Photo/video per unsigned card via forumPhotoSrc (<img src> /messages/{id}/photo.jpg, extra stills /photo/{n}.jpg) and forumVideoSrc. Unsigned gallery is ForumPhotoGallery (horizontal snap row, data-scroll-x, 88% peek, current/total chip, dots); data-photo-index keeps the original still index when an earlier extra still fails to load. Translate (Languages icon) under unsigned note and reply bodies via NoteTranslate when the language differs from the UI locale. A via === '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 (TranslatableNoteBody plain) instead of ForumQuotedBody. Each unsigned card is ₿ plus optional preferred-fiat · formatFiatDisplay of 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 with receivedSats greater than zero, that card uses ReplyDirectionAmounts instead of the single amount: sent and received stay separate lines and are not added. A top-level card keeps one amount, the collected total. useSpotRate feeds 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 positive goalSats also shows ForumGoalBar, and the same Loan, Donation, or #Shop tag as the forum beside the name. When ready && session && account and the root is loaded, mounts PublicMessageThread instead of the unsigned cards, passing seedReply as the highlighted hidden reply (omit the prop when none). Auth CTA once below either stack from useHydrateSession is Log in when unsigned; its href is loginHref of this note's path and query, read from window.location as 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 /welcome when this tab has none.
  • Inputs: id string from the route. Also reads session and account from the auth store and hydrate ready.
  • 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> error event hides the player and falls back to the photo when present. NoteTranslate on unsigned note and reply bodies (GET /translate on mount, POST on Translate). Unsigned stack has no pay, composer, copy, or FiatPicker. Hydrate-not-ready is only forum.loading (no unsigned cards). A hydrate drop after a note is loaded keeps the cards and shows forum.loading in 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 ForumBoard with composerHidden and truncate={false} so the original body stays full, auto-expand via fetchReplies, and the same React, copy, reply, overlay, photo, and poll behavior as /welcome. Public stills use forumPhotoSrc; a deleted staff row still loads via fetchMessagePhoto as a blob. React (forum.react, lucide Reply) on the root note; Heart (forum.heartAmount “Send ₿21” with a loaded account, otherwise forum.heart “Send ₿1”) on those same cards after Translate and before React or Gift; on every nested reply Gift when payable (shown disabled with CannotReceiveLabel when 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. Staff onDeleted on the root calls onRootDeleted (loader → missing); a nested reply is dropped from the list. Passes permalinkTargetId so only a matching nested reply is ringed. Owns payHost and 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 in src/components/PublicMessageThread.tsx: root is ForumMessage, highlightId is string | null (route id when it is a reply UUID), seedReply is the opened hidden reply when the route id is a hidden child, onRootDeleted is () => 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 fetchReplies of the root, merge seedReply into the list when it is missing so the signed-in board still shows the hidden permalink target. Passes permalinkTargetId={highlightId} and viewerAccountId, so on the viewer's own root the reply form has no Amount field and a reply posts unpaid (isOwnNote; an empty one sets empty). No top-level composer or feed filters. Owns payHost and 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). A WalletRequiredError (api code wallet_required) on a gift, a paid reply, or a posting fee opens the RequirementsOverlay wallet step. A paid reaction keeps its text and amount in the disabled form behind the reaction pay sheet (replyPayPreview on ForumBoard); 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's sparkInvoice so 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 sets empty, 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. No OnboardingGate, no SignedInChrome.
  • Inputs: Dynamic route params (viewKey).
  • Returns / side effects: Exports metadata.referrer = 'no-referrer'. AppShell with ProfileChromeLeft (wordmark HomeWordmark: / unsigned, /welcome when a session is hydrated) and light LanguageSwitcher top-right; body is ViewProfileLoader. The arrow returns to the previous in-app view, or /welcome when 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 renders MemberProfileScreen, the same card as /profile and /members/:id. When a session exists and the payload has an id, fetchMember replaces the card so hearts and trust match. A failed refetch keeps the public card. Activity is fetchMemberActivity after that refetch and fetchViewActivity otherwise. Public posts, replies, shops, and credits use fetchViewForumList only while the card stays public. It passes shareViewKey so Copy link to this profile writes the current /view/<key> URL, including when the signed-in account is the owner. ViewProfileClaim stays under the card.
  • Inputs: viewKey string from the route. Session from useAuthStore.
  • Returns / side effects: Loading (forum.loading) / missing (view.missing) / error with Try again / the shared card plus ViewProfileClaim (hasPasskey from 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 stays profile.chartEmpty. An empty loan series renders nothing. The chart is never swapped for forum.loading.
  • Used by: ViewProfilePage.

Function: ViewProfileScreen

  • Purpose: Presentational read-only identity card matching signed-in profile chrome: heading Profile, AccountActivityChart, then LoanBalanceChart directly under it (same activityFailed flag), About me inside the card (not a forum post; public AboutMeSection with name={profile.name} shows filled text and/or photo, or omits the heading when neither; Languages Translate when aboutMessageId is set), name, location, and public username@21.gifts rows (labels name.heading / location.heading / profile.giftsHeading) without edit or Message actions. Unset location shows location.unset. Missing username shows view.noGiftsAddress. Copy-profile-link on the card (profile.copyLink). When a username is set, a centered QrCode (label profile.giftsQr) under the address encodes openCryptoPayQrValue (https://<domain>/pl/?lightning= plus the uppercase LNURL of https://<domain>/.well-known/lnurlp/<local>), including on a smartphone. A missing username shows no QR. When lightningAddressVerified is false, the card shows Can't receive yet (CannotReceiveLabel) instead of the address and the QR.
  • Inputs: { profile, viewKey, received, donated, owed, credit } — received is AccountActivity['receivedOverTime']; optional donated / owed / credit default []; optional activityFailed (default false), passed to both charts as failed. viewKey builds the copy URL /view/<viewKey>. profile includes aboutMe, aboutMeHasPhoto, and location. Public AboutMeSection hasPhoto from aboutMeHasPhoto with loadPhoto (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 activityFailed is 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, or dev. Passkey begin and finish send it as X-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.ts bakes it at next build from Docker ARG NEXT_PUBLIC_BUILD_ID (unset or empty → dev). Not an entrypoint.sh placeholder.
  • Used by: startPasskeyRegistration, finishPasskeyRegistration, startPasskeyAuthentication, finishPasskeyAuthentication, startPasskeyRecovery, finishPasskeyRecovery.

Function: LoginsClosedError

  • Purpose: Typed error for the api's HTTP 503 answer with code logins_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's code and that status, never by text; screens show catalog copy.
  • Inputs: None. The message is logins_closed.
  • Returns / side effects: Error instance named LoginsClosedError. usePasskeyLogin maps it to status closed.
  • Used by: startPasskeyRegistration, finishPasskeyRegistration, finishPasskeyAuthentication, startPasskeyRecovery, finishPasskeyRecovery, usePasskeyLogin.

Function: AppOutdatedError

  • Purpose: Typed error for the api's HTTP 403 answer with code app_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's code and that status, never by text; screens show catalog copy.
  • Inputs: None. The message is app_outdated.
  • Returns / side effects: Error instance named AppOutdatedError. usePasskeyLogin maps it to status outdated.
  • Used by: startPasskeyRegistration, finishPasskeyRegistration, startPasskeyAuthentication, finishPasskeyAuthentication, startPasskeyRecovery, finishPasskeyRecovery, usePasskeyLogin.

Function: LoginBlockedNotice

  • Purpose: The card body when the api refused to create a session: closed is the calm status line 21.gifts is updating. Please try again a little later. (login.closed) with nothing to press; outdated is A new version is ready (login.outdated) with Reload (login.reload), or without it when reload is false.
  • Inputs: kind: closed or outdated; optional reload (default true): whether outdated offers Reload.
  • Returns / side effects: React fragment (icon, role="status" line, and for outdated with reload a labeled Button). Reload calls window.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, and RecoverScreen (the blocked step on /recover, which adds Try again and Start over under closed, and passes reload={false} for outdated: 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 (hasPasskey false) 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) and hasPasskey from the public profile. Uses usePasskeyLogin, useAuthStore, useRouter, isInAppBrowser, and InAppBrowserView.
  • Returns / side effects: Waits for useHydrateSession ready. Claimed (hasPasskey true) → null (even in Telegram, even if signed in). In-app on mount or unsupported → same card chrome as login wrapping InAppBrowserView (no yellow Activate). Else in a real browser: yellow banner with view.activationRequired and Activate (view.activate) even when account !== null; click sets a claim-attempted flag, cancel + clearAuth when a session exists, then register(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.alreadyClaimed plus Fingerprint that calls authenticate(); after that attempt the yellow Activate banner does not return (successful login hides the control; a dismissed prompt keeps the already-claimed copy). Status unknown shows view.claimError and Try again calls authenticate(), never register, 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.error is wallet.prfUnsupported), the alert is wallet.prfUnsupported (This phone or browser cannot hold a 21.gifts wallet. Please use an up-to-date phone or browser that supports passkeys.) instead of view.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: WalletLoginCard stands 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. Status closed or outdated after Activate or after Log in instead shows LoginBlockedNotice in 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: viewKey string.
  • Returns / side effects: Validated ViewProfile, or null on 404. Throws on other non-2xx or a body that fails viewProfileSchema. Hits /view-key/${encodeURIComponent(viewKey)}.
  • Used by: ViewProfileLoader.

Function: proxyViewGet

  • Purpose: Same-origin proxy of api GET /view/:viewKey (public; no auth).
  • Inputs: Incoming Request and viewKey path segment.
  • Returns / side effects: Proxied upstream Response for /view/${encodeURIComponent(viewKey)}.
  • Used by: App Router GET on /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) and donated (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 (null string → 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) selects cumulative*Usd|*Chf|*Eur|*Php. 'sat' ignores fiat.
  • 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 1 when empty/all zeros.
  • Inputs: points, scale (sat | fiat), optional fiat (FiatCode) — same as activityValue.
  • 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 cumulativeUsd is null; CHF/EUR/PHP are unsummable when every source cumulative for that code is null or 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 matches alignActivitySeries; negative cumulativeSats and fiat cumulatives are kept; null USD/CHF/EUR/PHP cumulatives become 0.
  • Inputs: owed (AccountActivity.owedOverTime) and credit (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 / loanAxis tests.

Function: loanValue

  • Purpose: Read one cumulative chart value from an aligned loan point (owed or credit).
  • Inputs: point, series (owed | credit), scale (sat | fiat); when 'fiat', fiat (FiatCode) selects cumulativeOwed*|cumulativeCredit* USD/CHF/EUR/PHP (USD when omitted). 'sat' ignores fiat.
  • 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 / maxY are min/max of 0 and both series at the active scale (empty → both 0); span is maxY - minY, or 1 when that difference is 0.
  • Inputs: points, scale (sat | fiat), optional fiat (FiatCode) — same as loanValue.
  • Returns / side effects: { minY, maxY, span } for SVG placement of positive and negative balances.
  • Used by: LoanBalanceChart.

Function: useAccountTotals

  • Purpose: Session-based GET /me/activity via fetchAccountActivity; returns given/received sats plus donateOverTime / receiveOverTime, and loan owedSats / creditSats plus owedOverTime / creditOverTime. Fetches even before the in-app wallet is verified (forum gifts do not need it) and does not call fetchGiftStats. Missing loan fields become saldo 0 and empty loan series.
  • Inputs: Reads session and whether account.sparkWalletVerified is true from useAuthStore; calls fetchAccountActivity whenever 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: failed false, all series empty, the gift chart shows empty copy and the loan chart renders nothing. Success: failed false and series from the payload (?? [] / ?? 0 for loan fields). Thrown fetch: failed true, zeros, empty series, both charts show error copy. Session null: failed false, no fetch. On each fetch start (including a session or wallet-verification change) totals and series reset to zeros/empty and failed is false; AccountActivityChart shows empty copy (no SVG) and LoanBalanceChart renders 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 (AppShell wrapper) with ProfileChromeLeft hideHistoryArrow and ForumHomeWordmark top-left, and WelcomeTopRight (the member menu when a session or a held-back session exists, otherwise a link to /login). OnboardingGate screen="welcome" allowGuest wraps WelcomeScreen. 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 LoansCard and then LenderWaitingCard directly under the welcome heading before ForumLoader. Without a session it is the public active list. Page column is max-w-xl (Card surface={false}) so the AppShell frame is the only page-level rounded-3xl.
  • Inputs: Reads session and account from useAuthStore; composes LoansCard place="welcome", LenderWaitingCard, useWallet, useWalletSend, and useWalletPanel. A signed-in member also gets WalletTour, blocked while 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 LoansCard follows the heading when a loan is collecting or being repaid, collapsed by default; LenderWaitingCard follows it while lenderWaiting.shares of GET /me/loans is above 0; then comes the forum board. A session writes in the writer, not on the page (below). ForumLoader sets readOnly when there is no session. WelcomePage shows Log in in the chrome. No name or address form. No donate CTA. No LogoutButton in the page column. A signed-in member whose wallet is configured (useWallet not disabled) also gets WalletFooterActions (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 /welcome from useWalletPanel (in-page state, not a route): the welcome column stays mounted but hidden, 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 through useChromeBack (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 with shadow-lg, accessible name forum.writerOpen Write a post, lucide Plus) through AppShellOverlay, 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), otherwise bottom-6. It stays mounted and fades out (pointer-events-none invisible opacity-0, 250 ms ease-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 the bottom glide it has while the frame body carries data-footer-snap): the footer buttons leave in that step, so a fade would show it dropping to bottom-6. It fades back in when the view closes. A tap opens the writer (ForumLoader writer, rendered by ForumBoard) 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, a PanelChromeBack registers the top-left arrow (nav.back, not over: an Ask step inside the writer registers later and steps back first); the arrow closes the writer, and so do a successful post (ForumLoader calls onClose), the wordmark and the Menu's Home. Closing first blurs the focused element, so the keyboard closes as a focus change for useAppHeight. 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 in ForumLoader, so reopening shows an unsent draft. While a text field inside the page scrollport has the focus (a textarea, or an input whose type takes typed text: focusin / focusout on the scrollport), the + gets the same fade (pointer-events-none invisible opacity-0, 250 ms ease-glide; motion-reduce:transition-none), and only then does WalletFooterActions get folded. 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 its pointerup / 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 no focusout, so while a field has the focus a MutationObserver on the scrollport (child list, subtree) and every wallet-view change read the focus again. A signed-in page ends with an aria-hidden 80 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 an OpenReceiveProvider: 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 .length collapsed preview (FORUM_TEXT_PREVIEW_LIMIT) for the feed/profile timeline analog. Show more / truncated: true only when text.length is 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 so LinkedText cannot autolink a shorter href.
  • Inputs: text — full body; optional limit is this collapsed preview length (default 280); the full-body ceiling is limit * 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 / QuotedForumNote when truncate is true). Empty text returns null. Bodies autolink http(s) URLs via LinkedText. Optional plain forwards plain rendering to LinkedText on 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 pass forceExpanded. Optional forceExpanded renders the full body and omits Show more. Expand in place; no Show less. Click and keydown stopPropagation so the parent card role="button" does not toggle replies. On /messages/[id], the original body is LinkedText (ForumQuotedBody with truncate={false}).
  • Inputs: ForumNoteTextProps — text, className, optional plain, optional forceExpanded (default false).
  • Returns / side effects: LinkedText (<p> plus optional overlay), or null when text === ''. Local React expand state only.
  • Used by: ForumQuotedBody / QuotedForumNote (remaining text and nested quoted note bodies when truncate is true) and TranslatableNoteBody (original body only when truncate is 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:SS plus 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 is data-scroll-x (sideways only, vertical axis clipped) and is not a second page scroll. A current/total chip (forum.galleryPosition) sits on the visible still. Dots (gap-5, IconButton sm ghost, forum.galleryDot) scroll that row. Empty photos returns null. Single still has the chip and no dots. The capture time is stored, not shown.
  • Inputs: photos ({ index, url, loading?, fetchPriority? }[]), alt, optional className (ForumBoard passes mt-2), optional onPhotoClick (ForumBoard stopCardToggle), optional onPhotoError (the parent drops that index). url is a blob or data URL, a same-origin public still path, or a public API URL. loading defaults to lazy. fetchPriority defaults to low.
  • 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, PublicThreadCard in PublicMessageLoader, 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, optional busyLabel (the sentence above the buttons while posting is true), optional cancelDisabled (locks Cancel; omitted means Cancel follows posting), optional allowStepsWhilePosting (Next and the chrome Back stay usable while posting is 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, optional onCancel (edit mode only), resetToken (closes the wizard after a successful send), maxLength. Optional mode (create default, or edit), submitLabel, keptMedia, onRemoveKept, imagesOnly, photoError (unsupported, tooLarge, tooMany, or API formatOrSize), 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 adds shops.photoRejectedHint on its own line under any later pick reason), and serverProblem; known server fallbacks move back to the owning step and field. imagesOnly selects 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 calls onPickFiles. 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 photo aria-invalid; its icon button keeps only aria-describedby, because aria-invalid is not valid on a button. An API media error after a create or edit submit returns to this photo step. The summary button calls onSubmit (Post, or submitLabel such as Save changes). In edit mode, the icon-only Close (X) on the photo step calls onCancel. 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 while posting is true, unless allowStepsWhilePosting is set. The card does not draw Back.
  • Used by: ForumBoard when shopComposer is set, and ShopNoteEditControl in 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 sends goalCurrency and goalAmount. Only Credit is posted as goalRepayable true, together with goalTermDays. 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, optional rateDay (Bitcoin-draft preview counterpart of the typed ask), optional composerMaxLength (default FORUM_MESSAGE_MAX_LENGTH, 8000), optional askCadence ('once' | 'daily', default once) and onAskCadenceChange, optional askObligation ('donation' | 'credit', default donation) and onAskObligationChange, optional shopElsewhere (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. While shopElsewhere is 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 through aria-describedby and aria-invalid, without role="alert". No network.
  • Used by: ForumBoard when composeIntent is ask.

Function: parseForumAskAmount

  • Purpose: Parse the Ask amount draft into a whole-sat goal.
  • Inputs: raw string.
  • Returns / side effects: Integer 1..10_000_000, or null when 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 null when 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 null when 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 }, or null when 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 use forumGoalPercent(sats, goalSats); a fiat Ask uses forumFiatGoalPercent of the payment snapshot (null collected 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), optional goalCurrency / goalAmount / goal snapshots / payment snapshots, optional rateDay, optional preview, optional goalRepayable, optional goalTermDays, optional goalClosedAt (an authoritative loan close that suppresses lending immediately), optional messageId (posted credit; omitted in the wizard), optional ledgerCollapsed (feed and profile show a Repayment list link to /messages/<id>/repayment-list and do not mount CreditLedger; the open note leaves it false and renders CreditLedger with list="summary"), optional onLend (posted loan only; omitted when the viewer cannot lend). Non-positive or non-finite goalSats yields null. The percent comes from forumAskPercent. Optional lendBlocked (posted loan only): the borrower cannot receive yet, so Lend shows disabled; passed to LoanBlock.
  • Returns / side effects: The bar, or null. A posted loan (goalRepayable with messageId, not preview) renders LoanBlock instead 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, ledgerCollapsed as the Repayment list link, onLend, and lendBlocked. goalClosedAt suppresses lending immediately, including on collapsed feed and profile cards that never load a ledger. With ledgerCollapsed false it also renders CreditLedger (list="summary", which fetches GET /messages/:id/repayment) and passes the ledger that component loads (onLedger) back into LoanBlock, so the open note shows the paid-back share without a second request. With ledgerCollapsed true nothing is fetched. The wizard preview and LoansCard (no messageId) keep the Ask line, the daily plan of a credit, and the bar. A bitcoin daily plan (goalCurrency missing or BTC) shows bitcoin and the current spot and calls satsToFiatAmount, including in the preview. Bitcoin stands alone only when that spot is not loaded. A fiat daily plan uses the stored goalAmount and keeps trailing zeros, so 12.00 stays 12.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; passes onLend and lendBlocked), PublicMessageLoader, ForumAskWizard (preview at 0 collected), and LoansCard.

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 goalClosedAt the 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 in font-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 use paidAmount cents, bitcoin rows use paidSats; a fully paid row contributes its whole original value, and rows without an amount are skipped), aria forum.loan.paidBarAria, and Fully funded · being repaid. Paid back (every row paid, at least one row): a full green bar and Paid back in text-app-success with lucide CircleCheck. No lender count, no line about the viewer's own share, and no repayment-plan explanation.
  • Inputs: messageId, ask (markup), collected and goal (strings with their fiat), percent (uncapped; the label), funded (collected sats reached the asked sats), ledger (RepaymentLedger or null), ledgerLink (show Repayment list to /messages/<id>/repayment-list), optional goalClosedAt (authoritative close from the note), optional onLend. Optional lendBlocked: the borrower cannot receive yet.
  • Returns / side effects: A section labelled Loan request with data-loan-block (collecting, funded, repaying, or repaid). The bottom row shows Repayment list and, only while collecting, while goalClosedAt is null or absent, and while the loaded ledger does not have a non-null closedAt, Lend. goalClosedAt therefore 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 uses forum.loan.payNoticeOne, a note without a term forum.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, or undefined), full.
  • Returns / side effects: A paragraph with data-loan-notice (lend or full). No network.
  • Used by: ForumReplyPayPage and ForumPaySheet (through ForumBoard's loan target).

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 ForumGoalBar and LoansCard on BTC and legacy Asks. Fiat Asks use forumFiatGoalPercent.
  • Inputs: sats (collected) and goalSats (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 snapshot amountUsd / amountChf / amountEur / amountPhp, two-decimal string or null) and goalAmount (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 null for 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) uses forumFiatGoalPercent of the payment snapshot in that code; every other Ask uses forumGoalPercent of 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, optional goalCurrency, goalAmount, and the payment snapshots amountUsd / 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 goalAmount exactly, not the two-decimal snapshot of the same currency.
  • Inputs: amount string, fiat code, number-format style.
  • 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, and totalText (the whole debt, already formatted).
  • Returns / side effects: A figure, or null when every amount is missing. No network.
  • Used by: CreditLedger, ForumAskWizard plan 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 scrollIntoView and it never scrolls the document. The same module exports SCROLL_FOLLOW_ATTR (data-scroll-follow), the mark a reveal puts on the scrollport while it follows a moving target (ForumBoard); WalletFooterActions and 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 scrollTop only. No network and no window scroll.
  • Used by: revealReplyForm, ForumBoard composer and reply focus, useAppHeight after a viewport change.

Function: revealReplyForm

  • Purpose: Keeps a forum reply form inside the AppShell scroller by delegating to revealInScrollport after 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 (HTMLElement or null) and the reply <form> (or null).
  • Returns / side effects: Void. Mutates that scrollport's scrollTop only when both arguments are present. No network. No scrollIntoView.
  • Used by: ForumBoard after 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 (HTMLElement or 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: ForumBoard while 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-fit so the picture stays centered and both controls sit on it. The fullscreen button calls requestFullscreen on that frame, or webkitEnterFullscreen when 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: ForumBoard feed video, PublicMessageLoader public 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 an IconButton; the footer ₿ amount button and the reply-count button (when shown) also call onToggleExpand; React on every top-level note (forum.react, lucide Reply; expands the reply composer; omitted when deletedAt is set), a heart (lucide Heart; forum.heartAmount “Send ₿21” with a loaded account, otherwise forum.heart “Send ₿1”) that sends the account's stored heartSats (default 1) on a non-deleted post and a non-deleted reply when heartViewerId !== accountId (shown signed-out; hidden when payable is false and when onHeartTip is 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 calls onHeartTip and 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/repay when repayLink is 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 no goalClosedAt, otherwise Repay your loan (ForumLoader and MemberProfileScreen pass it; PublicMessageThread does not), Translate (Languages icon, controlSlotId on TranslatableNoteBody in this row), a copy-link IconButton on every note and every reply, optional Gift on a payable reply (disabled, and still inside the zap SundayWritingGate, 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 calls onPayCancel, while a posting-fee sheet (payHost composer) stays), and optional delete sit outside that control as sibling IconButtons that stopPropagation; when shopNoteEdit is 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; when shopPlaceEdit is set, a compact place control (Add a place or Edit place) sits in that footer after the pencil and before the account control; when shopAccountEdit is set, a compact account control (Add an account or Edit account) sits after the place control; Gift/Delete/reply composer also omit when deletedAt is set). Optional dismissible living-room laws hint box (X control; two laws plus links to /rules and /contact) when lawsVisible, Active/No gifts yet/All/Most popular ForumModeSelect (closed dropdown; selected label and chevron on the trigger; unpaid count chip on the closed trigger when unpaidNewCount > 0 and unpaid is not selected), list of posts (name, the author row uses MessageKindTags (Loan and Donation buttons that show a sentence, #Shop stays 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 (basis has no pill), top-level shop notes show a #Shop link to /shops and hide #21GiftsShop, timestamp, optional inline photo from forumPhotoSrc (/messages/{id}/photo.jpg, extra stills /photo/{n}.jpg; blob and data URLs in photoUrls win for a composer preview; a deletedAt row never gets the public URL) (single still when photoCount ≤ 1; a horizontal snap row (ForumPhotoGallery, data-scroll-x, 88% peek) when photoCount > 1 — sideways only, current/total chip, 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 @username link 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 with max-h-80 max-w-full, no full-width black canvas), remaining body text through ForumQuotedBody / ForumNoteText (280-character preview plus forum.showMore only when the body is longer than 560 on the feed; signed-in /messages/[id] passes truncate={false} so the original stays full), Translate (Languages icon) / Show original / Show translation in the footer icon row via TranslatableNoteBody (controlSlotId), which portals NoteTranslate with placement="row" when the board has that row, a reply or note with via === 'nostr' (a Nostr zapper with no 21.gifts account) renders the External button only when the api role has no tag (for example basis); a nostr note whose api role is software_developer shows 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 via TranslatableNoteBody plain (no quoted-note unfurl, URLs stay visible text) instead of ForumQuotedBody, ₿ amount plus optional preferred-fiat · formatFiatDisplay of 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 (parentId set), or a disabled Gift with CannotReceiveLabel when the reply's author cannot receive yet; the card's copy control is labelled forum.copyReplyLink when the card is a reply and forum.copyLink otherwise, 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) when onPlaceDraftChange is 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 is ForumAskWizard (the amount step and the preview open with the One-time / Daily pill; the photo and text steps do not); when allowAsk is false the Post/Ask pill and Ask wizard are omitted; shopComposer shows ShopAddWizard instead of the post composer), optional photo draft preview (Selected photo) when photoDrafts.length === 1 with Remove photo X, composer gallery when photoDrafts.length > 1 (ul of Selected photo alts + per-index Remove photo), optional video draft preview with Remove video X — icon-only, catalog aria-labels, maxLength from optional composerMaxLength (default 8000)), in-card reply composer (amount row first: AmountEntry layout="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, when payHost is composer, 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 (PaySheet inside a Collapse with holdMs PAY_SHEET_HOLD_MS: title, amount with fiat, and the WalletPay pay 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. When receivedSats is greater than zero, forum.receivedOnReply is a separate line and is not added to sats. A text reply that has both uses forum.sentOnReply for 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 unless modeSelector is false or composerHidden is true. When modeSelector is false the list is every loaded row (mode all), including zero-sat basis notes; an empty loaded list still uses emptyKey, not forum.emptyPaid. Uses optional emptyKey (forum.empty default, shops.empty on shops) when the loaded list is empty, forum.emptyPaid when Active or Most popular hide every loaded row (Most popular remains paid-only; Active also keeps unpaid moderator notes; a top-level note with goalSats > 0 and zero sats is not Active), and forum.emptyUnpaid for No gifts yet when that filter hides all loaded rows. Props messages are 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. When onRefresh is passed, pull-to-refresh from the top of the AppShell inner scroller (useAppShellScroller) calls it; while refreshing (or a pull that reached the arm threshold) a visually hidden (sr-only) role="status" with forum.refreshing is mounted for assistive tech only — idle markup has no status node so welcome screenshots stay unchanged. When newPostsAvailable is true, a labeled primary Button (forum.newPosts, decorative lucide ArrowUp) is sticky top-2 in the scroller; the node is omitted when the flag is false. When moderatorAppointedAvailable is true, a labeled primary Button (forum.moderatorAppointed, size sm with shadow-lg, decorative lucide ArrowUp) in the same visual language as New posts is sticky top-2 when it is the only pill and calls onShowModeratorAppointed; the node is omitted when the flag is falsy. When both this and newPostsAvailable are true, the appointment pill stays sticky top-2 and New posts is sticky top-14. Listens for FORUM_COMPOSE_EVENT / requestForumCompose: focuses the new-post textarea with preventScroll and then revealInScrollport when the shell scroller exists and consumes pending compose only when that textarea exists (composerHidden boards keep the flag). /messages/<uuid> and http(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) is WalletPay, which pays from the member's in-app wallet (sparkInvoice when the api issued one, otherwise pr, 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. When authorCannotReceive is true for a note or reply (api authorCanReceive: 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 with cannot_receive shows forum.payErrorAuthorWallet under the heart (cannotReceive on 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, optional readOnly (signed-out living room: no composer, pay, delete, or @mention links; an author name with a non-empty accountId is still the profile button, including when readOnly is 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, optional refreshing / onRefresh (omit onRefresh to disable pull-to-refresh), optional newPostsAvailable / onShowNewPosts (pill omitted when the flag is falsy), optional moderatorAppointedAvailable / onShowModeratorAppointed (pill omitted when the flag is falsy), posting, draft, onDraftChange, askDraft / onAskDraftChange, optional allowAsk (default true; false omits the Post/Ask pill and the wizard) / optional composeIntent / 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), controlled mode / onModeChange, optional modeSelector (default true), optional nearEndRef (callback ref on the visible note about eight rows from the end so ForumLoader can 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), optional unpaidNewCount (default 0), required lawsVisible / onDismissLaws, photoDrafts (ForumPhotoPayload[]), placeDraft (ForumPlacePin | null), optional onPlaceDraftChange (omit it and the place control is absent, so replies have none), videoDraft, onPickFiles(files: File[]), onRemovePhoto(index: number), onClearPhoto, photoUrls, optional photoVersions (Readonly<Record<string, string>>, default {}; a non-empty token is appended as ?v= on the public still path), videoUrls, optional composerHidden (hides the new-post composer; the textarea is absent so compose-pending is not consumed), optional composerMaxLength (default FORUM_MESSAGE_MAX_LENGTH; shops pass 7986 so the #21GiftsShop suffix fits), optional emptyKey (forum.empty default, shops.empty on shops), plus pay sheet props (payMessageId, optional payHost (composer keeps the sheet on the top-level composer; card binds to the matching parent or reply; omit/null infers from the list), payDraft, payBusy, payError (amount / request / rateLimit / authorWallet / deleted), payInvoice, optional replyPayPreview (string | null, default null; when set with a matching card invoice, ForumReplyPayPage opens over the page and the reply composer stays, disabled), optional rateDay (FiatRateDay | null; omit or null leaves unsent previews bitcoin-only because no rate is loaded; a present rateDay prices 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, optional viewerAccountId, optional repayLink (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 optional replyAmountDraft / onReplyAmountDraftChange, replyFormError including amount for a non-numeric or overflowing paid-reply sats field, deleted when that note is missing or was deleted, and authorWallet (forum.payErrorAuthorWallet) when the author's wallet cannot take a paid reply), optional shopComposer (shops; ShopAddWizard instead of the post composer), shopUsername / onShopUsernameChange / shopResetToken, optional shopNoteEdit / onShopNoteUpdated (moderator pencil on a top-level shop note), optional shopPlaceEdit (true on shops; the footer place control is absent when omitted) and onShopPlaceUpdated (applies a saved or cleared pin to that row), optional shopAccountEdit (true on shops; the footer account control is absent when omitted) and onShopAccountUpdated (applies a saved or cleared shop account to that row), and optional onDeleted (moderator DeletePostControl on the parent footer and on nested replies with kind="reply"), optional heartViewerId (default null; hides the heart when it equals accountId), optional heartViewerSats (default null; whole sats the loaded viewer's heart sends, named through forum.heartAmount “Send ₿21”; null keeps forum.heart), optional onHeartTip / heartTipViews (heart from useHeartTip; omit onHeartTip to hide the heart on every note), optional permalinkTargetId (nested reply ring only: data-permalink-target="true" and ring-1 ring-app-fg; parent notes are not ringed), and optional truncate (default true; PublicMessageThread passes false). Gift-only replies (text === '' and sats > 0) render forum.giftReply with formatBitcoin plus the same optional preferred-fiat · formatFiatDisplay suffix 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. receivedSats greater than zero adds forum.receivedOnReply with the received fiat fields, not a sum. A text reply with both amounts labels the sent line forum.sentOnReply. The video-draft X still calls onClearPhoto; each photo-draft X calls onRemovePhoto(index). Optional onShopNoteSaved runs 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 via visibleForumMessages. Load error copy is forum.error via t(), never Error.message. Formats timestamps via formatForumTime. Hides empty text paragraphs; public stills use forumPhotoSrc; blob and data URLs stay for the composer preview; a deleted staff row has no public URL. Feed video is ForumVideo (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> error event hides that player (photo fallback when a still URL exists: the public forumPhotoSrc path, or a blob or data URL in photoUrls). Clicking a role pill toggles a short explanation under that card header (one open at a time). Dismiss control calls onDismissLaws only; persistence is owned by ForumLoader. ForumBoard itself does not fetch; nested NoteTranslate GETs /translate on mount and POSTs on Translate. No mode state of its own. After onPaySubmit resolves to an invoice, ForumBoard does not window.location.assign; every user-agent shows the same bottom pay sheet, whose pay slot is WalletPay (the in-app wallet only); the sheet mounts no QrCode. A FORUM_COMPOSE_EVENT focuses the new-post composer when it is mounted; a composerHidden board leaves pending compose set for a later visible board. While a payment is open, revealPaySheet runs on its gift amount box ([data-pay-amount]; the bottom pay sheet sits in the overlay, outside the scroller) instead of revealReplyForm. 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 stays relative; the pay sheet's close sits at the right end of its title row. With viewerAccountId set, 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 cannotReceive shows forum.payErrorAuthorWallet; creditClosed reuses the localized forum.payErrorCreditClosed loan-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; only ForumLoader for 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, AppShellOverlay holds the writer: a Scrollport (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 centred h2 (forum.composePost, or forum.composeAsk while 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 (payHost composer) is hosted on the page beside the overlay, in its own Collapse with holdMs, 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 calls onOpen synchronously; a request left pending before mount calls onOpen too. 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. Without writer the board renders as before.
  • Loans: A top-level loan note (goalRepayable with a positive goalSats) passes onLend to ForumGoalBar when the board is not readOnly, it is not the device's local Sunday, the note is payable, 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 a LoanPayTarget (name, goalTermDays, and full once the collected sats reach goalSats, 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 line forum.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 (Collapse and AutoHeight, with src/lib/motion.ts; see docs/ui.md Motion): the expanded block of a card (replies, retry, reaction form) opens and closes with Collapse, and its height glides while it is open. The card-level, per-reply and composer gift boxes open and close with Collapse; each pay host's Collapse (those three and the reaction's ForumReplyPayPage) carries holdMs PAY_SHEET_HOLD_MS, so the PaySheet drawn 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 shows LoanPayNotice at 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 an inert Collapse and no longer counts as open; the PaySheet itself 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 (Collapse instant), 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 (Collapse about to open or opening, AutoHeight with data-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 carries SCROLL_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 === '' and sats > 0) is forum.giftReply. A reply with text and sats, and no later receipt, is the bare formatted amount under the body. When receivedSats is greater than zero, that receipt is forum.receivedOnReply on its own line. A text reply that also sent sats labels that line forum.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, optional receivedSats, rateDay, fiat, numberFormat, optional sent fiat fields for sats, optional received fiat fields for receivedSats.
  • Returns / side effects: React element, or null when both amounts are absent. No network. Bitcoin via formatBitcoin. Fiat via preferredFiatSuffix on 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: ForumBoard on every nested reply, and PublicThreadCard in PublicMessageLoader when the unsigned card is a reply with receivedSats greater 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 PaySheet with 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; rateDay and optional ratePending (default false; Continue does not submit while it is true); showPaymentQr is accepted and not rendered; onInteract so the box does not toggle the card under it; optional loan (LoanPayTarget: borrower name, term, and whether the loan is full) and optional recipient.
  • Returns / side effects: The amount box (data-pay-amount, rounded-xl border p-3 pl-12 pt-12, its X at left-3 top-3): AmountEntry, a pay error that folds in and out (Collapse), including the creditClosed sentence that the loan no longer collects, LoanPayNotice when loan is set, and Continue. While an invoice is open it keeps the existing PaySheet and wallet-only flow. No network of its own.
  • Used by: ForumBoard and HabitComments, each inside a Collapse with holdMs PAY_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 PaySheet slides up over the page with the amount and the WalletPay pay slot, which pays from the member's in-app wallet (sparkInvoice when the api issued one, otherwise pr, 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, optional sparkInvoice, rateDay, onCancel, optional onSentChange (passed to the sheet, for usePaySheetHold), optional loan (LoanPayTarget), and optional recipient (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 WalletPay reports a payment that did not go out under the flow reaction. Close (X) calls onCancel. 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 a Collapse with holdMs PAY_SHEET_HOLD_MS next 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 from grid-rows-[0fr] to grid-rows-[1fr] with opacity-0 to opacity-100 over 280 ms (ease-glide). Content shown on the first render shows at once, without a move. When show turns 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 own grid-template-rows transition 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. With holdMs, 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, usePresent says whether the fold still shows it.
  • Inputs: show, the content, optional className for the inner box that holds the content, optional instant (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. Optional holdMs (ms; instant wins).
  • Returns / side effects: The folding box (data-collapse closed while closed or folding, opening until it has settled open, then open; with holdMs, held once it has folded away while the hold keeps it mounted, so a wait for moving boxes does not wait for the hold), or null while closed. Settling open sends MOTION_SETTLE_EVENT while the box still says opening, and the box says open right 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 with holdMs PAY_SHEET_HOLD_MS; reply form errors), ForumPaySheet (pay errors), HabitComments and InboxScreen (their pay sheets, with holdMs), AmountEntry (counter line).

Function: usePresent

  • Purpose: Tells content inside a Collapse whether that fold still shows it, so a layer it draws elsewhere (the PaySheet in 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 Collapse gets show false (while it folds or holds its last content), true otherwise, and true outside a Collapse. 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 ResizeObserver on 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-follow turns its own transition off) instead of gliding a second time behind it. Without ResizeObserver the box keeps its natural height. With reduced motion the height follows at once and nothing clips.
  • Inputs: The content, optional className for the inner flow-root box that holds it.
  • Returns / side effects: The gliding box (w-full min-w-0, data-auto-height; data-gliding while its own glide runs). It writes style.height from the observer, the way src/lib/scroll-surface.ts sizes a textarea, never as a JSX style attribute (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. viewKey names 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 at opacity-0 and 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, optional className for the box that holds the view (for example the flex column and gap its parts sit in).
  • Returns / side effects: The swapping box (data-swap names 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, AutoHeight or Swap once: 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.ts also holds the shared time windows MOTION_EASE_MS (280 ms, also the shell footer's fold in WalletFooterActions), MOTION_SWAP_FADE_MS (180 ms) and MOTION_FOLD_MS (320 ms, the latest settle of a move), and MOTION_SETTLE_EVENT (21gifts:motion-settle).
  • Inputs: The element, the transition property as transitionend names 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 transitionend listener 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); ForumBoard listens.

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 no matchMedia.
  • 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 from useAuthStore; returns null without a session. Posts via postContact. On success fetches conversations and navigates to /messages or /messages?c= for the official 21.gifts thread. No local success-hide of the form. Uses nextContactRequirement so missing name/rules open RequirementsOverlay (no Skip); a wallet is not required for contact.
  • Inputs: None (reads session from the auth store).
  • Returns / side effects: React element wrapping ContactScreen, or null. Owns draft/posting/formError. Empty or whitespace drafts set empty; trimmed text longer than 8000 characters sets tooLong and does not call postContact. After a successful post, the draft is cleared and posting is set false, then fetchConversations and returnToView open the inbox thread (a step back when that thread opened Contact, otherwise a replace). A failed post sets request and clears posting so Send can retry, and the draft stays.
  • Used by: Screen /contact.

Function: ContactPage

  • Purpose: Next.js page for /contact.
  • Inputs: None.
  • Returns / side effects: AppShell with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate around ContactLoader.
  • 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, catalog aria-label contact.send, no HTML max length). Over 8000 characters is the field message. Success is owned by ContactLoader (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 /map to 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 /map and every path except /_next/static, /_next/image, /sw.js, and the files under public/ (icons, og.png, robots.txt, sitemap.xml, handbook-images/, happyland/). It reads CSP_MODE through getCspMode on 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 /shops and keeps the query string, with the hash #map. A public language URL is rewritten to the unprefixed path, the request gets x-21gifts-public-locale, and a document open sets the locale cookie (Path=/, Max-Age=31536000, SameSite=Lax, Secure on HTTPS). Every other matched request passes on. A fresh nonce (createCspNonce) goes into the policy (buildCsp). The policy is set on the response as Content-Security-Policy-Report-Only, or Content-Security-Policy when CSP_MODE=enforce, with Reporting-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 and RootLayout on 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 key GoogleMapCanvas draws 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 from formatPlacePinText (name and address line, or coordinates). A pin label opens /{shopNpub} when shopNpub is set, and /messages/:id when it is null. Those links are next/link, so opening a member or a note keeps the document. After a pin edit saves, the row takes lat, lng, label, address, and shopNpub from the updated note; a response without shopNpub keeps 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 with shop: true; it loads that note and opens the same steps as editing a shop post. A failed load shows forum.editShopNoteLoadFailed, not the save-failure sentence. embedded returns 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), and onShopsChanged (run once after a moderator's shop save (a complete save, or a partly written one when its editor closes or unmounts)). Catalog via useTranslations. Session from useAuthStore. Optional ?pin= id.
  • Returns / side effects: Card maxWidth="xl" surface={false}, or only the body when embedded. Fetches places and /maps/key. With a country, the list and the markers keep only the shop pins (shop: true, the pins the filter counts) whose countryCode matches and the map fits (or centers on) those pins; none left is the empty copy map.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 via fetchMapsKey.
  • Interaction log: An opened ?pin= whose place is a shop (shop: true) is recorded once as shop_opened with 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, or null for 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 GoogleMapCanvas and PlaceField so 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"]) loads https://maps.googleapis.com/maps/api/js?key=…&v=weekly with no extra libraries. A script[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 marked data-gmaps-state="error" rejects at once.
  • Returns / side effects: Promise<void> that resolves at once when google.maps exists, otherwise when the script loads and installs google.maps. On a script error it rejects and removes the script, so the next call adds a fresh script and retries. On a load without google.maps it rejects, marks that script data-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. GoogleMapCanvas and PlaceField on 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 loadGoogleMaps call, and puts it back if another script replaced it.
  • Returns / side effects: An unsubscribe function. A report is remembered for the google.maps namespace that was on the page when Google made it: a later subscriber on the same page is called at once. A report before google.maps exists reaches current subscribers only.
  • Used by: GoogleMapCanvas, PlaceField.

Function: fetchPlaces

  • Purpose: Load every live top-level forum pin for the signed-in session.
  • Inputs: sessionToken bearer.
  • Returns / side effects: ForumPlaceRow[] from GET /forum/messages/places. A row may include shop: true when 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), and countryCode (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/key returns 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 is PlacePinChip, 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. Optional buttonSize (lg default, or sm), buttonVariant (secondary default, or ghost), previewSlot (accepted and not read), ariaLabel (default Add a place), onCommit. Without onCommit, Use this place and Remove place call onChange and close. With onCommit, those buttons wait; a rejection keeps the dialog open with its reason; a success closes without calling onChange. When a pin is already set, Remove place stays inside the open dialog, including when the map is unavailable. Optional shopDetails (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 old showPreview prop is removed; a confirmed composer place shows as PlacePinChip.
  • Returns / side effects: Attach button and an accessible modal dialog. Fetches /maps/key when opened. A stored place can be removed from the living-room composer (no shopDetails). A shop dialog never offers Remove place, because a shop name cannot be cleared. Fetches /maps/key through fetchMapsKey when opened and loads Google's script through the shared loadGoogleMaps. Subscribes to a rejected key through onGoogleMapsAuthFailure for 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, no shopDetails), ShopAddWizard (shopDetails), and ShopPlaceControl (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), optional disabled, and onRemove.
  • 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 (lucide Camera) with its own hidden <input type="file" accept="image/*" capture>. On a phone, capture opens 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 ignores capture and 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), optional facing (environment, the back camera, by default; user, the front camera, for the profile photo), size (md default, lg beside a large gallery button), disabled (button and input together), name (on the hidden input), and onChange, 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), and ProfileScreen (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: ForumModeSelect for 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 carries data-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, and window.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: shotScreen in e2e/visual.spec.ts, before every screenshot, and the behavior test Function: 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) and onUpdated (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) with message.text, so invalid name/text combinations are linked under Shop name and block Use this place before the request. onCommit calls setMessagePlace; a failed save keeps the panel open and maps known API reasons back to their owning field or footer.
  • Used by: ForumBoard when shopPlaceEdit and onShopPlaceUpdated are set (ForumLoader feed="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), optional onSaved (once, after every changed part is saved; when a later part fails after earlier parts were written, the editor stays open with its error and onSaved runs 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), optional existingPhotos, optional existingVideoUrl, and optional startOpen.
  • 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) or inbox.errorTooLarge under the steps, and stills past ten show forum.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; API At most 10 photos maps to tooMany, and Photo must be a JPEG, PNG, or WebP under 1 MiB maps to formatOrSize (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 with forum.editShopNoteFailed and 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 use forum.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 shows forum.editHistoryFailed instead 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: ForumBoard when shopNoteEdit and onShopNoteUpdated are set (ForumLoader for a moderator on every feed), ShopTable, and PlacesMapScreen for a pin with shop: true.

Function: ShopAccountSuggestions

  • Purpose: The People list under a shop-account field. Each row is @username and 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, and onPick.
  • Returns / side effects: A listbox labelled People. onPick runs on mouse down and on click. No network.
  • Used by: ShopAddWizard on the username step and ShopAccountControl in 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) and onUpdated (message id plus the saved { id, username, name }, or null when the saved message omits shopAccount).
  • 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 debounced lookupAccountByUsername check. 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 with aria-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, because setMessageShopAccount validates again. Only errors returned after Save use role="alert"; success calls onUpdated and closes. The control does not offer a way to clear the account. A response that omits shopAccount still passes null to onUpdated.
  • Used by: ForumBoard when shopAccountEdit and onShopAccountUpdated are set (ForumLoader feed="shops").

Function: ShopsPage

  • Purpose: Next.js page for /shops. Flow AppShell (align="start") with ProfileChromeLeft + SignedInChrome, OnboardingGate screen="welcome", and ShopsScreen. No route.ts beside 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 is ShopList. Post is ForumLoader feed="shops". Map is PlacesMapScreen embedded. Table is ShopTable. 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 no hashchange. 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 carries data-view-history-back, its href is the view-stack path and has no hash, and when canStepBack is true the click steps back with router.back() and the view follows the restored entry instead of treating that href as List. Any other link to this page, including a hashless /shops link, still selects the view in its href. Links with a target or download are left alone.
  • Inputs: Catalog via useTranslations. The view stays unset until the hash is read. /shops#post, /shops#map, and /shops#table open that view. A missing or unknown hash opens List. Choosing an option writes the same hash. List clears it. The country query (shopCountryFromQuery) is the country filter: it is read with the hash on load, on popstate, and from a link to this page.
  • Returns / side effects: Card maxWidth="xl" surface={false}. ShopsCountryFilter registers its chip in the top bar. Choosing a country sets or removes country with useRouter().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 to ForumLoader, ShopTable, and PlacesMapScreen (the post list and the table remount per country, so their pages restart). ShopList remounts with the same view key and still loads the full directory. Each of the post list, map, and table reports onShopsChanged after 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 /shops shows, or All countries.
  • Inputs: value (ISO 3166-1 alpha-2 code or null) and onChange. Session from useAuthStore; locale and catalog via useTranslations.
  • 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 calls onChange(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 country value, 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 SegmentedControl labelled 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. #post opens Post.
  • Inputs: value (list, map, table, or post) and onChange.
  • Returns / side effects: A SegmentedControl tone="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, className underline, and href is /{npub}. When place is non-null, the place line under the link is formatPlacePinText and is not a link. When place is null, that line is omitted. Rows are keyed by npub. Show more loads the next page. An empty page with a next cursor keeps Show more and does not show shops.empty. A failed later page keeps the rows, shows shops.loadError, and Try again reloads that same cursor. A failed first page replaces the list with shops.loadError, and Try again loads the first page again. Until the first page arrives, the line is map.loading. Does not call fetchMessages, 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 sends country, so the api returns only shops pinned in that country and Show more pages only those. Optional onShopsChanged, run once after a moderator's shop save (a complete save, or a partly written one when its editor closes or unmounts). Session from useAuthStore. Catalog via useTranslations.
  • 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}#map via formatPlacePinText (name and address line, or coordinates; ShopsScreen then 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/rules instead with returnToView (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: kinds from noteKinds. children is 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 the ForumAskWizard preview.

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 #21GiftsShop token adds shop.
  • Inputs: parentId, text, optional goalSats, optional goalRepayable.
  • Returns / side effects: loan, donation, and shop in that order, or an empty list. No network.
  • Used by: ForumBoard, ForumAskWizard.

Function: isShopNote

  • Purpose: True when text contains a #21GiftsShop token (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 #21GiftsShop tokens 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#21GiftsShop when 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 Set of uppercase two-letter codes.
  • Returns / side effects: Membership lookup for countryOptions and 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) and locale for the display names.
  • Returns / side effects: The localized name, or code when the runtime has no name. No network.
  • Used by: countryOptions, formatShopAddressLine.

Function: countryOptions

  • Purpose: Country options for a native <select>, labeled in locale and sorted by that label.
  • Inputs: locale for Intl.DisplayNames and localeCompare.
  • Returns / side effects: One { value, label } per code in ISO_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, or null when every field is empty.
  • Returns / side effects: 'missing', 'street', 'houseNumber', 'postalCode', 'city', 'country', or null. 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, or null when 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: PlaceField for 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 null or undefined when unset.
  • Returns / side effects: 'name', 'nameAddress', 'nameLong', 'nameControls', or null. 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 pin label (or null).
  • Returns / side effects: 'short', 'long', 'notLonger', 'controls', or null. 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 the ShopAddWizard text 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: ShopAddWizard for 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, otherwise null. No network. Format stays in shopUsernameProblem.
  • Used by: ShopAddWizard, ShopAccountControl, and composeShopUsername in ForumLoader.

Function: shopUsernameProblem

  • Purpose: Checks the shop-account username format, including an optional leading @. Empty input returns null. shopAccountRequiredProblem owns 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 returns null. No network.
  • Used by: ShopAddWizard, ShopAccountControl, and the pre-payment validation in ForumLoader.

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}$, otherwise null. No network.
  • Used by: LoginCard name 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, otherwise null. 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, otherwise null. No network.
  • Used by: placeLabelProblem for 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, otherwise null. 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 null while 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, otherwise null. No network.
  • Used by: PlaceField when 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, otherwise null. 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, otherwise null. 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, otherwise null. 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: null when blank after trim, 'long' over 8000 characters, 'controls' for a control other than LF or CR, or for DEL, otherwise null. 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, ShopAddWizard summary.

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 ForumPlacePin and UI locale.
  • 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 null when unset.
  • Returns / side effects: true when shopNameProblem and shopAddressProblem are 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.message string 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, or null for unknown text. No network.
  • Used by: ForumLoader shop creation and ShopNoteEditControl photo 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.message from postMessage, setMessagePlace, or setMessageShopText, 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 ShopApiProblem for a shop name/address, description, or username rejection.
  • Returns / side effects: 'place', 'text', or 'username'. No network.
  • Used by: ShopAddWizard, ForumBoard, ForumLoader, and ShopNoteEditControl for 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: true only for string keys in SHOP_API_MESSAGE; otherwise false. No network.
  • Used by: ForumLoader to preserve or clear mapped shop errors and ForumBoard to 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-field errors, and optional onBlur(field).
  • Returns / side effects: Labeled inputs with linked aria-invalid / aria-describedby errors. Autocomplete off / off / postal-code / address-level2 / country. No network.
  • Used by: PlaceField when shopDetails is set.

Function: RulesDocument

  • Purpose: Presentational living-room rules body from catalog keys: lead with the The test callout, three rule cards (rules.lawKicker with {n}, title, body, optional test callout), welcome / allowed / better-not / forbidden lists rendered as bordered cards with lucide glyphs (Check text-app-fg, Check muted, Minus, X text-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: messages catalog for the request locale; optional showNav (default true); optional chapter (RulesChapterId). When chapter is set, only that chapter is rendered and the public nav is omitted (showNav ignored). When showNav is false and chapter is omitted, the public Contact nav is omitted.
  • Returns / side effects: React element. Server component — uses translate, not useTranslations. 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 mounts ProfileChromeLeft with HomeWordmark (publicHref is homeHref, the language home) plus LanguageSwitcher. The arrow returns to the previous in-app view, or /welcome when this tab has none. The signed-in wordmark stays /welcome.
  • Inputs: children (heading + RulesDocument from RulesPage) and homeHref (unsigned language home). Uses useHydrateSession and useAuthStore for session.
  • Returns / side effects: PageChrome with the matching top-left / top-right slots around children. The unsigned wordmark opens homeHref. No network beyond session hydration.
  • Used by: RulesPage.

Function: RulesPage

  • Purpose: Next.js page for /rules, /en/rules, /de/rules, /es/rules, and /fil/rules with localized heading and living-room rules document, wrapped in RulesPageChrome (signed-in or unsigned chrome depending on hydrated session).
  • Inputs: None. Calls getRequestLocale() for the page title and document catalog, and passes homeHref={localizedPublicPath(locale, '/')} to RulesPageChrome.
  • Returns / side effects: Heading + RulesDocument inside RulesPageChrome (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 /welcome and /shops with feed="shops" (filter #21GiftsShop, hide laws, append hashtag on compose, emptyKey shops.empty, pass shopPlaceEdit and onShopPlaceUpdated so a moderator can set or replace the pin on an existing shop note, and shopAccountEdit and onShopAccountUpdated so a moderator can set or replace the shop account). Session and account from useAuthStore; 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 requests mode: 'all' with hashtag: '21GiftsShop' and does not mount the mode selector, the Post/Ask pill, or ForumAskWizard (allowAsk: false); it mounts ShopAddWizard through shopComposer and does not apply active/unpaid/popular. A moderator session passes shopNoteEdit on 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. An IntersectionObserver sentinel about eight notes from the visible end prefetches the next page when nextCursor is 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 shows shops.empty immediately. The 30-second visible-tab poll, visibilitychange, persisted pageshow, and pull-to-refresh fetch page 1 only, without a cursor; applying page 1 does not replace already-loaded older pages. Fetches via fetchMessages, renders public stills via forumPhotoSrc; composer previews stay blob URLs in photoUrls, and a shop-note save clears that id's blob URLs while photoVersions busts that id. Loads rateDay via the shared useSpotRate() hook on mount (failure leaves rateDay null), posts via fetchComposeTarget then postMessageInvoice (1 sat to 21.gifts, payHost: composer) for anyone below verified, otherwise postMessage with a photos array so postMessage dual-sends { photo, photos } (non-empty photos wins; max 10) or postMessageVideo (multipart clip); composer submit is ignored while a note POST is in flight (sync notePostInFlightRef, not only the posting prop); prepares picks via prepareForumPhoto / isForumVideoFile / prepareForumVideo; owns photoDrafts (plural, not photoDraft), placeDraft, and videoDraft / videoUrls; onPickFiles appends stills and sets formError tooMany when the selected File list (not successful prepares) would exceed 10, preparing only the first remaining slots; video xor stills; video-only posts are allowed. Pay invoices via postMessageInvoice (optional text when the reply composer pays) and waits on fetchPublicMessage while the pay sheet is open (no attempt cap; aborts in-flight wait on Close / clear). A top-level note passes sinceSats and closes when sats rises. An existing reply passes sinceReceivedSats and closes when receivedSats rises. After that rise, the row is merged into loaded replies/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's sats rose 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 passes repayLink so 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 passes unpaidNewCount to ForumBoard (0 while unpaid is selected or messages are still null). After a successful living-room post with created.sats === 0, switches mode to All so the author sees the note, including a positive goalSats Ask, because Active and Most popular hide a note that has not received sats. If All is already selected, loaded pages and nextCursor stay. Shops already lists with mode: 'all' and does not switch. The sheet clears when the pay target is no longer in the visible parent list and not in loaded replies (mode change, collapse, or delete), not when Active merely hides the parent note. Also polls GET /forum/messages until the merged list is payable (8 attempts, 2s; local extras kept until GET echoes), cancelled-flag fetch like StatsLoader. Silently re-fetches on visibilitychange (hidden→visible), on pageshow when persisted is true, on a FORUM_LIST_POLL_MS visible-tab interval, on FORUM_HOME_EVENT (wordmark / Menu Home while already on /welcome), and when the board pull-to-refresh calls onRefresh — 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) < 8 is at-top; window.scrollY is only the no-shell fallback) and hasUnseenForumPosts is true, the fetch is held and ForumBoard shows New posts; at the top the list is applied. With a session, fetches GET /forum/notifications via existing fetchNotifications (cancelled-flag fetch like other ForumLoader loads) and, when an unread moderator_appointed row exists (readAt === null), drives the ForumBoard pill (moderatorAppointedAvailable / onShowModeratorAppointed); click marks that row read via markNotificationRead and clears the flag, staying on /welcome without 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 from account.forumLawsDismissed and persists dismiss via dismissForumLaws (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 via onDeleted / deleteMessage without 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 shows forum.errorEmpty and invoices nothing); unpaid postMessage with inReplyTo only 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 sets empty, 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 calls markVisibleForumNoteRead; expanding still calls markNotificationsReadForMessage. 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. Uses nextPostRequirement so a missing name, username, wallet (api lightning-address), or rules agreement opens RequirementsOverlay (no Skip) before a post or reply retries. After a successful top-level post or reply, sets hasPosted: true on 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 sets empty, 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 to ForumBoard, so the living-room composer lives in the writer; every successful own post calls its onClose: from applyCreatedNote when 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 (startPayPoll with ownPost) when the payment itself created a text-only post. A failed post leaves it open with its error. Optional feed ('living-room' default, 'shops') and country (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. ShopsScreen remounts the loader when the country changes. Optional onShopsChanged runs 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, or null. Owns draft/askDraft/composeIntent/askStep/askCadence/placeDraft/photoDrafts/videoDraft/photoUrls/videoUrls/posting/formError/feedMode/loaded-pages/nextCursor/pay/expand/replies/refreshing/rateDay state, the No gifts yet last-visit stamp, and retry attempts. askCadence defaults to once and returns to once after the visitor's own compose is paid (postAfterPay or switchToAll in the pay poll) and in applyCreatedNote. A gift or a reply does not clear it. Empty text without photos and without a video sets empty; trimmed text longer than 8000 characters sets tooLong and does not call postMessage / 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 shows forum.errorEmpty and invoices nothing) and does not set empty, including when the parent omits accountId. A non-exempt reply with text and an empty amount still invoices 1 sat instead of setting amount. 0 is billed as 1 sat. Non-digits and overflowing amounts still set amount (forum.errorReplyPayment). When the parent omits accountId, an unpaid postMessage is 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 fill payDraft. A CannotReceiveError (api code cannot_receive) on a gift or a paid reply maps to authorWallet; on a posting fee (the 1 sat to 21.gifts before a note or a reaction) it stays request; a WalletRequiredError (api code wallet_required) on a gift, a paid reply, or a posting fee opens the RequirementsOverlay wallet step; a missing or deleted note (NoteDeletedError, HTTP 404) maps to deleted on the pay sheet and on a paid reply; a 404 on the platform compose-target invoice stays request; other invoice failures stay request; rate limit stays rateLimit. Revokes photo and video blob URLs on unmount. May POST /me/forum-laws-dismissed. After a successful top-level post or reply, writes hasPosted: true on the session account only when the session token is unchanged and an account is still present (no persist-flag POST). On shops, passes shopComposer so the board mounts ShopAddWizard, shopPlaceEdit / onShopPlaceUpdated so a saved or cleared pin updates that row, and shopAccountEdit / onShopAccountUpdated so a saved or cleared shop account updates that row. For a moderator on every feed, including the living room, passes shopNoteEdit / onShopNoteUpdated. Passes repayLink on every feed (the viewer's own credit links to /loans/repay as 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, and rateDay to ForumBoard. Stamps last visit on unpaid; mode is not persisted. Does not pass Error.message to 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 (/login for a signed-out mode or page that needs a session, /setup/rules for missing rules) use returnToView: 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 sets PaySheetFailed around ForumBoard until 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). composerShopError maps shop name/address 400s outside Shops to shopElsewhere.
  • First post free: while the signed-in member is below verified and has no missing requirements, the loader calls fetchComposeTarget once (again when the session, role, or missing list changes) and passes firstPostFree to ForumBoard for the hint; a failed call shows no hint. On Post below verified (and without a paid fee waiting), it calls fetchComposeTarget again, and that answer also decides the hint; an older mount answer that arrives later is ignored. When that answer has firstPostFree, it creates the note directly with postMessage or postMessageVideo (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 with PostFeeRequiredError, 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 rulesAgreedAt timestamp (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.setup only.

Function: nextOnboardingPath

  • Purpose: Picks /setup/name, /setup/username, /setup/rules, or /welcome from account.setup. setup === 'wallet' maps to name, username, rules, or /welcome from 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's setup === 'lightning-address' (which follows the name step, filled or skipped) resolves to username, rules, or /welcome without checking the name again. Other values stay a 1:1 map (skips advance setup without clearing missing). Username still cannot be skipped.
  • Inputs: account with required setup and missing.
  • 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 (name only).
  • Returns / side effects: Updated Account from POST /me/setup/skip; callers merge setup and missing into the auth store.
  • Used by: The NameForm onboarding Skip button.

Function: fetchMember

  • Purpose: Loads a signed-in member profile by account id.
  • Inputs: Bearer session and accountId.
  • Returns / side effects: Validated MemberProfile, including postCount, replyCount, optional shopCount, and optional creditCount, or null on 401/404. Throws MissingRequirementsError on 409. Hits /forum/members/:id. A profileMessage that fails forumMessageSchema (an About me saved empty: no text, no media, 0 sats) reads as null, so the profile renders with the About me empty state instead of failing; the drop is counted in one console.warn without content.
  • Used by: MemberProfileLoader, ProfileScreen, and ViewProfileLoader (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 forumListSchema and returns the messages newest-first, capped by the api at 200. Rows are parsed one by one (forumMessageRowsSchema): a note that fails forumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in one console.warn without 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 as fetchMessages; a 409 missing_requirements throws MissingRequirementsError as in fetchMember / 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 forumListSchema and returns the messages newest-first, capped by the api at 200. A 401/404 uses the same visitor-facing message-list failure as fetchMessages; a 409 missing_requirements throws MissingRequirementsError as in fetchMember / 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 forumListSchema and returns the messages newest-first, capped by the api at 200. A 401/404 uses the same visitor-facing message-list failure as fetchMessages; a 409 missing_requirements throws MissingRequirementsError as in fetchMember / 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 forumListSchema and 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 include parentId. Rows are parsed one by one (forumMessageRowsSchema): a note that fails forumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in one console.warn without 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 as fetchMessages; a 409 missing_requirements throws MissingRequirementsError as in fetchMember / fetchMessages.
  • Used by: MemberProfileScreen.

Function: parseMissingRequirements

  • Purpose: Parses a 409 { error: 'missing_requirements', missing: [...] } body.
  • Inputs: Unknown JSON body.
  • Returns / side effects: MissingRequirementsError or null.
  • 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-address key, which means the member cannot receive yet (the wallet step of nextPostRequirement).
  • Inputs: missing array from the api body.
  • Returns / side effects: Error instance with missing field; 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 show login.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 show forum.errorNoteDeleted instead 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 code wallet_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's code, 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/amount it shows the pos.needWallet alert. On a forum, member, or public-note gift, paid reply, or posting fee it opens the RequirementsOverlay wallet step; on /loans/repay it becomes the wallet-unavailable repayment state; in the inbox it shows the wallet-required alert link to /wallet.
  • Used by: throwIfWalletAnswer (so postMessageInvoice, postRepaymentDue, postConversationInvoice, and createPosCharge), PosAmount, useLoanRepay, ForumLoader, MemberProfileScreen, PublicMessageThread, and InboxLoader.

Function: CannotReceiveError

  • Purpose: Typed error for the api's answer with code cannot_receive (CANNOT_RECEIVE_CODE; HTTP 400, or 409 on a habit donation): the receiving wallet cannot take this payment. Recognised by the body's code, 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 to authorWallet, and so does the habit pay sheet (MemberHabits); sendHeartTip maps it to author_cannot_receive (forum.payErrorAuthorWallet under the heart); /loans/repay (useLoanRepay) shows loans.errorCannotReceive; /pos/amount shows 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_closed distinct 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 to ForumPayError: 'creditClosed', while sendHeartTip maps it to credit_closed; both paths clearly say that the loan no longer collects.
  • Used by: postMessageInvoice, ForumLoader, MemberProfileScreen, PublicMessageThread, and sendHeartTip.

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: code wallet_required (WALLET_REQUIRED_CODE) throws WalletRequiredError, code cannot_receive (CANNOT_RECEIVE_CODE) throws CannotReceiveError. Status alone and the error text 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, and createPosCharge.

Function: isWrongAccountError

  • Purpose: Detects a wrong-account rejection (WrongAccountError or an Error whose message is exactly WRONG_ACCOUNT_ERROR).
  • Inputs: error unknown.
  • Returns / side effects: true for that instance or exact message; false otherwise.
  • 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. usePasskeyLogin may signal the credential unknown and sets status unknown. LoginCard shows the unknown login card. ViewProfileClaim shows view.claimError and Try again calls authenticate(), never register.
  • Used by: finishPasskeyAuthentication, usePasskeyLogin.

Function: isUnknownCredentialError

  • Purpose: Detects an unknown-credential rejection (UnknownCredentialError or an Error whose message is exactly UNKNOWN_CREDENTIAL_ERROR).
  • Inputs: error unknown.
  • Returns / side effects: true for that instance or exact message; false otherwise.
  • 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's code or exact error.
  • 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), or key_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 RecoveryError with a readonly kind and the message recovery_<kind>.
  • Used by: startPasskeyRecovery, finishPasskeyRecovery, putRecoveryShare, the recovery flow on /recover, and useSocialRecoverySetup.

Function: RecoveryPendingError

  • Purpose: Typed error for the api's HTTP 409 answer with code recovery_pending on authenticate finish: the passkey belongs to a social recovery that is not finished yet. Recognised by that status together with the body's code, never by text. Unlike UnknownCredentialError, 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, then name, then username, then wallet). The api's lightning-address key means the member cannot receive yet and maps to the wallet step (the member's own in-app wallet). The api's wallet key is ignored; it is not a posting overlay field.
  • Inputs: missing array from the account or a 409 body.
  • Returns / side effects: 'rules', 'name', 'username', 'wallet', or null. No side effects.
  • Used by: ForumLoader, MemberProfileScreen, RequirementsOverlay flow.

Function: nextContactRequirement

  • Purpose: Picks the next field to collect before a contact send (rules before name before username). A missing wallet (the api's lightning-address key) returns null — contact does not open an overlay for it.
  • Inputs: missing array from the account or a 409 body.
  • Returns / side effects: 'rules', 'name', 'username', or null. No side effects.
  • Used by: ContactLoader, RequirementsOverlay flow.

Function: RequirementsOverlay

  • Purpose: Modal to add a missing name (NameForm profile), username (UsernameForm), or agree to rules before retrying a post. No Skip. The wallet step 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 labeled ButtonLink Open your wallet (requirements.walletOpen) to /wallet and 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-label from requirements.nameTitle, requirements.usernameTitle, requirements.rulesTitle, or requirements.walletTitle. The wallet step shows requirements.walletBody and a labeled ButtonLink Open 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.balanceTitle 21.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.menuTitle Everything 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). Reads session and account.walletIntroSeen from useAuthStore and useWallet().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 longer connecting (so the balance step is not lost to a wallet that is still opening), blocked is false, and no other aria-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, so wallet_tour_step is recorded only once a step's own target was measured: a step skipped because its target is gone is never recorded as shown. A fixed inset-0 z-[95] layer takes every click; inside it an aria-hidden ring box (fixed rounded-2xl ring-2 ring-white, a shadow-[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; its style sets only the measured top, bottom, left, and width (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 (style top or bottom only). 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 primary Button 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 on resize, on any scroll (capture), and on every change of the page (MutationObserver on document.body). Skip, Escape, and Got it set walletIntroSeen: true on the stored account at once, so the tour never comes back in this session even when the request fails, and call markWalletIntroSeen (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. SignedInChrome mounts it on /welcome only, 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 a Button that dismisses, opens the forum home writer and focuses its text field (requestForumCompose / FORUM_COMPOSE_EVENT); it does not navigate. No Skip-forever. Hidden when hasPosted is true or omitted (older api) and while setup is not null.
  • Inputs: onDismiss.
  • Returns / side effects: Dialog UI (role="dialog" aria-modal="true", fixed inset card z-50). Title/aria-label from introduce.title; body introduce.body; CTA introduce.cta as catalog Button type="button" size="lg"; close introduce.close. Does not write forumLawsDismissed or any account field.
  • Used by: SignedInChrome.

Function: SocialRecoveryPromptOverlay

  • Purpose: Modal on the forum home (/welcome) that tells a grant member (funding admitted, or trial for today) whose account has no Social Recovery yet (socialRecoverySetUp === false) to set it up, and names the day from which grant payouts require it. SignedInChrome mounts it on /welcome only, 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 scrim inset-0 z-50 bg-app-overlay, Card maxWidth="sm"). Title and aria-label socialRecoveryPrompt.title; an icon-only ghost close X (socialRecoveryPrompt.close) calls onDismiss; body socialRecoveryPrompt.body; a labeled Button size="lg" Secure my account (socialRecovery.secure) calls onDismiss and router.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, and useSpotRate (only while a payment is showing).
  • Returns / side effects: null without a payment. Otherwise a portal to document.body: a pointer-events-none fixed inset-x-0 top-3 z-[90] row centring a max-w-sm card (role="status", animate-slide-down from the top, rounded-2xl border border-app-success/40 bg-app-card shadow-lg) with lucide ArrowDownLeft in an h-9 w-9 bg-app-success/15 text-app-success circle, 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 one next/link to /wallet that also closes the banner. An icon-only ghost IconButton X (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-received pin 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 calls useChromeBack().setOverride with labelKey nav.back, over: true, and an onClick that calls the latest onBack (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 (and false on unmount), so SignedInChrome can take the Menu out of reach behind it. Reads account.username from useAuthStore, 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: null while closed. It opens when takeMoveFundsRequest finds a request, on mount and on MOVE_FUNDS_EVENT (a ?move=1 link through MoveFundsLink, also one followed before signing in, or the Receive view's Move Bitcoin from another wallet), and then removes move from the address with history.replaceState. It takes a request only while signed in, done with onboarding (nextOnboardingPath is /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 an AppShellOverlay over the page body under the header row (absolute inset-0 z-[95] bg-app-overlay) holding a role="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 and sm:rounded-3xl centred on a wider frame): four progress dots (aria-hidden, with an sr-only Step N of 4, moveFunds.progress) and an icon-only ghost X (moveFunds.close, Close). Steps: 1 Bring your Bitcoin here (moveFunds.introTitle), the text moveFunds.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) through MoveFundsBack as 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 records wallet_move_closed with that step under the ending session (LOGOUT_EVENT, sent by logLogout before the session is cleared). Under the Playwright-only ?visual=move-arrived pin 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 Tab KeyboardEvent; and panel, the modal dialog HTMLElement.
  • 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: LoanPayMore and PaySheet.

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.tsx also holds PAY_SHEET_SUCCESS_MS (1400 ms) and PAY_SHEET_HOLD_MS (PAY_SHEET_SUCCESS_MS plus MOTION_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, or null), successTitle (Sent to {name}, Lent to {name}, Paid and posted, or Sent), onClose (the member left the payment), optional onSentChange (told whether the pay slot has a payment out or on its way, for usePaySheetHold), optional stored (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. Reads useTranslations, useNumberFormat, useFiatPreference, usePresent (whether the host's Collapse still shows it), and the flag of an enclosing PaySheetFailed.
  • Returns / side effects: An AppShellOverlay layer over the frame body under the header row (absolute inset-0 z-[95], data-pay-sheet-layer open or closed): a dimmed scrim (bg-app-overlay, a button with forum.payClose that is not in the tab order) and a role="dialog" aria-modal panel labelled by the title (data-pay-sheet pay or success, 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 and sm:rounded-3xl sm:border centred on a wider frame). The panel shows a decorative handle, the title (h2, centred) with the icon-only ghost X (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, otherwise formatFiatDisplay of 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-full to translate-y-0, the scrim fading in; 280 ms ease-glide; on a wide frame a short rise with a fade). Close, a tap on the scrim, and Escape call onClose once 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 is inert while 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 a Collapse with holdMs PAY_SHEET_HOLD_MS; when that fold closes without such a close (usePresent turns false) while the pay slot reports a send that went out (usePaySheetSent paid), the pay step fades into the success step (Swap; role="status": a green CircleCheck, successTitle, and the amount with its fiat), which stays until PAY_SHEET_SUCCESS_MS after the close, then the sheet slides away; Escape, a tap on the scrim or Close lets it go at once without calling onClose again. A send still pending at 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 gone PAY_SHEET_SUCCESS_MS after the close. A host close with no send out (a failed check, another thread), or one under PaySheetFailed (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), and InboxScreen.

Function: usePaySheetClose

  • Purpose: Gives a control inside a PaySheet the 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 onClose and slides it away without a success step, because the member left the payment), or null outside a pay sheet.
  • Used by: AddBitcoinButton.

Function: usePaySheetSent

  • Purpose: Lets the pay slot tell the PaySheet around 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; WalletPay passes useWalletPay's sent), or null outside a pay sheet. When the host then closes the payment, a paid send shows the success step; a pending one 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) and children (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 PaySheet that 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 (around ForumBoard; 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, or null.
  • Returns / side effects: { held, closedByMember, sentChange }. The host passes sentChange to the sheet as onSentChange with 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 (a paid or pending send) and without the member closing it, held is its key for PAY_SHEET_SUCCESS_MS, then null; 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 beside ForumReplyPayPage, keyed by the card) and InboxScreen (the amount row, keyed by the invoice's pr).

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 nearest OpenReceiveProvider, and useRouter.
  • 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 an OpenReceiveProvider with an opener (the forum home), otherwise router.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, or null while the page has no wallet view) and the page.
  • Returns / side effects: The page under that opener. No network.
  • Used by: WelcomeScreen (its useWalletPanel Receive, after closing an open writer; null while the member has no wallet).
  • Purpose: Opens the Receive view once when /wallet was 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, removes receive from it with history.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, then fetchMemberActivity even when the member has no wallet yet. It does not prefetch post/reply/shop/credit feeds; postCount, replyCount, optional shopCount, and optional creditCount arrive 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. fetchMember 409 missing_requirements → /setup/rules (returnToView). fetchMemberActivity 409 missing_requirements → /setup/rules (returnToView). Any other activity error (other than MissingRequirementsError) keeps the card and both charts show their error copy (profile.chartError / profile.loanChartError). MissingRequirementsError still goes to /setup/rules.
  • Used by: MemberProfilePage.

Function: MemberProfileScreen

  • Purpose: Signed-in member identity card (gift chart from given and received activity, then LoanBalanceChart directly under it with the same activityFailed flag, About me inside the card not as a forum post (Translate, Languages icon, when profileMessage.id or aboutMessageId is set), name, location, public username@21.gifts (profile.giftsHeading), role pill, optional funding-program icon-only button (pressing it reveals that one sentence; that result is the separate screenshot state funding-program-open) when fundingReviewedAt is a number, copy-profile-link, and post/reaction count toggles) plus stacked ForumBoard activity feeds loaded on demand. Location is read-only on someone else's card (location.unset when empty). When the signed-in account id matches, the owner edits the centered name and location. The owner About me editor passes omitEmptySlotAdds and imageEpoch, so empty profile-photo and wide-image adds stay on the header and a header save reloads those slots while the editor stays open. Public AboutMeSection (name={profile.name}) shows filled text and/or photo, or omits the heading when neither. A labeled Message Button (profile.message) with a decorative Mail icon sits on the card when another member has a profileMessage — 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-note ForumBoard; the posts feed lists that note when present. A feed shorter than its profile count gets a muted profile.activityLatest truncation line. Posts show React and do not show Send Bitcoin; a payable reply card in the replies feed shows Gift (disabled with CannotReceiveLabel when 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 with parentId navigates to /messages/{parentId}. Verified members may POST /messages unpaid 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 shows forum.errorEmpty and invoices nothing); everyone else invoices ≥ 1 sat with optional text; typed 0 is always billed as 1 sat even for exempt. When a note omits accountId, a text reply with an empty amount tries unpaid POST /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 use forumPhotoSrc. About me / loadPhoto stays fetchMessagePhoto (and fetchPublicMessagePhoto when signed out). ForumBoard does not paint photos on nested replies. Loads rateDay via useSpotRate (failure leaves null) and passes it to every ForumBoard so 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 passed stored object 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). Uses nextPostRequirement so a missing name, username, wallet, or rules agreement opens RequirementsOverlay (no Skip) before a reply retries. When a username is set, a centered QrCode (label profile.giftsQr) under the address encodes openCryptoPayQrValue (https://<domain>/pl/?lightning= plus the uppercase LNURL of https://<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 sticker Button under the QR opens ShopStickerOverlay with the same openCryptoPayQrValue and the public handle, including on a smartphone; Close and Escape unmount it. On the full member view, an own credit uses the ForumBoard Pay 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.shopCount appears after reactions only when optional shopCount > 0 and 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.creditCount appears after shops only when optional creditCount > 0 and loads an on-demand ForumBoard from GET /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 pass shopNoteEdit. Credit notes remain in Posts. Credits are not prefetched.
  • Inputs: MemberProfile (includes aboutMe, aboutMeHasPhoto, and location) plus received, donated, owed, and credit series (loan series default []); optional factsOnly (default false); optional omitPills (default false; /profile does not pass it); optional loadPublicList for the share link's public posts, replies, shops, and credits; optional loadAboutPhoto for that link when aboutMeHasPhoto is true and the profile note has no id (fetchViewAboutMePhoto); optional activityFailed (default false), passed to both charts as failed; session/account from the auth store. The full card loads public GET /pictures/:id and GET /banners/:id (no bearer). factsOnly does not. Public AboutMeSection hasPhoto from aboutMeHasPhoto / profileMessage.hasPhoto with loadPhoto (fetchMessagePhoto, and fetchPublicMessagePhoto when signed out). Public Translate uses profileMessage.id, or aboutMessageId when the share link has no profile note. Optional shareViewKey is the /view/:viewKey route 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/spot into rateDay via useSpotRate; posts, replies, shops, and credits use forumPhotoSrc; About me stays a fetchMessagePhoto blob (and fetchPublicMessagePhoto when signed out); may POST gift or posting-fee invoices, conversations, and replies and navigate to /messages?c= or a reply's /messages/{parentId}. When activityFailed is true and a series is empty, that chart shows its error copy. factsOnly still has no charts. factsOnly returns only the role pill, the funding-program icon, the gifts address, QR, Shop sticker, count buttons, the activity feed, and RequirementsOverlay — no heading, charts, About me, name, location, Message, or staff block. /profile, /members/:id, and /view/:viewKey each render this screen once. Owner edits appear when the signed-in account id matches the profile. A WalletRequiredError (api code wallet_required) on a gift, a paid reply, or a posting fee opens the RequirementsOverlay wallet step. A paid reaction keeps its text and amount in the disabled form behind the reaction pay sheet (replyPayPreview on ForumBoard); 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's sparkInvoice so 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 sets empty. A MissingRequirementsError while loading a feed goes to /setup/rules with returnToView. 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 sets empty, and one with text posts unpaid or pays only the 1 sat posting fee.
  • Used by: MemberProfileLoader, ProfileScreen, and ViewProfileLoader. ProfileScreen renders this screen once and does not pass factsOnly.

Function: MemberProfilePage

  • Purpose: Route /members/[accountId] with profile onboarding gate and signed-in chrome.
  • Inputs: Dynamic accountId.
  • Returns / side effects: AppShell with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate around MemberProfileLoader.
  • Used by: App Router.

Function: proxyMeSetupSkipPost

  • Purpose: Proxies POST /me/setup/skip to the api.
  • Inputs: App Router request (Bearer + { step }).
  • Returns / side effects: Upstream response.
  • Used by: /me/setup/skip route.

Function: proxyMembersGet

  • Purpose: Proxies GET /members/:accountId to 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/posts to the api.
  • Inputs: App Router request and accountId.
  • Returns / side effects: Upstream response via /members/${encodeURIComponent(accountId)}/posts.
  • Used by: /forum/members/[accountId]/posts route.

Function: proxyMembersShopsGet

  • Purpose: Proxies GET /members/:accountId/shops to the api.
  • Inputs: App Router request and accountId.
  • Returns / side effects: Upstream response via /members/${encodeURIComponent(accountId)}/shops.
  • Used by: /forum/members/[accountId]/shops route.

Function: proxyMembersCreditsGet

  • Purpose: Proxies GET /members/:accountId/credits to the api.
  • Inputs: App Router request and accountId.
  • Returns / side effects: Upstream response via /members/${encodeURIComponent(accountId)}/credits.
  • Used by: /forum/members/[accountId]/credits route.

Function: proxyMembersRepliesGet

  • Purpose: Proxies GET /members/:accountId/replies to the api.
  • Inputs: App Router request and accountId.
  • Returns / side effects: Upstream response via /members/${encodeURIComponent(accountId)}/replies.
  • Used by: /forum/members/[accountId]/replies route.

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, calls fetchMe, and evaluates hydratesLocked(account).
  • Returns / side effects: { ready }. A valid account whose wallet is already open, or to which the wallet gate does not apply, goes through setAuth; otherwise setLockedSession keeps the stored token (and the account's name or username as lockedName, for the login card's greeting) while leaving active session and account null. WrongAccountError calls clearAuth and setWrongAccount(true) then becomes ready so the stale token is not left. Generic /me failures log and do not set the flag. ready is false until storage//me has 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 logo centers that image at 48px and sets error correction H; profile cards pass profileQrLogo, the inlined apple-touch icon.
  • Inputs: value (required) and label (required accessible name, already translated). Optional logo.
  • Returns / side effects: React element.
  • Used by: PayLinkScreen shows an invoice QR only when the user agent is not a smartphone. PosTill, ShopScreen, MemberProfileScreen, ViewProfileScreen, WalletReceive, and WalletOwnAddress render this QR when the value exists, including on a smartphone. FondDeposit renders the Fond wallet's on-chain deposit address as a bitcoin: QR on every device (the documented Fond exception in CONTRIBUTING "Payment QR vs wallet links"). MoveFundsSheet renders the same address QR only off a smartphone. HeldSharesScreen shows a kept share's code on /settings/held-shares, and SocialRecoveryScreen shows 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 /wallet and 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]), which WalletSend makes 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 a from-black/80 gradient: by default Point the camera at a Bitcoin QR code, or the hint key in copy. The viewfinder only shows where to aim: every frame is read whole. Reads about eight frames a second: with the browser's BarcodeDetector when it lists qr_code among its formats, otherwise with jsqr on 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.denied otherwise) 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.unavailable otherwise). Both are role="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 with showing when the preview plays while the camera delivers pictures, or the picture comes back, denied or unavailable when the alert replaces the preview, or paused when 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. Optional copy (QrScannerCopy: catalog keys hint, denied, unavailable, and optional hintVars, the placeholder values of hint) 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 the heldShares.* wording), and OldWordsInput (two share codes on /recover and /settings/previous-wallets/[sparkPubkey], with Scan code {n} of 2 and the recover.* 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), blocking APP_HEIGHT_BOOTSTRAP_SCRIPT then THEME_BOOTSTRAP_SCRIPT in <head>, suppressHydrationWarning on <html>, token body classes (bg-app-bg text-app-fg), and AppHeightSync. Nest is Locale → NumberFormat → FiatPreference → Theme. Inside ThemeProvider: AccountPreferenceSync, LocaleRouteSync, PushOpenListener, WalletSync, FondPayoutSync, FondDepositSync, InteractionLog, RememberWalletReturn in Suspense, MoveFundsLink in Suspense, then ViewHistoryRoot around the page children.
  • Inputs: children React nodes. Calls getRequestLocale() for html lang and messages, getRequestNumberFormat() for the number-format provider, getRequestFiat(locale) for the fiat provider, reads the x-nonce request header that middleware sets.
  • 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 (window undefined).
  • Used by: useAuthStore.clearAuth.

Function: fetchTrustChain

  • Purpose: GET /trust/graph (same-origin proxy of api GET /trust-chain) with Bearer and parse the Trust Chain graph. Optional around loads one hop (?around=).
  • Inputs: Bearer sessionToken, optional around account 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/verify with { accountId, confirmedName } so a moderator verifies a basis member.
  • Inputs: Bearer sessionToken, subject accountId, confirmedName.
  • Returns / side effects: { id, name, role }. Throws visitor copy on any failure.
  • Used by: MemberVerifyScreen.

Function: postTrustPropose

  • Purpose: POST /trust/propose-moderator with { accountId }.
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: { id, name, role }. Throws visitor copy on any failure.
  • Used by: MemberTrustActions.

Function: postTrustConfirm

  • Purpose: POST /trust/confirm-moderator with { accountId } (caller must not be the proposer).
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: { id, name, role }. Throws visitor copy on any failure.
  • Used by: MemberTrustActions, ProposalsScreen.

Function: postTrustReject

  • Purpose: POST /trust/reject-moderator with { accountId }.
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: { id, name, role }. Throws visitor copy on any failure.
  • Used by: ProposalsScreen.

Function: postTrustAppoint

  • Purpose: POST /trust/appoint-moderator with { accountId } (founder only).
  • Inputs: Bearer sessionToken, subject accountId.
  • 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 api GET /trust/proposals) and parse moderatorProposalsResponseSchema.proposals. Next.js forbids a route.ts beside /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 } via fundingApplyResponseSchema. Role basis is 403. 400 About me is required / About me photo is required / Location is required are rethrown; other failures use visitor copy Could 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 status none or rejected sees the walk and calls postFundingApply after 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 } via fundingWithdrawResponseSchema; after a withdrawal the status is none (the same enum as every other owner funding answer).
  • Inputs: Bearer sessionToken.
  • Returns / side effects: Updated OwnerFunding. Throws Unauthorized on 401 and Conflict on 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 copy Could not withdraw. Please try again.
  • Used by: FundingWithdrawControl on /grants, after the member confirms Withdraw my application or Leave the grant.

Function: fetchFundingPayoutDays

  • Purpose: GET /funding/payout-days (same-origin Bearer proxy of api GET /funding/payout-days) and parse fundingPayoutDaysResponseSchema. Next.js forbids a route.ts beside /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 copy Could 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 api GET /shops/activity/shops) and parse shopActivityShopsSchema. today and lastChargeDay must 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 copy Could 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 api GET /funding/applications) and parse fundingApplicationsResponseSchema.applications. Next.js forbids a route.ts beside /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 parse fundingApplicationDetailSchema.
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: Account, grant, and living-room posts. Rows are parsed one by one (forumMessageRowsSchema): a note that fails forumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in one console.warn without its content, and the other rows still render; only an invalid envelope fails the detail. Throws visitor copy Could 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 api GET /funding/daily-roster) and parse dailyRosterSchema. Next.js forbids a route.ts beside /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. address stays in the JSON and is not rendered. defaultAmountUsd is a finite number. Moderator rows stay out of recipients.
  • Inputs: Bearer session.
  • Returns / side effects: Parsed roster. Throws funding.daily.forbidden on api Forbidden. Throws visitor copy Could 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/comment with { comment } and parse the returned roster.
  • Inputs: Bearer session, comment text.
  • Returns / side effects: Updated roster. Throws a funding.daily.* catalog key. Maps api Invalid comment to funding.daily.invalidComment. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentCommentScreen.

Function: saveDailyRosterPayments

  • Purpose: POST /funding/daily-roster/payments with { enabled } and parse the returned roster. enabled is a boolean.
  • Inputs: Bearer session, enabled.
  • Returns / side effects: Updated roster. Throws a funding.daily.* catalog key. Maps api Invalid payments switch to funding.daily.invalidSwitch. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentAmountsScreen.

Function: addDailyRosterRecipient

  • Purpose: POST /funding/daily-roster/recipients with { accountId, amountUsd } and parse the returned roster. amountUsd is 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. Maps Invalid person or amount, Unknown person, Person has no Lightning address, and Address already listed. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentAmountsScreen.

Function: updateDailyRosterRecipient

  • Purpose: POST /funding/daily-roster/recipients/update with { 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. Maps Invalid address or amount and Unknown address. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentAmountsScreen.

Function: deleteDailyRosterRecipient

  • Purpose: POST /funding/daily-roster/recipients/delete with { address } and parse the returned roster.
  • Inputs: Bearer session, stored address.
  • Returns / side effects: Updated roster. Throws a funding.daily.* catalog key. Maps Unknown address. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentAmountsScreen.

Function: addDailyRosterModerator

  • Purpose: POST /funding/daily-roster/moderators with { accountId, amountUsd } and parse the returned roster. amountUsd is 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. Maps Invalid person or amount, Unknown person, Person has no Lightning address, and Address already listed. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentModeratorsScreen.

Function: updateDailyRosterModerator

  • Purpose: POST /funding/daily-roster/moderators/update with { 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. Maps Invalid address or amount and Unknown address. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentModeratorsScreen.

Function: deleteDailyRosterModerator

  • Purpose: POST /funding/daily-roster/moderators/delete with { address } and parse the returned roster.
  • Inputs: Bearer session, stored address.
  • Returns / side effects: Updated roster. Throws a funding.daily.* catalog key. Maps Unknown address. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentModeratorsScreen.

Function: saveDailyRosterModeratorPayments

  • Purpose: POST /funding/daily-roster/moderators/payments with { enabled } and parse the returned roster. enabled is a boolean.
  • Inputs: Bearer session, enabled.
  • Returns / side effects: Updated roster. Throws a funding.daily.* catalog key. Maps api Invalid payments switch to funding.daily.invalidSwitch. Any other failure is funding.daily.saveError.
  • Used by: DailyPaymentModeratorsScreen.

Function: postFundingAdmit

  • Purpose: POST /funding/admit with { accountId } (staff). Target pending or trial.
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: FundingDecisionResult. Throws Error(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 copy Could 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/reject with { accountId } (staff). The subject may re-apply.
  • Inputs: Bearer sessionToken, subject accountId.
  • Returns / side effects: FundingDecisionResult. Throws visitor copy Could 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: current graph, incoming hop from GET /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-side next/link (no prefetch), so without onExpand a plain click opens the member without a page load.
  • Inputs: chain: TrustChain, optional expandingId, optional onExpand.
  • 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-chain body: 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, optional expandingId, 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 null without 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") with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate screen="welcome" around TrustChainLoader. Graph HTTP is under /trust/graph (no route.ts beside 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 /statistics the only child is the payout link, and StatisticsScreen mounts the disclosure only for an account at least moderator when yesterday's person count is a number. The summary is staff.functions, a closed details / summary row. Children mount only while it is open.
  • Inputs: children.
  • Returns / side effects: data-testid="staff-functions". open while 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 ButtonLink to /members/[accountId]/verify and 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 closed StaffFunctions disclosure; they are not painted until it is opened.
  • Inputs: profile, optional onUpdated. 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. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="profile" around MemberVerifyScreen. The card has no back control. There is no route.ts beside this page.
  • Inputs: Dynamic accountId.
  • Returns / side effects: The stored-name check inside fill AppShell. Member HTTP stays on the existing fetchMember client.
  • Used by: Route /members/[accountId]/verify.

Function: MemberVerifyScreen

  • Purpose: Client stored-name check. Heading Verify. Renders null without 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. Otherwise fetchMember runs. 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 of SundayWritingGate; Sunday hides both. There is no Cancel. Chrome back does not post.
  • Inputs: Route accountId; session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. postTrustVerify(session, profile.id, identifyingName) only from Yes, with the untrimmed stored name, then router.push to /members/${profile.id}. No only router.push to /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/stats and 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 fails walletStatsSchema.
  • Used by: StatsLoader on /stats (inside the same Promise.all, tolerant so a failure only hides the Wallets section) and WalletUsageLoader on /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/usage and parses walletUsageSchema. 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: WalletUsageLoader on /stats/wallet.

Function: fetchGiftStats

  • Purpose: GET /gifts/stats and 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: StatsLoader and StatisticsScreen. Live amounts use fetchFxSpot, not this.

Function: fetchAccountActivity

  • Purpose: GET /me/activity with Bearer and parse accountActivitySchema (given + received, house gifts + forum zaps).
  • Inputs: sessionToken.
  • Returns / side effects: AccountActivity. Throws visitor copy Could not load gift stats. Please try again. on non-2xx, network, or schema failure.
  • Used by: useAccountTotals.

Function: fetchMemberActivity

  • Purpose: GET /forum/members/:id/activity with Bearer and parse activity for a member card.
  • Inputs: sessionToken, accountId.
  • Returns / side effects: AccountActivity. 409 missing_requirements → MissingRequirementsError. Other non-2xx / schema → visitor copy.
  • Used by: MemberProfileLoader, ProfileScreen, and ViewProfileLoader after a successful signed-in refetch.

Function: fetchViewActivity

  • Purpose: GET /view-key/:viewKey/activity with 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 shows profile.chartError.
  • Used by: ViewProfileLoader.

Function: fetchMe

  • Purpose: GET /me with the bearer session.
  • Inputs: sessionToken.
  • Returns / side effects: Account or null on 401. Throws WrongAccountError on 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=active with no Authorization header. Same page size (20) and cursor as the signed-in feed. HTTP 401 throws PublicForumUnauthorizedError.
  • Inputs: Optional limit and cursor.
  • Returns / side effects: { messages, nextCursor }. Rows are parsed one by one (forumMessageRowsSchema): a note that fails forumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in one console.warn without its content, and the other rows still render; only an invalid envelope fails the list. nextCursor is kept even when every row of a page was dropped; ForumBoard then puts the scroll sentinel on the empty-feed line so ForumLoader loads that next page.
  • Used by: ForumLoader when 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 Error whose name is PublicForumUnauthorizedError.
  • Used by: fetchPublicForumMessages, ForumLoader.

Function: fetchMessages

  • Purpose: GET /forum/messages with the bearer session, parse forumListSchema, and return the newest-first feed page as { messages, nextCursor } (including defaulted replyCount).
  • Inputs: sessionToken; optional { mode, limit, cursor, hashtag, country }. Always sends limit (default 20), sends mode when supplied, sends hashtag when non-empty, sends country (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: ForumFeedPage with nextCursor: null when 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 fails forumMessageSchema, such as an empty About me note (no text, no media, 0 sats), is dropped and counted in one console.warn without its content, and the other rows still render; only an invalid envelope fails the list. nextCursor is kept even when every row of a page was dropped; on the forum list ForumBoard then puts the scroll sentinel on the empty-feed line, so ForumLoader loads 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 (messages not an array, or an empty nextCursor).
  • Used by: ForumLoader, ShopTable.

Function: fetchExternalAuthorProfile

  • Purpose: GET /public-messages/:id/external-profile with no Authorization and parse externalAuthorProfileSchema.
  • Inputs: Forum message id.
  • Returns / side effects: { name, npub, nip05?, lud16? }, plus optional postCount, replyCount, shopCount, and creditCount, or null on 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-posts with no Authorization. After HTTP OK, require { messages: array }, parse the items with forumMessageRowsSchema (each item through forumMessageSchema; invalid items are skipped and counted in one console.warn without 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 throw MissingRequirementsError. No Bearer.
  • Used by: ExternalAuthorProfile.

Function: fetchExternalAuthorShops

  • Purpose: GET /public-messages/:id/external-shops with no Authorization. After HTTP OK, require { messages: array }, safeParse each item with forumMessageSchema, 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 throw MissingRequirementsError. No Bearer.
  • Used by: ExternalAuthorProfile.

Function: fetchExternalAuthorCredits

  • Purpose: GET /public-messages/:id/external-credits with no Authorization. After HTTP OK, require { messages: array }, safeParse each item with forumMessageSchema, 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 throw MissingRequirementsError. No Bearer.
  • Used by: ExternalAuthorProfile.

Function: fetchExternalAuthorReplies

  • Purpose: GET /public-messages/:id/external-replies with no Authorization. After HTTP OK, require { messages: array }, parse the items with forumMessageRowsSchema (each item through forumMessageSchema; invalid items are skipped and counted in one console.warn without 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 throw MissingRequirementsError. No Bearer.
  • Used by: ExternalAuthorProfile.

Function: fetchPublicMessage

  • Purpose: GET /public-messages/:id without a session, parse forumMessageSchema, and return one public forum note for the HTML note page. Optional sinceSats appends ?sinceSats= so the api can wait until the note has more sats (pay poll on a top-level note). Optional sinceReceivedSats appends ?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, sinceSats comes first.
  • Inputs: Forum message id (UUID string). Optional opts with sinceSats and sinceReceivedSats (each a finite integer ≥ 0; omitted / NaN / Infinity / negatives / non-integers skip that query) and signal (AbortSignal passed to fetch when provided).
  • Returns / side effects: ForumMessage, or null on 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.
  • Purpose: GET /links/<code> without a session. An invalid code, a non-OK response (400, 404, 409, or anything else), and an unexpected body return null. Network and JSON failures return null and do not throw.
  • Inputs: code string. Only ^[0-9a-f]{8}$ (case-insensitive) is fetched; other strings return null without a request.
  • Returns / side effects: { kind: 'message' | 'member', id } with id lowercased, or null.
  • Used by: ForumQuotedBody.

Function: fetchForumMessage

  • Purpose: GET /forum/messages/:id with a bearer session, parse forumMessageSchema, and return one forum note. Staff sessions receive soft-hidden rows (deletedAt / deletedBy); others get 404.
  • Inputs: sessionToken and forum message id (UUID string).
  • Returns / side effects: ForumMessage, or null on 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/replies without a session. After HTTP OK, require { messages: array }, parse the items with forumMessageRowsSchema (each item through forumMessageSchema; invalid items are skipped and counted in one console.warn without content), and return the survivors oldest-first. A hearts array, when present, is parsed with heartSenderSchema and 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-enumerable hearts property (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/photo with no Authorization when the index is 0 or ≤0, and GET /messages/:id/photo/{index}.jpg for indices 1–9. The blob is for MemberProfileScreen when that screen has no session. Public forum stills use forumPhotoSrc instead. Throws visitor copy on failure.
  • Inputs: Forum message id, optional zero-based index (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/replies with the bearer session. After HTTP OK, require { messages: array }, parse the items with forumMessageRowsSchema (each item through forumMessageSchema; invalid items are skipped and counted in one console.warn without content), and return the survivors oldest-first. A hearts array, when present, is parsed with heartSenderSchema and kept newest first.
  • Inputs: sessionToken, parent message id.
  • Returns / side effects: ForumMessage[] (empty if none survive) with a non-enumerable hearts property (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 omit role (schema defaults to basis). An optional via: '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 a Blob for URL.createObjectURL rendering.
  • Inputs: sessionToken, message id, optional zero-based index (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), ShopNoteEditControl when existingPhotos is shorter than photoCount.

Function: postMessage

  • Purpose: POST /forum/messages with bearer + { text, photo?, photos?, inReplyTo?, goalCurrency?, goalAmount?, place?, shopUsername? }, parse forumMessageSchema, and return the created message or reply (text and/or up to ten photos). Non-empty photos dual-sends photo as the first still plus photos. A non-blank string takenAt on a still is included; a blank or missing time is omitted. Optional goalCurrency and goalAmount go together on a top-level note, never as goalSats; omitted on replies and when either is missing. goalSats remains a field of the read note. Optional place is { lat, lng, label, address? } on a top-level note, where address contains street, house number, postal code, city, and country; omitted when unset. Replies must not send it. Optional shopUsername is sent only when the trimmed value without a leading @ is non-blank.
  • Inputs: sessionToken, input with text, optional { contentType, data, takenAt? } photo, optional photos array (max 10), optional inReplyTo parent id (thread composer only), optional goalCurrency and goalAmount (together, never goalSats), optional place (ForumPlacePin, top-level only), and optional shopUsername (leading @ stripped; omitted when blank).
  • Returns / side effects: ForumMessage. Omits inReplyTo, goalCurrency/goalAmount, place, and shopUsername from 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 throws Could not post your message. On 403 throws PostFeeRequiredError with the api error string when present, otherwise A reply needs a Bitcoin payment. On 404 whose api error is exactly No account with that username throws that string; any other 404 throws NoteDeletedError.
  • Interaction log: A created top-level note is recorded as post_created with its id, the number of photos, and whether it is an Ask; a reply as reply_created with its id and the parent id. The text is never recorded.
  • Used by: ForumLoader, MemberProfileScreen.

Function: postContact

  • Purpose: POST /contact/submit with bearer + { text }, parse contactSchema, and return the created message.
  • Inputs: sessionToken, text.
  • Returns / side effects: ContactMessage. On 400 uses the api error string when present; otherwise throws Could not send your message.
  • Used by: ContactLoader.

Function: isForumPhotoFile

  • Purpose: True when a browser File has 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 and prepareForumPhoto or WideImageCropper turns 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: file from <input type="file"> (camera or gallery).
  • Returns / side effects: Boolean. No side effects.
  • Used by: prepareForumPhoto, and the wide-image pick in AboutMeSection and ProfileScreen.

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 takenAt from Exif before the canvas encode, also when the camera handed it over without a mime type; PNG, WebP, HEIC, and HEIF set takenAt null. HEIC and HEIF become a JPEG when the browser can decode them.
  • Inputs: file accepted by isForumPhotoFile.
  • Returns / side effects: { ok: true, photo } (photo.takenAt is 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; WideImageCropper frames 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: imageWidth and imageHeight in source pixels.
  • Returns / side effects: { x, y, width, height }, or null when 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 current crop, and dx / dy in source pixels.
  • Returns / side effects: A new crop with the same width and height. x and y are 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 current crop, and factor.
  • Returns / side effects: The zoomed crop, or the same crop when the image has no fitting window. The window cannot grow past initialBannerCrop and 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: cropWidth in source pixels.
  • Returns / side effects: { width, height }. Width is min(1280, max(640, round(cropWidth))). Height is max(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: source canvas image, imageWidth, imageHeight, and the crop window.
  • Returns / side effects: { ok: true, photo } with contentType: 'image/jpeg', raw base64 data, and a previewUrl data 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, or toDataURL is 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 file isForumPhotoFile accepts, from the camera or the gallery), optional busy, onConfirm with { contentType: 'image/jpeg', data }, onCancel, and onError ('unsupported' or 'tooLarge').
  • Returns / side effects: The frame (profile.about.bannerCropHint Drag 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 calls encodeWideBanner and onConfirm. Cancel calls onCancel and uploads nothing. A file that cannot be decoded calls onError('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 value if it is exactly one of NUMBER_FORMATS (ch / us / de); otherwise Swiss ch. Case-sensitive; 'CH' and 'de-CH' are invalid and fall back to the default.
  • Inputs: Raw cookie or option value string, or undefined when absent.
  • Returns / side effects: A supported NumberFormatStyle. Missing or unknown values become DEFAULT_NUMBER_FORMAT (ch). Never writes a cookie.
  • Used by: getRequestNumberFormat (server cookie) and any caller that must coerce a raw numberFormat string.

Function: separatorsFor

  • Purpose: Returns the grouping and decimal characters for one NumberFormatStyle without Intl.NumberFormat. Swiss uses ' + ., US uses , + ., German uses . + ,.
  • Inputs: style (ch / us / de).
  • Returns / side effects: { grouping, decimal } for that style. Exhaustive switch over NumberFormatStyle.
  • Used by: formatGroupedNumber and formatUsdTick (under-10 values swap the decimal separator).

Function: formatGroupedNumber

  • Purpose: Groups the integer part of value in threes from the right and emits fractionDigits decimal digits using separatorsFor. Non-finite values are treated as 0. Rounding uses Math.round at fractionDigits.
  • Inputs: value number, style NumberFormatStyle, fractionDigits (0 omits the decimal part).
  • Returns / side effects: Grouped numeric string without a currency or ₿ prefix (for example 1'500 or 10'000.23). Negative values keep a leading minus.
  • Used by: formatBitcoin, formatUsdDisplay, formatUsdTick, NumberFormatSwitcher sample labels, DayLoader, GiftDayTable, and StatsDashboard.

Function: formatBitcoin

  • Purpose: Formats a whole-sat amount as BIP-177 ₿-only display (leading ₿, grouping from style, no fraction, no “sats” unit).
  • Inputs: sats non-negative number (API sats / totalSats; chart mid-ticks may be fractional and are rounded); optional style NumberFormatStyle (default ch). No locale argument.
  • Returns / side effects: Display string such as ₿1'500 or ₿0.
  • Used by: ForumBoard, AccountActivityChart, StatsDashboard, GiftDayTable, DayLoader, WalletBalance, WalletPay, WalletSend, LoansCard, LoanRepayScreen, MenuAccountHeader.

Function: isLocalSunday

  • Purpose: True when nowMs falls on Sunday in an IANA zone, or in the runtime zone when timeZone is omitted. An invalid zone returns false. Does not use one fixed zone for every visitor.
  • Inputs: nowMs epoch milliseconds and optional timeZone.
  • 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 renders meta[name=e2e-now], and only then does the script honour that meta or a sessionStorage e2e-now pin.

Function: useLocalSunday

  • Purpose: Reads documentElement.dataset.localSunday after 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, and PlacePinChip.

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 /view it 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 sends authorCanReceive: false, canReceive: false, lightningAddress: null (member card), or lightningAddressVerified: 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), MemberProfileScreen and ViewProfileScreen (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.css hide the field before paint once data-local-sunday="1" is set. Weekday wrappers use display: contents.
  • Inputs: children, and optional notice (write or zap).
  • 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-Zone header for the runtime IANA zone so the API can apply the same Sunday rule. Empty in Node (no window), when the zone is blank, or when Intl throws.
  • 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: iso string, locale BCP 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), or String(ms) when the instant is invalid.
  • Inputs: ms epoch milliseconds, locale BCP 47 tag.
  • Returns / side effects: Display string. Delegates to formatForumTime after toISOString.
  • 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 keeps origin plus the long path (/messages/<id> or /members/<id>).
  • Inputs: origin without a trailing slash, resource id, and longPath used when id is not a UUID.
  • Returns / side effects: Absolute URL string. No I/O.
  • Used by: copyMessageLink in ForumBoard, the member profile copy control, and publicMessageOgMetadata.

Function: shortLinkPath

  • Purpose: Map a GET /links/:code JSON body to the long app path. kind: "message" becomes /messages/<uuid> and kind: "member" becomes /members/<uuid>, with the id lowercased. Anything else, including a non-UUID id, is null.
  • Inputs: Parsed JSON body (unknown).
  • Returns / side effects: Path string or null. No I/O.
  • Used by: fetchShortLink and the GET /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: text string, optional resolvedIds ReadonlySet<string>.
  • Returns / side effects: { displayText, ids }. No I/O.
  • Used by: ForumQuotedBody.
  • Purpose: Parse HTTP(S) /l/<8 hex> URLs from a forum body using the same host and punctuation rules as splitForumMessageQuotes. Codes are lowercased, unique, and first-seen. When resolvedCodes is 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: text string, optional resolvedCodes ReadonlySet<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 for http(s)://<host>/l/<8 hex> codes that fetchShortLink resolves 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, which LinkedText then autolinks as an internal /messages/<uuid> path. Nested card is an outer frame with one empty stretched permalink (absolute inset-0, aria-label forum.quotedNote, or forum.quotedNoteExternal when the quoted note has via === '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 is pointer-events-none with [&_*]: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 has via === 'nostr', the name is a link to /messages/<id>/author, not a dialog. [&_[role=dialog]]:pointer-events-auto and [&_[role=dialog]_*]:pointer-events-auto keep the external-link confirm dialog and everything inside it clickable, because that dialog is a descendant of the card and is not portaled. The photo img is draggable={false} and is not inside the permalink. Caption rendering is unchanged (TranslatableNoteBody when translate is true, plain only when via === 'nostr'; when translate is false, ForumNoteText when truncate, else LinkedText; no nested unfurl). TranslatableNoteBody on stripped display text only (a successful translation replaces that original after the same quote/short-link strip; optional formatTranslated runs after that strip). Feed remaining text and nested captions go through ForumNoteText (280-character preview, Show more only above 560, bodies autolinked) until replaced. Permalink passes truncate={false} so the original stays full (LinkedText). Callers skip this component for via === 'nostr' rows (plain text and the External badge are handled by the caller). A nested card whose quoted note has via === '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 as basis) does it show the non-interactive External span instead. A software developer shows one Software Developer pill because the api sends role: 'software_developer'. Nested nostr captions use TranslatableNoteBody plain only when translate is true (a URL in a quoted external reply is never a link). When translate is false, nested cards use ForumNoteText / LinkedText and never TranslatableNoteBody.
  • Inputs: text, knownNotes, excludeId, rateDay, fiat, optional truncate (default true), optional className (default whitespace-pre-wrap text-sm text-app-fg; text-app-btn-fg selects NoteTranslate tone="onButton" (via TranslatableNoteBody)), optional translate (default true; false renders remaining text and nested quoted cards — including via === 'nostr' — through ForumNoteText / LinkedText without TranslatableNoteBody; forwarded to nested QuotedForumNote), optional conversationId (when set, the remainder translates as that conversation message; nested cards stay forum notes), optional formatTranslated (applied only to the visible remainder translation, after the quote/short-link strip), optional controlSlotId (forwarded to TranslatableNoteBody for the footer icon row), optional onActivate.
  • Returns / side effects: React element or null when text==='' and no resolved quotes. Unknown quote ids load via fetchForumMessage when a session exists, otherwise fetchPublicMessage (catch, never throw). Optional mentions are 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. Uses useActiveSession: while a login is still opening its wallet, a missing quote loads through the public fetch.
  • Used by: ForumBoard, PublicMessageLoader, InboxScreen.
  • 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. Internal path collapses extra leading slashes so https://21.gifts//… stays a same-origin /… href, not protocol-relative.
  • Inputs: text string, optional currentOrigin (page origin; that hostname is also internal).
  • Returns / side effects: NoteLinkSegment[] covering text in 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.gifts and other subdomains are external. Userinfo does not change the hostname check.
  • Inputs: href string, optional currentOrigin.
  • 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 to pathname+search+hash (no warning). External URLs are <a href> that preventDefault on a primary click and open ExternalLinkWarning. Click and Enter/Space stopPropagation so a forum card does not toggle; Enter/Space on an external URL opens the warning. Optional suffix sits in the same <p> after the runs (Show more). Optional mentions turn a resolved @username into the member button (forum.authorProfile). A click opens /members/<accountId>. Optional plain (default false) renders text as a single span with no autolinking (no <a> / Link, no ExternalLinkWarning), used for Nostr-zapper (via: 'nostr') rows.
  • Inputs: text, className for the wrapping <p>, optional linkClassName (default underline, inherit colour), optional currentOrigin, optional suffix, optional plain (default false), optional mentions ({ username, accountId }[]).
  • Returns / side effects: Fragment: <p> plus optional overlay. Confirm on https: calls openInSystemBrowser; other http uses window.open.
  • Used by: ForumNoteText, ForumQuotedBody (when truncate is 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 by ExternalAuthorPage inside PublicMessageChrome. No profile image and no outbound link. Copy uses the clipboard, then a hidden textarea. When both postCount and replyCount are 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 centered NpubCopyButton.
  • Shop activity: The posts/reactions gate remains unchanged; the preceding absent-count rule applies to those two buttons. Independently, profile.shopCount appears after reactions only when optional shopCount > 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.creditCount appears after shops only when optional creditCount > 0, including when shopCount is 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. Empty fallbackName shows view.unnamed until 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 shows profile.activityLatest; loading uses forum.loading; failure uses forum.error and view.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. Reads params.id and searchParams.name (a string or the first array entry, trimmed; blank becomes ''). Renders ExternalAuthorProfile inside PublicMessageChrome. No OnboardingGate. The note id is not validated as a UUID.
  • Inputs: Dynamic route params (id) and optional name query (string or string[]).
  • Returns / side effects: ExternalAuthorProfile inside PublicMessageChrome (unsigned wordmark href / plus LanguageSwitcher, or signed-in ProfileChromeLeft plus SignedInChrome). No generateMetadata.
  • Used by: Route /messages/[id]/author. ForumBoard (name click). QuotedForumNote (quoted name). PublicMessageLoader (PublicThreadCard name).

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/onCancel does not open the URL. Open link calls onConfirm. Dialog click and keydown stopPropagation so 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) with Card maxWidth="xl": title Shop sticker, lead Print it for a shop window. The QR code pays {handle}., a Second language combobox, a preview <img> of buildShopStickerSvg (alt Shop sticker preview for {handle}), a neutral SegmentedControl File format PDF | PNG | JPG | SVG (PDF first), and a labeled Download.
  • Inputs: qrValue (the profile's openCryptoPayQrValue), handle (giftsLightningAddress), onClose. The text language is not a prop. shopStickerLangInitial sets the first selection from the visitor's UI language (en → English only, de → German, es → Spanish, fil → Filipino), unless the page lang query 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 shopStickerBlob runs, then saves the blob through a temporary <a download> named by shopStickerFileName and revokes the object URL a second later; a failure shows role="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 calls onClose. Escape closes the open language list first and leaves the dialog up; the next Escape calls onClose. The dialog's own keydown handles Escape from inside it, and a document listener (removed on unmount) closes only on Escape from outside the dialog, so one key press never closes twice even with the app root on document. Dialog click and keydown stopPropagation. 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) and mode (active | unpaid | all | popular).
  • Returns / side effects: A new array. all keeps input order including unpaid (sats === 0) notes. active keeps paid notes (sats > 0) and unpaid notes without an ask (goalSats undefined) whose api role is at least moderator, so an unpaid note with role: 'software_developer' counts as a software developer, newest-first. A zero-sat ask is not active. popular keeps only paid notes, ordered by sats descending, then createdAt descending, then id descending. 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. null current 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[] or null) and fetched (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 invalid seenAt is a first visit and returns 0 even when unpaid notes exist.
  • Inputs: messages (newest-first list from the api / loader merge) and seenAt (ISO last-visit stamp, or null when 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 dispatches MOVE_FUNDS_EVENT so an open signed-in screen opens it at once.
  • Inputs: source: 'receive' (the Receive view's button) or 'link' (a ?move=1 link).
  • 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 request requestMoveFunds left, or null when 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 new requestMoveFunds clears 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 IntroduceYourselfOverlay on 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 window exists, dispatches FORUM_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: true when compose focus is still pending, then clears the flag. false on a second call. ForumBoard consumes only after the new-post textarea is present; a composerHidden board does not clear the flag.
  • Used by: ForumBoard.

Function: consumeSkipIntroduceOverlay

  • Purpose: One-shot read of the skip-introduce-once flag from requestForumCompose: the next SignedInChrome mount after Write an introduction starts with the overlay dismissed. That mount uses up the flag, so a later visit to /welcome asks again while the member still has not posted.
  • Inputs: none.
  • Returns / side effects: true when 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, and formatDefinedGoalAmount.

Function: formatFiatDisplay

  • Purpose: Formats an API fiat amount string for stats display using the visitor grouping style. null becomes — (U+2014). USD uses $ and PHP uses ₱; CHF and EUR prefix the code (CHF 1'425.00).
  • Inputs: amount (string | null), code (FiatCode), and optional style NumberFormatStyle (default ch).
  • Returns / side effects: Display string such as $1'425.00 / CHF 1'425.00. No Intl.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 as formatUsdTick) and PHP uses ₱; CHF and EUR keep the code (CHF 0 / CHF 1.43 / CHF 1'425).
  • Inputs: amount number (layout scale only), code (FiatCode), and optional style NumberFormatStyle (default ch).
  • 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 — — StatsDashboard does that when every selected cumulative is null. AccountActivityChart maps all-null CHF/EUR/PHP to — itself.
  • Used by: StatsDashboard over-time fiat scale, AccountActivityChart (profile fiat scale).

Function: defaultFiatForLocale

  • Purpose: Picks the locale default for preferred fiat when the fiat cookie 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 around formatFiatDisplay(..., 'USD', style)).
  • Inputs: usd string from GET /gifts/stats; optional style NumberFormatStyle (default ch).
  • Returns / side effects: Dollar string such as $1'425.00.
  • Used by: StatsDashboard KPI when USD is selected.

Function: formatUsdTick

  • Purpose: Formats a parsed USD chart-axis value as a grouped dollar label.
  • Inputs: usd number (layout scale only); optional style NumberFormatStyle (default ch).
  • Returns / side effects: Label such as $1'425. Values under 10 keep trimmed decimals and use the style decimal separator (. for ch/us, , for de).
  • Used by: AccountActivityChart when USD is selected. Stats over-time uses formatFiatTick.

Function: spotRateDay

  • Purpose: Turns the GET /fx/spot prices 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>> from fetchFxSpot.
  • Returns / side effects: FiatRateDay with sats: 100000000 and usd / chf / eur / php set to that price or null, or null when 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. useSpotRate returns its rateDay. A shop or till charge is not priced from this hook: WalletPaymentDetails and WalletHistory call useShopChargeFigure and do not call useSpotRateState. Fetches GET /fx/spot via fetchFxSpot on 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 (default true); while false nothing is fetched, rateDay is null, and loading is true.
  • Returns / side effects: { rateDay, loading }: rateDay is spotRateDay of the latest usable answer (or null), and loading turns false once the first read settles, whatever its result. Calls fetchFxSpot on 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. Fetches GET /fx/spot via fetchFxSpot on mount and again every five minutes (SPOT_REFRESH_MS) while mounted, and resolves spotRateDay of 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 from GET /gifts/stats, and nothing else uses it.
  • Inputs: Optional enabled (default true). When false, the fetch is skipped and the hook returns null, also after a rate was loaded.
  • Returns / side effects: FiatRateDay | null. Calls fetchFxSpot on 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 use committedFiatFigure, not this rate), PosAmount, MenuAccountHeader, WalletBalance, WalletSend, ExternalAuthorProfile, MemberProfileScreen, PublicMessageLoader, PublicMessageThread, StatsDashboard (only while wallet stats are present), LoansCard, LoanRepayScreen, and RemainingBalanceScreen (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 optional typed ({ code, amount } or null). Omitted or null stores only the spot.
  • Returns / side effects: { amountUsd, amountChf, amountEur, amountPhp }, each a two-decimal string or null. 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.round on cents): the spot rate from useSpotRate, or one gift day's totals on the statistics pages.
  • Inputs: sats, day (FiatRateDay | null), code (FiatCode).
  • Returns / side effects: "0.02"-style string, or null when 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 FiatRateDay or null, visitor FiatCode, 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 theme cookie and OS prefers-color-scheme, exposes preference / resolved theme, and keeps html.dark in 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. Writing light/dark sets the cookie (Path=/, Max-Age=31536000, SameSite=Lax, Secure on https); system deletes it. Listens to matchMedia while preference is system.
  • Used by: RootLayout (wraps the app), ThemeSwitcher, useTheme.

Function: ThemeSwitcher

  • Purpose: Settings Display row: uppercase theme.label kicker and SegmentedControl tone="neutral" for System / Light / Dark, then the muted line Saved on this device (settings.deviceOnly). Always visible on the signed-in /settings page. Not page chrome, not a Menu disclosure.
  • Inputs: None. Reads preference / setPreference from useTheme. Catalog keys theme.label, theme.system, theme.light, theme.dark, aria.theme.
  • Returns / side effects: Settings row matching PushToggle chrome. Pressing an option calls setPreference (cookie write via ThemeProvider); 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 outside ThemeProvider.
  • Used by: ThemeSwitcher and any client chrome that needs the resolved theme.

Function: parseThemePreference

  • Purpose: Parses a cookie / stored theme preference.
  • Inputs: Raw cookie value, or undefined when 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), prefersDark boolean.
  • 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)'), toggles html.dark, and has no dependencies.
  • Inputs: None (constant string).
  • Returns / side effects: Non-empty IIFE source mentioning theme= and classList.
  • Used by: RootLayout <head> script.
  • 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_URL via 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 for GET /shops/:npub and for the shop photo URLs), loadPublicMessageForOg (api base for GET /messages/:id), and the GET /l/[code] route handler (api base for GET /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 through entrypoint.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 null when unset or empty. Does not throw and does not invent a time. The head script then uses the device clock.
  • Used by: RootLayout for the e2e-now meta tag; useWallet, useWalletPay, and useWalletSend, 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_KEY access.
  • Returns / side effects: The key string, or null when 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 optional entrypoint.sh placeholder: 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_USERNAME access (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 null when 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 optional entrypoint.sh placeholder like NEXT_PUBLIC_PLATFORM_USERNAME. Unset, empty, or blank turns error reporting off.
  • Inputs: None. Literal process.env.NEXT_PUBLIC_SENTRY_DSN access; regular-expression blank check, as in getPlatformUsername.
  • Returns / side effects: The trimmed DSN, or null when unset or blank. Never throws.
  • Used by: sentryOptions, forwardSentryEnvelope.

Function: getSentryEnvironment

  • Purpose: Reads the optional error-reporting environment name NEXT_PUBLIC_SENTRY_ENVIRONMENT (for example staging), set per deployment. An optional entrypoint.sh placeholder.
  • Inputs: None. Literal process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENT access; regular-expression blank check.
  • Returns / side effects: The trimmed name, or null when 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 as 0.25, set per deployment. An optional entrypoint.sh placeholder, 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_RATE access. The value is read with a regular expression (0, 1, 0.25, .5, 1.0, surrounding blanks allowed) instead of Number, so the minifier cannot fold it against the placeholder.
  • Returns / side effects: The rate, or null when unset, empty, blank, or anything else (1.5, -1, 1e-2, 10%, text). sentryOptions then 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 null when NEXT_PUBLIC_SENTRY_DSN is unset, empty, or not a DSN (then nothing starts and nothing is sent).
  • Inputs: 'browser' or 'server'. Reads getSentryDsn, getSentryEnvironment, getSentryTracesSampleRate, and getAppVersion (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 is null; the server samples none (tracesSampleRate: 0). traceLifecycle: 'static' sends each trace as one transaction, so beforeSendTransaction sees every span. tracePropagationTargets: []: no request carries sentry-trace or baggage headers. 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 keeps BrowserTracing (page loads, navigations, fetch spans). Browser options post to the same-origin tunnel /monitoring. beforeSend, beforeSendTransaction, and beforeBreadcrumb remove 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/lnurl strings and BOLT12 lno1/lni1 strings, spark1/sparkrt1/sp1/sprt1/spt1 addresses, Bitcoin base-chain addresses (bech32 bc1/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 as Uint8Array), bearer tokens, the stored session token, URL queries and fragments, and every value under keys such as mnemonic, phrase, words, seed, share, slip39, token, secret, prf, invoice, pr, query, or fragment. 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 under event_id, trace_id, span_id, and parent_span_id are left as they are, because a random id can start with bc1. beforeSendTransaction first 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, and Content-Length header 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) and src/instrumentation-client.ts, which first removes the server's sentry-trace and baggage meta 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 Request whose 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 a transaction.
  • 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 length that 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=…, with sentry_release and, when set, sentry_environment), so policy gaps show up before the policy is enforced.
  • Inputs: Incoming Request with the legacy report-uri body { "csp-report": {…} } or a Reporting API (report-to) array; only csp-violation entries 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 of src/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 as inline, eval, wasm-eval, data, blob, wss; anything else is empty), disposition, source-file (origin only), and whole non-negative line-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 (by Content-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: enforce only when CSP_MODE is exactly enforce; report-only when unset, empty, or anything else.
  • Used by: middleware.

Function: cspHeaderName

  • Purpose: Response header name for a Content-Security-Policy mode.
  • Inputs: report-only or enforce.
  • Returns / side effects: Content-Security-Policy-Report-Only or Content-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_SOURCES in order, the nonce on script-src, then report-uri /monitoring/csp and report-to csp. The img-src directive contains only the OpenCryptoPay origin selected for the hostname. docs/csp.md lists every source and why it is needed.
  • Inputs: The nonce of this response and the request hostname; 21.gifts and www.21.gifts select 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: buildCsp and the homepage popup photo filter.

Function: placesOrigin

  • Purpose: Select the OpenCryptoPay origin for the page hostname.
  • Inputs: A hostname; 21.gifts and www.21.gifts select 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 optionally route (spark, lightning, or onchain) or prompt (login, unlock, or recovery for the passkey a social recovery creates and signs in with), and on the login prompt held (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, from capturePageLoad: load (navigate, reload, back_forward, prerender, or unknown) and load_trigger (app for App Router's fallback to a full page load, otherwise other), and how the app is displayed: display (standalone or browser, from isStandaloneDisplay), 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 (createNewPasskey and its sign-in, wallet.passkey with prompt: recovery; the address claim, wallet.address.transfer; the balance send, wallet.send with route: spark), and transferRemainingBalance (wallet.send).

Function: register

  • Purpose: Next.js server start hook (src/instrumentation.ts) for the Node.js and edge runtimes. Starts error reporting with sentryOptions('server').
  • Inputs: None.
  • Returns / side effects: Calls the SDK init when 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.ts for errors thrown while rendering a page or handling a route on the server. It is the SDK's captureRequestError.
  • 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 sentryOptions scrubber 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: load is the browser's PerformanceNavigationTiming.type (navigate, reload, back_forward, prerender, or unknown without an entry), and load_trigger is app when a navigate load found the marker a client-side navigation leaves while it runs (App Router fell back to a full page load), otherwise other. A reload or a history step that finds the marker was the member's.
  • Inputs: None. Reads the navigation entry and the 21gifts.load key of sessionStorage (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.ts and traceWallet.

Function: markAppNavigation

  • Purpose: Leave the one word app under 21gifts.load in sessionStorage while 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 app marker 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.load from sessionStorage; 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.ts called when an App Router navigation starts. It leaves the app marker (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's captureRouterTransitionStart, so each client-side navigation gets its own navigation transaction named after its route.
  • Inputs: The target href and the navigation type (push, replace, or traverse), from Next.js.
  • Returns / side effects: Writes the one word app to sessionStorage (21gifts.load), also while error reporting is off. Starts the navigation transaction while tracing is on; the transaction then passes the sentryOptions scrubber. Adds no headers to the navigation's requests. The browser start-up in the same file first calls capturePageLoad, 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 Messages object for that locale. Exhaustive switch over Locale.
  • Used by: RootLayout, Home, /login, NotFound, MarketingFooter, HandbookPage, RulesPage, RulesSetupPage, and the renderWithLocale test 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 cookie locale, then Accept-Language.
  • Inputs: Reads x-21gifts-public-locale, the locale cookie, and the Accept-Language header via next/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; otherwise parseAcceptLanguage; unmatched → en.
  • Used by: RootLayout, MarketingLayout, Home, AboutPage, DonatePage, NotFound, MarketingFooter, HandbookPage, HandbookScreensPage, HandbookFunctionsPage, HandbookEndpointsPage, RulesPage, and RulesSetupPage. Lives in src/lib/request-locale.ts so client components can import locale constants without next/headers.

Function: getRequestNumberFormat

  • Purpose: Resolve the visitor number-format style for the current request without writing cookies. Cookie numberFormat wins when it is ch/us/de; otherwise Swiss ch.
  • Inputs: Reads the numberFormat cookie via next/headers (async in Next 15).
  • Returns / side effects: A NumberFormatStyle. Invalid or missing cookie → ch. Lives in src/lib/request-number-format.ts so client components can import NUMBER_FORMATS from @/lib/number-format without pulling next/headers into the browser bundle.
  • Used by: RootLayout (passes initial into NumberFormatProvider).

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 with Mobile; false for iPad, Android tablet (no Mobile), and desktop. Viewport width is irrelevant.
  • Inputs: userAgent string (navigator.userAgent).
  • Returns / side effects: true iff the UA is a smartphone. No side effects.
  • Used by: PayLinkScreen only, 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 a name@domain address, as issued.
  • Returns / side effects: lightning: plus the trimmed request, e.g. lightning:lnbc21n1… or lightning:alice@21.gifts. Pure; no casing change, no I/O.
  • Used by: PayLinkScreen (Pay on an issued invoice) and the landing Home page (the project donate address link).

Function: isInAppBrowser

  • Purpose: Detects Telegram and other in-app WebViews where a WebAuthn passkey ceremony cannot complete, so /login and /view/[viewKey] can show an escape card instead of starting WebAuthn.
  • Inputs: Optional InAppBrowserHost (win); defaults to globalThis.window when present. Missing window (SSR) is treated as not in-app.
  • Returns / side effects: true when a Telegram JS bridge is present (TelegramWebviewProxy, TelegramWebview, or Telegram.WebApp) or the UA matches a known in-app token list; otherwise false. No network and no DOM writes.
  • Used by: LoginCard and ViewProfileClaim (choose the in-app escape card after mount), usePasskeyLogin (safety net: NotAllowedError during 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: useHydrateSession on mount, useUnreadCount, refreshUnreadAppBadge, NotificationsLoader, MenuAccountHeader.

Function: loadUnpaidSeenAt

  • Purpose: Reads the persisted No gifts yet last-visit timestamp from localStorage key 21gifts.forum-unpaid-seen.
  • Inputs: None.
  • Returns / side effects: The stored ISO string, or null when none is stored, the value is empty/whitespace/Date.parse is not finite, storage access throws, or when running on the server (no window). SSR-safe.
  • Used by: ForumLoader on mount.

Function: parseAcceptLanguage

  • Purpose: Negotiate a supported UI locale from an RFC 7231 Accept-Language header.
  • Inputs: Raw header string (may be empty). Splits on commas. A missing q defaults to 1. A bare q, empty/invalid qvalue, or duplicate q discards that language-range. Maps primary subtags (en/de/es/fil, and tl→fil).
  • Returns / side effects: Among valid mapped ranges with q > 0, highest q, then earlier header position, then LOCALES order. No positive assignment → en. Pure function — no I/O.
  • Used by: getRequestLocale when no valid locale cookie is present.

Function: parseHandbookMarkdown

  • Purpose: Parse handbook markdown into headings, paragraphs, and lists with inline code, strong, links, and images.
  • Inputs: markdown string and idPrefix for 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: token string.
  • 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: iso ISO timestamp to store (new Date().toISOString()).
  • Returns / side effects: void. SSR no-op. A throwing storage write is also a no-op.
  • Used by: ForumLoader when entering unpaid and while unpaid as the list refreshes.

Function: setName

  • Purpose: POST /me/name.
  • Inputs: sessionToken, name, and optional sundayWrite (enforce default, or setup to omit Time-Zone during onboarding).
  • Returns / side effects: Updated Account.
  • Used by: NameForm.

Function: setLocation

  • Purpose: POST /me/location with 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/about with bearer + { text, photo? } and return the updated account. photo omitted keeps a stored image; null clears it; { contentType, data } replaces it (same JPEG payload as a forum post).
  • Inputs: sessionToken, text, optional photo ({ contentType, data } | null).
  • Returns / side effects: Updated Account including aboutMe and aboutMeHasPhoto. Throws MissingRequirementsError on 409 missing_requirements. A 400 body with an error string is thrown after toUserFacingError (the About me length sentence passes through). A 400 without an error string, a 409 that is not missing_requirements, or any other non-2xx throws 'Could not save. Please try again.'. A 2xx body that fails accountSchema throws the schema error.
  • Used by: ProfileScreen.

Function: fetchAboutMePhoto

  • Purpose: GET /me/about/photo with the bearer session and return the raw image bytes as a Blob for URL.createObjectURL rendering.
  • 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: ProfileScreen via AboutMeSection loadPhoto.

Function: fetchViewAboutMePhoto

  • Purpose: GET /view-key/:viewKey/about/photo without Authorization and return the raw image bytes as a Blob.
  • 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: ViewProfileLoader when the share link has an About me photo and no profile-note id, and ViewProfileScreen via AboutMeSection loadPhoto.

Function: dismissForumLaws

  • Purpose: POST /me/forum-laws-dismissed to permanently dismiss the welcome-forum living-room laws hint.
  • Inputs: sessionToken.
  • Returns / side effects: Updated Account with forumLawsDismissed: true. No request body.
  • Used by: ForumLoader.

Function: markWalletIntroSeen

  • Purpose: POST /me/wallet-intro-seen to 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 Account with walletIntroSeen: true. No request body. Throws 'Could not save the wallet tour' on a non-ok response; a 2xx body that fails accountSchema throws the schema error.
  • Used by: WalletTour.

Function: postNotificationLevel

  • Purpose: POST /me/notification-level with 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 fails accountSchema throws the schema error.
  • Used by: PushToggle.

Function: postHeartNotifications

  • Purpose: POST /me/heart-notifications with 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 fails accountSchema throws the schema error. notifyHearts is 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: hearts from GET /messages/:id/replies; each row has accountId, name, optional username, optional role, exact sats, createdAt, and the frozen fiat strings amountUsd, amountChf, amountEur, and amountPhp (each a two-decimal string or null). 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 shows formatBitcoin(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 is null or missing does preferredFiatSuffix use the current spot. No I/O.
  • Used by: ForumBoard and PublicMessageLoader.

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 MemberIdentityPills and ForumBoard.
  • Inputs: role (Role), expanded (whether this pill's sentence is open), and onToggle.
  • Returns / side effects: The pill for the given role, or nothing only for basis (the one role without a tag). It is a button with aria-expanded. The shown role is that Role through forumTaggedRole. Pressing it calls onToggle; the caller owns which row is open. No network.
  • Used by: MemberIdentityPills, ForumBoard, and ReplyHeartSenders.

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, and ReplyHeartSenders.

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, or founder; null for basis and unknown roles. No network.
  • Used by: ForumRoleTag, ForumRoleHint, MemberIdentityPills, and ForumBoard for 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-agreement with Bearer and no JSON body.
  • Inputs: sessionToken.
  • Returns / side effects: Updated Account with rulesAgreedAt set. Throws 'Could not save your agreement' on a non-ok response.
  • Used by: RulesSetup.

Function: setUsername

  • Purpose: POST /me/username with the unique LUD-16 local-part.
  • Inputs: sessionToken, username, and optional sundayWrite (enforce default, or setup to omit Time-Zone during onboarding).
  • Returns / side effects: Updated Account. Throws Username is already in use when 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.gifts address 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 to 21.gifts.
  • Inputs: username (nullable), optional hostname.
  • Returns / side effects: local@domain or null. No I/O.
  • Used by: MemberProfileScreen, ViewProfileScreen, openCryptoPayQrValue, projectDonateAddress, WalletOwnAddress, ShopScreen, PosTill and PosAmount (via usePosTillState), 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 with giftsLightningAddress from getPlatformUsername.
  • Inputs: hostname — the host the page was requested on (21.gifts, dev.21.gifts, localhost); loopback hosts fall back to 21.gifts as in giftsLightningAddress.
  • Returns / side effects: The address, or null when the build sets no platform username. No I/O.
  • Used by: The landing Home page, which shows the #project donate section only when this is not null.

Function: encodeLnurl

  • Purpose: BIP-173 bech32-encode a cleartext URL with HRP lnurl and return it uppercase, for an Open CryptoPay lightning query parameter.
  • Inputs: url string.
  • 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 giftsLightningAddress is null.
  • Inputs: username (nullable), optional hostname.
  • Returns / side effects: https://<domain>/pl/?lightning=<LNURL> or null. 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, PosTill and PosAmount (via usePosTillState), 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, which scripts/build-shop-sticker-artwork.mjs generates with every glyph converted to an outline. Only three colours: orange #F99602, black, white.
  • Inputs: qrValue — the member's openCryptoPayQrValue. Optional lang — default Filipino (English + Filipino artwork). spanish, german, french, and kikamba replace artwork indices 6–12. english replaces 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's openCryptoPayQrValue. Optional lang — same languages as buildShopStickerSvg (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 (format pdf).

Function: shopStickerBlob

  • Purpose: The shop-sticker file in the format the visitor picked.
  • Inputs: qrValue, format — one of SHOP_STICKER_FORMATS (pdf, png, jpg, svg). Optional lang — same languages as buildShopStickerSvg (default Filipino).
  • Returns / side effects: Promise<Blob>: application/pdf from buildShopStickerPdf; image/svg+xml from buildShopStickerSvg; 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@domain or a bare username), format. Optional lang — default Filipino, which keeps the historical unsuffixed name. english, spanish, german, french, and kikamba insert -english, -spanish, -german, -french, or -kikamba before the extension.
  • Returns / side effects: 21gifts-shop-sticker-<username>[-language].<format>. The username is lowercased and reduced to a-z 0-9 . _ - (member when nothing is left). No I/O.
  • Used by: ShopStickerOverlay.

Function: shopStickerLangFromQuery

  • Purpose: Selects the printable shop-sticker text language from a lang query value.
  • Inputs: value — raw lang query value, or null when the parameter is absent.
  • Returns / side effects: Trimmed, case-insensitive. kikamba/kam; filipino/fil; Spanish spanish/spanisch/es/espanol/español; German german/deutsch/de; French french/fr/francais/français/französisch/franzosisch; English-only english/en/none/keine. Null, blank, and unknown stay filipino. 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 lang query via shopStickerLangFromQuery.
  • Returns / side effects: The language from that query (english, spanish, german, french, filipino, or kikamba), or filipino when the query is missing, unknown, or window is missing. No I/O. A missing query returning filipino does 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 lang query 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 of en, de, es, fil. When window exists, also reads the current lang query.
  • Returns / side effects: A known alias (kikamba/kam, fil/filipino, Spanish, German, French, or English-only en/none/keine) wins over the UI language. A missing, blank, or unknown query, and a missing window, 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 lnurl string back to its cleartext URL. Not bech32m.
  • Inputs: value string, either uniform case.
  • Returns / side effects: The URL, or null when 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 lightning query when it points at this site's /.well-known/lnurlp/ path.
  • Inputs: lightning LNURL string, pageHost (port and a leading www. are ignored; loopback and raw IPs expect 21.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: text as pasted or scanned: a bech32 LNURL (an optional lightning: prefix is removed, surrounding space is trimmed) or an https /pl/ link that carries one in its lightning query, 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 gives null.
  • Returns / side effects: <name>@<host> with the name as it stands in the URL, or null for 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 the send-confirm-fixed pin).

Function: PayLinkScreen

  • Purpose: Public payment card: the person's name, an exact satoshi amount, and one BOLT11 invoice.
  • Inputs: lightning query string.
  • Returns / side effects: PageChrome with ProfileChromeLeft (wordmark HomeWordmark) and a light language switcher. The arrow returns to the previous in-app view, or /welcome when 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. After GET /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 only formatBitcoin. 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 by formatDefinedGoalAmount (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 shows ChargeFiat: the stored figure, or the current spot when none was stored. One useSpotRate call, made once the pay profile is loaded, feeds the amount field while the payer is still typing, the minted view's ChargeFiat line, 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 sets window.location.href to the generic lightning: link from lightningHref, 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. A failed start shows no Pay: the amount form stays, and Continue calls openShopPayment again with the amount in the field. The page keeps the ambiguousAtMs that openShopPayment returns 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 an opened start clears it, and switching to another lightning value and back keeps it. Each Continue has its own AbortController, 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); an aborted start shows nothing, but its ambiguousAtMs is 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 new lightning value 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 from fetchShopInvoice and never mints; a pay request whose amountSats differs from the charge's amountSats (the till replaced its charge between GET /pay/:username and 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's expiresAt from GET /pay/:username, because no answer the page reads carries the payment's own window end (quote.expiration is the quote's end, which is the window end only for a Lightning-only quote, and GET /lnurlp/wait/:payment names only the BOLT11's invoiceExpiresAt), 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 with openShopPayment: charge loads the page again, invoice mints with POST /pay/:username/invoice, failed shows This payment could not be started. Try again. without minting, aborted is dropped, and opened reads the pay link: only a pay request whose quote.payment is another payment, or whose amountSats differs 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 longer open; 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 follows waitShopPayment (first without since, then with since set to the last paymentStatus; after a valid answer that is not final it asks again at once, because the api holds a read with since while the status is unchanged, and it pauses 2 s only after a read that failed or could not be read, a missing answer whose pay-link read failed, or a missing answer 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 is open. When status is not Pending the page stops the status reads and the quote refetch and keeps Paid ✓ on screen; a final ended payment (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 follows waitShopPayment from the start (without since); 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 next missing reads 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 is open. No forum and no auth gate.
  • Used by: PayLinkPage.

Function: PayLinkPage

  • Purpose: /pl server page. Reads the lightning query and renders PayLinkScreen.
  • Inputs: searchParams promise with an optional lightning string or array.
  • Returns / side effects: The payment screen. Does not 404 when the query is missing.
  • Used by: The App Router at /pl.
  • Purpose: Read the shop's pay link (GET /.well-known/lnurlp/:username on this site, without timeout, cache: 'no-store') and tell whether it carries a shop payment.
  • Inputs: username of the shop.
  • Returns / side effects: { kind: 'payment', request } for an OpenCryptoPay pay request (standard is OpenCryptoPay, or possibleStandards contains it) with callback, quote.id, quote.expiration, and quote.payment; request.amountSats is the payment's whole sats, read from the pay request itself: the BTC amount of the Lightning entry of transferAmounts, or requestedAmount (asset BTC) when that entry has no readable one, read as text with jsonAmountText and converted exactly with scaleDecimalTo8 (no float; a JSON number such as 2.1e-7 counts as 0.00000021, while a string in exponent form, a number with more than 8 decimals, zero, or more than a safe integer is unreadable); request.lines holds one entry per method and asset of transferAmounts, except the Lightning entry and an entry with available false, with its amount from jsonAmountText (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): tag payRequest, a string callback, safe-integer minSendable and maxSendable with 0 < minSendable ≤ maxSendable, and a string metadata. { 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 after openShopPayment, the refetch when a quote runs out, and the one restart after the wait route's missing) and openShopPayment (the read after a refusal in the ambiguous state).

Function: jsonAmountText

  • Purpose: Turn an amount of a pay link's JSON into text without the exponent form that JSON.parse and String give small numbers (0.00000021 is parsed as 2.1e-7), so 1–99 sats written as a JSON number stay readable.
  • Inputs: value, the amount field 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. null for 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: request from fetchShopPayLink; the call is <callback>?quote=<quote id>&method=Lightning&asset=BTC with cache: 'no-store'.
  • Returns / side effects: The pr string, or null for an error status (for example an expired quote), a missing or empty pr, 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/payment with { amountSats }), and keep the page's ambiguous state of the contract's "Payment page" section.
  • Inputs: username of the shop, the whole amountSats, and options: ambiguousAtMs (the value the previous call for this pay link returned, or null) and the page's abort signal.
  • Returns / side effects: { start, ambiguousAtMs }. A request that takes longer than SHOP_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 as null, a string, or an array; it may be a till's payment_open), and any 5xx other than 503 stablecoin_unavailable are unknown, because a payment may have been opened. Fresh (ambiguousAtMs null): a 200 with a non-empty payment id is { kind: 'opened', payment, expiresAt } (expiresAt is null when the answer has no readable window end); 409 payment_open is { kind: 'charge' }; 503 stablecoin_unavailable or any other 4xx (a 409 only with a readable body of another code) is { kind: 'invoice' } (mint with POST /pay/:username/invoice); an unknown outcome sets ambiguousAtMs to 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): opened clears ambiguousAtMs; charge keeps it; another unknown outcome is { kind: 'failed' } and moves ambiguousAtMs to its end; a 503 stablecoin_unavailable or another 4xx waits until ambiguousAtMs plus SHOP_PAYMENT_RECHECK_DELAY_MS (20 s; no wait when that has passed), then reads the pay link with fetchShopPayLink: plain (no open amount) is invoice, a pay request or error is failed. When signal aborts, 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, so ambiguousAtMs becomes 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: payment id, since (the last paymentStatus seen, or null for the first read, which answers at once), and an optional abort signal.
  • Returns / side effects: { status, paymentStatus }, where status is the DFX status (Pending until the payment is paid or closed) and paymentStatus is open, accepted, paid, or ended; 'missing' for a 404 with the api's error body (status ERROR, reason Not found: the api does not know the payment); null for any other 404 (for example a page that did not reach the api) or error status (for example 429), an unknown paymentStatus, an unreadable body, or a failed or aborted request. With since, 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 when count is 1, otherwise other; # in the chosen branch becomes that count), then replace {name} placeholders from vars.
  • Inputs: catalog (Messages), key (MessageKey), optional vars map of string/number values. A plural header needs a finite count.
  • 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 the t helper from LocaleProvider / useTranslations.

Function: useAuthStore

  • Purpose: Zustand auth store for active session + account, a valid but held-back lockedSession, and wrongAccount. Hydration is explicit (no module-init storage read).
  • Inputs: Hook. Methods setAuth, setAccount, setLockedSession, lockSession, noteLockedPasskeyMissed, dismissLockedPasskeyNotice, clearAuth, setWrongAccount, and clearWrongAccount.
  • Returns / side effects: Auth state object. setAuth persists the token, activates the account, clears lockedSession, and resets wrongAccount. setLockedSession keeps the token in storage but makes active session and account null, and keeps the account's name, else its username, as lockedName and its wallet passkey id as lockedCredentialId. lockSession moves the current token to lockedSession (and its account's display name to lockedName, its wallet passkey id to lockedCredentialId) without removing it from storage. noteLockedPasskeyMissed keeps the held-back token as lockedPasskeyMissed, so that session's next Log in offers every passkey, also after the card mounts again, and sets lockedPasskeyNotice, which dismissLockedPasskeyNotice clears when the next login run starts. setAuth and clearAuth reset lockedName, lockedCredentialId, lockedPasskeyMissed, and lockedPasskeyNotice. clearAuth clears the tab phrase and persisted token, bumps and clears the unread app badge, and drops active and held-back auth; it does not reset wrongAccount. setLockedSession and lockSession also 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), and payFromWallet's send (the session of a wallet send).

Function: useTranslations

  • Purpose: Client hook returning { locale, t } from the nearest LocaleProvider.
  • Inputs: None (React context).
  • Returns / side effects: Active locale and a t(key, vars?) bound to that catalog. Throws if used outside LocaleProvider.
  • 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 nearest NumberFormatProvider. Call sites that format counts or money take this hook's style, not UI locale.
  • Inputs: None (React context).
  • Returns / side effects: Active NumberFormatStyle and a setter that writes the numberFormat cookie. Throws useNumberFormat must be used within NumberFormatProvider when 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-subscriptions re-exports proxyMePushSubscriptionsDelete; /forum/messages/[id] re-exports proxyMessagesDelete; /pos/charge re-exports proxyPosDelete; /me/previous-wallets/[sparkPubkey] calls proxyMePreviousWalletDelete with the async sparkPubkey; /me/held-shares/[id] calls proxyMeHeldShareDelete with the async id.
  • Inputs: Incoming Request. For /forum/messages/[id], also async route params with 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]/place re-exports proxyMessagesPlacePatch. /forum/messages/[id]/shop-account re-exports proxyMessagesShopAccountPatch. /forum/messages/[id]/text re-exports proxyMessagesTextPatch. /forum/messages/[id]/photos re-exports proxyMessagesPhotosPatch.
  • Inputs: Incoming Request. For /forum/messages/[id]/place, /forum/messages/[id]/shop-account, /forum/messages/[id]/text, and /forum/messages/[id]/photos, also async route params with 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 via translate.
  • 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 in localStorage, 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 via translate (terms.title, terms.lastUpdated, terms.heading, terms.clause1Title…terms.clause5Title, terms.clause1…terms.clause5), so the page renders in German, English, Spanish, or Filipino. English title/description metadata is the documented exception.
  • Returns / side effects: The terms screen: an h1, the date line, an h2, and an ordered list of the five clauses. No links, no state.
  • Used by: Route /terms; linked from LegalPage, MarketingFooter, and RulesSetup (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 getRequestLocale and reads copy from the catalog via translate.
  • Returns / side effects: Footer element.
  • Used by: MarketingLayout, NotFound.

Function: MarketingHeader

  • Purpose: Sticky marketing header with one top-left arrow (ProfileChromeLeft tone="dark") beside HomeWordmark (tone="dark"). The wordmark publicHref is / 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 /welcome when this tab has none. The wordmark is not that control. On / and on the language home the header passes hideHistoryArrow and hideOverride, 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, PwaInstall tone="dark" placement="header", an always-visible LanguageSwitcher (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 useTranslations and the path via usePathname.
  • Returns / side effects: Header element; toggles nav on small screens. LanguageSwitcher stays visible when the hamburger is closed. Install control stays null until 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. Awaits MarketingFooter() (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; awaits MarketingFooter().
  • 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/name re-exports proxyMeNamePost; /me/location re-exports proxyMeLocationPost; /me/forum-laws-dismissed re-exports proxyMeForumLawsDismissedPost; /me/wallet-intro-seen re-exports proxyMeWalletIntroSeenPost; /me/notification-level re-exports proxyMeNotificationLevelPost; /me/heart-notifications re-exports proxyMeHeartNotificationsPost; /me/rules-agreement re-exports proxyMeRulesAgreementPost; /me/push-subscriptions re-exports proxyMePushSubscriptionsPost; /me/wallet-backup-seen re-exports proxyMeWalletBackupSeenPost; /me/wallet/report re-exports proxyMeWalletReportPost; /me/wallet/hearts re-exports proxyMeWalletHeartsPost; /me/events re-exports proxyMeEventsPost; /lnurlpay/[pubkey] calls proxyLnurlpayRegisterPost and /lnurlpay/[pubkey]/recover calls proxyLnurlpayRecoverPost with the async pubkey; /me/passkey-renew/report re-exports proxyMePasskeyRenewReportPost; /me/passkey-renew/ack re-exports proxyMePasskeyRenewAckPost; /auth/passkey/{register,authenticate,replace,seed,recovery}/{begin,finish} re-export the ten passkey proxy POSTs; /lnurlpay/[pubkey]/transfer calls proxyLnurlpayTransferPost with the async pubkey; /forum/messages re-exports proxyMessagesPost; /messages/[id]/invoice re-exports proxyMessagesInvoicePost; /messages/[id]/repayment re-exports proxyMessagesRepaymentPost for both no-body and { amount } requests; /messages/[id]/repayment/due and /close re-export their matching repayment proxy helpers; /conversations re-exports proxyConversationsPost; /conversations/[id] re-exports proxyConversationPost; /conversations/[id]/invoice re-exports proxyConversationInvoicePost; /conversations/[id]/read re-exports proxyConversationReadPost; /forum/notifications/read-all re-exports proxyNotificationsReadAllPost; /forum/notifications/read-by-message re-exports proxyNotificationsReadByMessagePost; /forum/notifications/read-visible re-exports proxyNotificationsReadVisiblePost; /forum/notifications/[id]/read re-exports proxyNotificationReadPost; /contact/submit re-exports proxyContactPost; /lnurl/pay-request re-exports proxyLnurlPayRequestPost; /lnurl/invoice re-exports proxyLnurlInvoicePost; /translate re-exports proxyTranslateNotePost with JSON { messageId, target }; /conversations/[id]/messages/[messageId]/translate re-exports proxyTranslateConversationMessagePost with JSON { target }; /trust/verify re-exports proxyTrustVerifyPost; /trust/propose-moderator re-exports proxyTrustProposeModeratorPost; /trust/confirm-moderator re-exports proxyTrustConfirmModeratorPost; /trust/reject-moderator re-exports proxyTrustRejectModeratorPost; /trust/appoint-moderator re-exports proxyTrustAppointModeratorPost; /funding/apply re-exports proxyFundingApplyPost; /funding/withdraw re-exports proxyFundingWithdrawPost; /funding/trial re-exports proxyFundingTrialPost; /funding/admit re-exports proxyFundingAdmitPost; /funding/reject re-exports proxyFundingRejectPost; /funding/daily-roster/comment re-exports proxyFundingDailyRosterCommentPost; /funding/daily-roster/payments re-exports proxyFundingDailyRosterPaymentsPost; /funding/daily-roster/recipients re-exports proxyFundingDailyRosterRecipientsPost; /funding/daily-roster/recipients/update re-exports proxyFundingDailyRosterRecipientsUpdatePost; /funding/daily-roster/recipients/delete re-exports proxyFundingDailyRosterRecipientsDeletePost. /pos/charge re-exports proxyPosPost. HTML /pos is the till page, not a POST proxy. HTML /messages is the inbox page, not a POST proxy.
  • Inputs: Incoming Request.
  • Returns / side effects: Upstream api Response on api proxies; /translate returns { 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), translateNote via POST /translate, translateConversationMessage via POST /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], async pubkey, 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/about re-exports proxyMeAboutPut; /me/wallet re-exports proxyMeWalletPut; /me/recovery-share re-exports proxyMeRecoverySharePut; /me/held-shares/[id] calls proxyMeHeldSharePut with the async id; /fond/deposit-address re-exports proxyFondDepositAddressPut.
  • Inputs: Incoming Request with Bearer session and JSON { text } (/me/about), { sparkPubkey } (/me/wallet), { sparkPubkey, share } (/me/recovery-share), { ciphertext } with the async box id (/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 / putFondDepositAddress through FondDepositSync).

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's x-breez-signature / x-breez-timestamp. Multipart POST/PUT/PATCH/DELETE bodies stream with duplex: 'half' when request.body is non-null and Content-Length is not 0; 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's x-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, apiPath beginning with /, and optional options.forwardAbort: when true, the upstream fetch gets request.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]/payment passes forwardAbort.

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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • Used by: Route POST /funding/apply.

Function: proxyFundingWithdrawPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/withdraw, the same proxy as proxyFundingApplyPost.
  • Inputs: Incoming Request (Bearer session, no body).
  • Returns / side effects: Upstream Response via proxyApiRequest, 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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • Used by: Route GET /funding/daily-roster.

Function: proxyFundingDailyRosterCommentPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/comment with JSON { comment }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/comment.

Function: proxyFundingDailyRosterPaymentsPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/payments with JSON { enabled }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/payments.

Function: proxyFundingDailyRosterRecipientsPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/recipients with JSON { accountId, amountUsd }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/recipients.

Function: proxyFundingDailyRosterRecipientsUpdatePost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/recipients/update with JSON { address, amountUsd }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/recipients/update.

Function: proxyFundingDailyRosterRecipientsDeletePost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/recipients/delete with JSON { address }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/recipients/delete.

Function: proxyFundingDailyRosterModeratorsPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/moderators with JSON { accountId, amountUsd }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/moderators.

Function: proxyFundingDailyRosterModeratorsUpdatePost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/moderators/update with JSON { address, amountUsd }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/moderators/update.

Function: proxyFundingDailyRosterModeratorsDeletePost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/moderators/delete with JSON { address }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /funding/daily-roster/moderators/delete.

Function: proxyFundingDailyRosterModeratorsPaymentsPost

  • Purpose: Same-origin Bearer proxy helper for api POST /funding/daily-roster/moderators/payments with JSON { enabled }.
  • Inputs: Incoming Request (Bearer session and JSON body).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • 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) and accountId.
  • Returns / side effects: Upstream Response via proxyApiRequest (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 Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • Used by: Route GET /wallets/stats; fetchWalletStats reads that route on /stats and /stats/wallet.

Function: proxyWalletUsageGet

  • Purpose: Same-origin proxy helper for api GET /wallets/usage.
  • Inputs: Incoming Request (no bearer).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /wallets/usage; fetchWalletUsage reads that route on /stats/wallet.

Function: proxyGiftsStatsGet

  • Purpose: Same-origin proxy helper for api GET /gifts/stats (forwards recipient query).
  • Inputs: Incoming Request (optional recipient search param).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • 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 Response via proxyApiRequest.
  • Used by: Route GET /me/activity.

Function: proxyMembersActivityGet

  • Purpose: Same-origin proxy helper for api GET /members/:accountId/activity.
  • Inputs: Incoming Request (Bearer) and accountId.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /forum/members/[accountId]/activity.

Function: proxyViewActivityGet

  • Purpose: Same-origin proxy helper for api GET /view/:viewKey/activity (public).
  • Inputs: Incoming Request and viewKey.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • 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, and kind (posts, shops, credits, or replies).
  • Returns / side effects: Upstream Response via proxyApiRequest. 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/:kind with no auth and parse one public profile list.
  • Inputs: viewKey (64 hex) and kind (posts, replies, shops, or credits).
  • Returns / side effects: ForumMessage[]. Throws visitor copy Could not load messages. Please try again. on a non-2xx status, a network failure, or an invalid envelope.
  • Used by: ViewProfileLoader when 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, and imageEpoch. 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. imageEpoch reloads the stored pictures without remounting the header.
  • Used by: MemberProfileScreen when the signed-in account id matches the profile.

Function: proxyMeNamePost

  • Purpose: Proxies POST /me/name.
  • Inputs: Request with JSON body.
  • Returns / side effects: Upstream Response.
  • Used by: Route POST /me/name.

Function: proxyMeUsernamePost

  • Purpose: Proxies POST /me/username.
  • Inputs: Request with JSON body.
  • Returns / side effects: Upstream Response.
  • Used by: Route POST /me/username.

Function: proxyMeLocationPost

  • Purpose: Proxies POST /me/location.
  • Inputs: Request with 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 Request with Bearer session and JSON { text, photo? }.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: App Router PUT on /me/about.

Function: putProfilePhoto

  • Purpose: PUT /pictures/me with { photo } for the signed-in account. null clears 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 (ProfileImages and the owner About me editor).

Function: fetchProfilePhoto

  • Purpose: GET /pictures/me bytes 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 header ProfileImages and AboutMeSection loadPicture), 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 GET on /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 PUT on /pictures/me.

Function: putWideBanner

  • Purpose: PUT /banners/me with { photo } for the signed-in account. null clears 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: ProfileScreen via AboutMeSection onSaveBanner.

Function: fetchWideBanner

  • Purpose: GET /banners/me bytes 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 header ProfileImages and AboutMeSection loadBanner).

Function: proxyWideBannerGet

  • Purpose: Same-origin Bearer proxy of api GET /banners/me.
  • Inputs: Incoming Request.
  • Returns / side effects: Upstream Response.
  • Used by: App Router GET on /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 PUT on /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 first image/* 200. No bearer. Not the About me note photo.
  • Inputs: Incoming Request, slot pictures or banners, and accountId. 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 GET on /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 (MemberProfile or null) and children(marks, hints).
  • Returns / side effects: Whatever children returns. No network. The pill is exactly the api role, so a software developer shows one Software Developer pill because the api sends role: '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 Request with Bearer session.
  • Returns / side effects: Upstream Response via proxyApiRequest to /me/about/photo.
  • Used by: App Router GET on /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, plus viewKey from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: App Router GET on /view-key/[viewKey]/about/photo.

Function: proxyMeForumLawsDismissedPost

  • Purpose: Proxies POST /me/forum-laws-dismissed.
  • Inputs: Request with 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: Request with 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-level with JSON { level }.
  • Inputs: Incoming Request with Bearer session and JSON { level }.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/notification-level.

Function: proxyMeHeartNotificationsPost

  • Purpose: Same-origin Bearer proxy of api POST /me/heart-notifications with JSON { enabled }.
  • Inputs: Incoming Request with Bearer session and JSON { enabled }.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/heart-notifications.

Function: proxyMeRulesAgreementPost

  • Purpose: Proxies POST /me/rules-agreement.
  • Inputs: Incoming Request with Bearer session (no JSON body required by the client).
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/rules-agreement.

Function: proxyMeGet

  • Purpose: Proxies GET /me.
  • Inputs: Request with Bearer token.
  • Returns / side effects: Upstream Response.
  • Used by: Route GET /me.

Function: proxyMessagesGet

  • Purpose: Bearer proxy GET /messages to the 21.gifts api (public forum list). App route is GET /forum/messages.
  • Inputs: Incoming Request with Bearer session.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • 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 Request with Bearer session.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: src/app/forum/messages/hidden/route.ts.

Function: proxyMessagesPost

  • Purpose: Bearer proxy POST /messages to the 21.gifts api (create a public forum message or reply). App route is POST /forum/messages.
  • Inputs: Incoming Request with Bearer session and JSON body.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /forum/messages.

Function: proxyMessagesRepliesGet

  • Purpose: Bearer proxy GET /messages/:id/replies to the 21.gifts api (oldest-first replies). App route is GET /forum/messages/[id]/replies.
  • Inputs: Incoming Request with Bearer session, plus parent message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /forum/messages/[id]/replies.

Function: proxyExternalAuthorProfileGet

  • Purpose: Public proxy GET /messages/:id/external-profile to the 21.gifts api (no auth). App path is /public-messages/[id]/external-profile.
  • Inputs: Incoming Request, plus message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest. Does not add a Bearer header.
  • Used by: Route GET /public-messages/[id]/external-profile.

Function: proxyExternalAuthorPostsGet

  • Purpose: Public proxy GET /messages/:id/external-posts to the 21.gifts api (no auth). App path is /public-messages/[id]/external-posts. Returns the upstream response via proxyApiRequest. Does not add a Bearer header.
  • Inputs: Incoming Request, plus message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest. Does not add a Bearer header.
  • Used by: Route GET /public-messages/[id]/external-posts.

Function: proxyExternalAuthorShopsGet

  • Purpose: Public proxy GET /messages/:id/external-shops to the 21.gifts api (no auth). App path is /public-messages/[id]/external-shops. Returns the upstream response via proxyApiRequest. Does not add a Bearer header.
  • Inputs: Incoming Request, plus message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest. Does not add a Bearer header.
  • Used by: Route GET /public-messages/[id]/external-shops.

Function: proxyExternalAuthorCreditsGet

  • Purpose: Public proxy GET /messages/:id/external-credits to the 21.gifts api (no auth). App path is /public-messages/[id]/external-credits. Returns the upstream response via proxyApiRequest. Does not add a Bearer header.
  • Inputs: Incoming Request, plus message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest. Does not add a Bearer header.
  • Used by: Route GET /public-messages/[id]/external-credits.

Function: proxyExternalAuthorRepliesGet

  • Purpose: Public proxy GET /messages/:id/external-replies to the 21.gifts api (no auth). App path is /public-messages/[id]/external-replies. Returns the upstream response via proxyApiRequest. Does not add a Bearer header.
  • Inputs: Incoming Request, plus message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest. Does not add a Bearer header.
  • Used by: Route GET /public-messages/[id]/external-replies.

Function: proxyPublicMessageGet

  • Purpose: Public proxy GET /messages/:id to 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 message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /public-messages/[id].

Function: proxyShortLinkGet

  • Purpose: Public proxy GET /links/:code to the 21.gifts api (JSON { kind, id }, no auth). App path is /links/[code]. Forwards the code with encodeURIComponent. The visitor-facing redirect is /l/[code], not this JSON route.
  • Inputs: Incoming Request, plus short-link code from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest (status and JSON body, or 502 when the api is unreachable).
  • Used by: Route GET /links/[code], which fetchShortLink calls.

Function: proxyPublicMessageRepliesGet

  • Purpose: Public proxy GET /messages/:id/replies to the 21.gifts api (oldest-first live replies, no auth). App path is /public-messages/[id]/replies so /messages/[id] can serve HTML.
  • Inputs: Incoming Request, plus parent message id from the App Router segment.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /public-messages/[id]/replies.

Function: proxyLnurlPayRequestPost

  • Purpose: Bearer proxy POST /lnurl/pay-request to the 21.gifts api (pay request of a Lightning address or LNURL on another host).
  • Inputs: Incoming Request with Bearer session and { target } JSON.
  • Returns / side effects: Upstream Response via proxyApiRequest (502 JSON when the api is unreachable).
  • Used by: Route POST /lnurl/pay-request.

Function: proxyLnurlInvoicePost

  • Purpose: Bearer proxy POST /lnurl/invoice to the 21.gifts api (invoice from a Lightning address or LNURL on another host).
  • Inputs: Incoming Request with Bearer session and { target, amountMsat, comment? } JSON.
  • Returns / side effects: Upstream Response via proxyApiRequest (502 JSON when the api is unreachable).
  • Used by: Route POST /lnurl/invoice.

Function: proxyContactPost

  • Purpose: Bearer proxy POST /contact to the 21.gifts api (create an in-app contact message). Same-origin path is /contact/submit so it does not collide with the /contact page.
  • Inputs: Incoming Request with Bearer session and JSON body.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /contact/submit.

Function: proxyMessagesPhotoGet

  • Purpose: Same-origin proxy GET /messages/:id/photo or /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). Runtime getApiUrl() via proxyApiRequest (not next.config rewrites).
  • Inputs: Incoming Request, message id from the App Router segment, and optional indexed file such as 1.jpg.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /messages/[id]/photo and GET /messages/[id]/photo/[file].

Function: proxyMessagesPhotoExtGet

  • Purpose: Same-origin proxy GET /messages/:id/photo.jpg to the 21.gifts api. Deletes authorization on the incoming request so the edge can cache the public still for a day.
  • Inputs: Incoming Request, message id from the App Router segment, and ext 'jpg'.
  • Returns / side effects: Upstream Response via proxyApiRequest. Query string is copied. No extra Cache-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. Runtime getApiUrl() via proxyApiRequest (not next.config rewrites).
  • Inputs: Incoming Request, message id from the route, and ext 'mp4' | 'webm' | 'mov'.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route GET /messages/[id]/[file] when file is video.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.create input, including excludeCredentials when present and client extensions (PRF eval.first as base64url) via applyClientExtensions.
  • Inputs: Record from POST /auth/passkey/register/begin or POST /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 valid public-key entries (invalid type or id is skipped; all skipped → TypeError), including before native parse.
  • Used by: usePasskeyLogin.register, renewPasskey, and createNewPasskey (the new passkey of a social recovery).

Function: credentialToJSON

  • Purpose: Serialise a PublicKeyCredential for the api finish body. Drops clientExtensionResults.prf so PRF bytes never leave the tab.
  • Inputs: Browser credential from create/get.
  • Returns / side effects: JSON record without prf results. Uses native toJSON when present, then strips prf.
  • Used by: usePasskeyLogin, renewPasskey, and the recovery flow (createNewPasskey, transfer).

Function: finishPasskeyAuthentication

  • Purpose: POST /auth/passkey/authenticate/finish and parse the session.
  • Inputs: challengeId and credential JSON.
  • Returns / side effects: { token, account }. A 409 with code recovery_pending throws RecoveryPendingError before any other check. Throws WrongAccountError on 403 with the duplicate-account api string. A 400 body exactly Unknown credential throws UnknownCredentialError. Other non-2xx stay status fallbacks. Sends X-App-Build (getBuildId). 503 code logins_closed throws LoginsClosedError; 403 code app_outdated throws AppOutdatedError (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/finish and parse the session.
  • Inputs: challengeId and credential JSON.
  • Returns / side effects: { token, account } with linkingKey null. Throws WrongAccountError on 403 with the duplicate-account api string. A 409 whose error is exactly Username is already in use throws Error with that string. Other non-2xx stay status fallbacks. Sends X-App-Build (getBuildId). 503 code logins_closed throws LoginsClosedError; 403 code app_outdated throws AppOutdatedError (checked before the wrong-account 403).
  • Used by: usePasskeyLogin.submitName for a new account, and usePasskeyLogin.register only 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 Request with JSON body.
  • Returns / side effects: Upstream Response.
  • Used by: Route POST /auth/passkey/authenticate/finish.

Function: DiagnosticsListener

  • Purpose: Subscribe to window error and unhandledrejection and forward the error name and message to the diagnostic log.
  • Inputs: None. Reads window.location.pathname when the event fires, plus the event's error or reason.
  • Returns / side effects: Renders null. Posts client.unhandled through reportDiagnostic. Removes both listeners on unmount.
  • Used by: Root layout, mounted once for every page.

Function: proxyDiagnosticsPost

  • Purpose: Proxies POST /diagnostics so the browser can store an allowlisted client event.
  • Inputs: Incoming Request with 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 fetch with keepalive. Never throws. Never sends PRF bytes, the recovery phrase, or a session token.
  • Used by: DiagnosticsListener, usePasskeyLogin, renewPasskey, and useWalletPhrase.

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 Request with 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.get input. Empty allowCredentials is omitted (discoverable credentials). When discoverable, sets hints: ['client-device']. Copies client extensions (PRF eval.first as base64url) via applyClientExtensions.
  • 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 valid public-key entries (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/begin and parse options.
  • Inputs: None.
  • Returns / side effects: { challengeId, options }. Throws on non-2xx. Sends X-App-Build (getBuildId). 403 code app_outdated throws AppOutdatedError; 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/begin to start the social recovery of the account the old wallet belongs to, and parse the answer with recoveryBeginSchema.
  • 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 }. Sends X-App-Build (getBuildId). 503 code logins_closed throws LoginsClosedError; 403 code app_outdated throws AppOutdatedError; 403 with the duplicate-account api string throws WrongAccountError. Then RecoveryError: not_found on 404, done or operator on 409 with code recovery_done or recovery_operator, unavailable on 5xx or 429, invalid on 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/finish to 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 in startPasskeyRecovery. Then RecoveryError: challenge on 400 Unknown or expired challenge, Challenge expired, or Challenge already used (the account did not move); pending on 409 A recovery is already pending; key_in_use on 409 Wallet key is already in use; unavailable on 5xx or 429; invalid on any other non-2xx, including a known text with another status.
  • Used by: transfer on /recover, as the first part of the move (the account).

Function: startPasskeyReplace

  • Purpose: POST /auth/passkey/replace/begin with 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/finish with 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 Account from { account }. Throws on non-2xx.
  • Used by: None. The client helper is removed.

Function: startPasskeySeed

  • Purpose: POST /auth/passkey/seed/begin with 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/finish with Bearer and { challengeId, credential }.
  • Inputs: Session token, challenge id, credential JSON.
  • Returns / side effects: The owner account (accountSchema), including passkeyCredentialId. A 200 body is that account, or the same account under one account key when the body has no top-level id. account only 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-seen with Bearer.
  • Inputs: Session token.
  • Returns / side effects: Owner Account. Throws on non-2xx.
  • Used by: The helper remains. useWalletPhrase does not call it.

Function: postWalletReport

  • Purpose: POST /me/wallet/report with bearer + { balanceSats, syncedAt, payments }.
  • Inputs: sessionToken and a WalletReportBody (balance in whole sats, ISO 8601 read time, at most WALLET_REPORT_PAGE_SIZE payments).
  • Returns / side effects: The acknowledgedIds of the response. Sends only those three fields, whatever else the body object holds. Throws Could not report wallet data: <status> on a non-2xx status, and throws when the response has no acknowledgedIds list.
  • 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 prfPresent boolean 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: renewPasskey before 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: renewPasskey when it builds the renew report.

Function: passkeyRenewClientCapabilities

  • Purpose: Read browser capability names that are strictly true, such as prf and hybridTransport. This describes the browser, not the passkey.
  • Inputs: None. Calls PublicKeyCredential.getClientCapabilities when 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: renewPasskey on every stored failure or cancel, including when create itself threw.

Function: postPasskeyRenewReport

  • Purpose: POST /me/passkey-renew/report with 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, and clientCapabilities.
  • Returns / side effects: Owner Account. Throws Could not report passkey renew on non-2xx. Never sends a phrase, PRF bytes, credential, challenge, or token in the body.
  • Used by: renewPasskey for browser-only ceremony failures and cancels.

Function: postPasskeyRenewAck

  • Purpose: POST /me/passkey-renew/ack with Bearer.
  • Inputs: Session token.
  • Returns / side effects: Owner Account. Throws Could not acknowledge passkey renew on non-2xx.
  • Used by: PasskeyRenewNotice OK button.

Function: renewPasskey

  • Purpose: Runs the seed-passkey ceremony for a member who has no seed yet.
  • Inputs: Session token.
  • Returns / side effects: ok with the account and in-memory PRF bytes, cancelled, stored when reload already shows a seed, or failed with a wallet error kind. failed includes 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 from obtainPrfFirst under the seed options' rp.id; null is wallet.prfUnsupported before 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 starts rememberPhraseFromPrf and does not wait for it. Does not persist the phrase (tab memory only).
  • Used by: useWalletPhrase.activate and PasskeyRenewNotice.

Function: mergePrfExtension

  • Purpose: Adds the PRF request to passkey creation options: prf.eval.first is the PRF salt (prfEvalFirstSalt), so the new passkey yields the bytes behind a recovery phrase.
  • Inputs: PublicKeyCredentialCreationOptions as 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 walletRequired is false: explain, confirm, device passkey prompt, then a success or failure confirmation.
  • Inputs: None. Reads the auth store and translations. ?visual=renew-passkey and ?visual=renew-ok force 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 shows wallet.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, or passkeyRenewClosed is true.
  • Used by: AppShell when walletRequired === false and passkeyRenewClosed is 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, then funding.stoppedDaily.body and 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, or null when 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 Request with 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 Request with 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 Request with 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 Request with 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 Request with 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 Request with 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 Request with JSON { sparkPubkey, lookup }; no session. X-App-Build is 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 Request with JSON { challengeId, credential, newSparkPubkey, signature }; no session. X-App-Build and Origin are 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 Request with Bearer.
  • Returns / side effects: Upstream Response.
  • Used by: Route POST /me/wallet-backup-seen.

Function: proxyMeWalletReportPost

  • Purpose: Proxies POST /me/wallet/report to the api with proxyApiRequest (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/hearts to the api with proxyApiRequest (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/events to the api with proxyApiRequest (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.ts pins 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.first from 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, info mnemonic-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.ts pins them with a known-answer vector (PRF bytes 00 01 … 1f give access 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, and createNewPasskey (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 with rememberCeremonyRpId), or null.
  • Returns / side effects: Bytes, or null when the id is null (no prompt), the get() gives no PRF output, or create() gave PRF output that differs from the get() output. Callers treat null as 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, and createNewPasskey (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 runs startPasskeyAuthentication only to read its rpId and keeps it; that begin is never finished and no assertion is forwarded. null without 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: rpId of assertion options, else rp.id of creation options.
  • Returns / side effects: The id, or null when it is missing or empty. That null is stored too and counts as no ceremony in this tab, so a later obtainPrfFirstFromGet asks 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, and obtainPrfFirstFromGet.

Function: classifyWebAuthnError

  • Purpose: Map WebAuthn failures to timeout / cancel / generic.
  • Inputs: Unknown rejection.
  • Returns / side effects: Discriminant string.
  • Used by: useWalletPhrase, renewPasskey, unlockWalletPhrase, and createNewPasskey.

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 from useWalletPhrase. Implemented in tab-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 from useWalletPhrase. Implemented in tab-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 in tab-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 in tab-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), or passphrase (not printable ASCII).
  • Returns / side effects: Error named Slip39Error with a readonly code and the message slip39_<code>. Neither ever holds a share word or a byte.
  • Used by: parseShare, splitRecoverySecret, combineShares, phraseFromShareCodes, and OldWordsInput (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 a Map, so constructor is 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 the value bytes. Throws Slip39Error word, length, checksum, params, or padding. 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 Slip39Share from parseShare.
  • Returns / side effects: true for 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.getRandomValues by 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 always academic; word 4 is acid, agency, or always. The shares are standard SLIP-39, so any SLIP-39 tool combines two of them to the same 16 bytes. Throws Slip39Error length for 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 Slip39Error empty, passphrase, any code of parseShare, set for shares of different sets, length for values of different lengths, members or groups for the wrong number of shares (one share alone and the same share twice are members), or digest when the shares do not fit together. No network, no storage.
  • Used by: splitPhrase (the pair check) and phraseFromShareCodes.

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_PREFIX plus 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 code when the result would not read back with parseShareCode, 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) and keepHeldShare.

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, then isRecoveryShare).
  • Inputs: Scanned or pasted text.
  • Returns / side effects: ShareCode (ownerAccountId, ownerUsername, share, identifier, memberIndex), or null for anything else. Pure.
  • Used by: encodeShareCode, loadHeldShares, keepHeldShare, useHeldShares (the owner's username of a scanned code), and OldWordsInput (the codes scanned on /recover and /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.getRandomValues by default; tests and the Playwright screenshot fixture of useSocialRecoverySetup pass a fixed one).
  • Returns / side effects: { identifier, shares } from splitRecoverySecret. Throws the BIP-39 error of mnemonicToEntropy for words that are not a valid phrase, Slip39Error length for a phrase longer than 12 words, and Recovery split check failed when a pair does not give the bytes back. The words and bytes stay in memory.
  • Used by: useSocialRecoverySetup on /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 Slip39Error set for shares of another owner or identifier, members for the same share twice, digest when they do not fit together, and length when they do not give 16 bytes.
  • Used by: OldWordsInput (two scanned codes rebuild the old 12 words on /recover and /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, info box-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 of mnemonicToEntropy for words that are not a valid phrase, and the DOMException of crypto.subtle.importKey or deriveKey when the browser cannot import or derive the key. The words and bytes stay in memory.
  • Used by: useHeldShares (the key of the open page) and relockHeldShares.

Function: newHeldShareBoxId

  • Purpose: A new box id: 16 bytes from crypto.getRandomValues as 32 lower-case hex digits, the form PUT /me/held-shares/:id accepts. 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 data 21gifts-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 DOMException of crypto.getRandomValues or crypto.subtle.encrypt when the browser cannot make the IV or encrypt with the key. No network.
  • Used by: keepHeldShare (a new box) and relockHeldShares (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 null when 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: loadHeldShares and relockHeldShares.

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 with parseShareCode.
  • 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 of fetchHeldShareBoxes when the boxes cannot be read.
  • Used by: useHeldShares on /settings/held-shares, and keepHeldShare (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 } with invalid, own, duplicate, or save (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 with created (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 null while 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) and useRemainingBalance (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, or null when 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 signature for 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: transfer on /recover, which signs it with the old wallet's signMessage before finishPasskeyRecovery.

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 finally on activate / showPhrase.
  • Used by: useWalletPhrase tests.

Function: useWalletPhrase

  • Purpose: Add or show the recovery phrase. /wallet does not render the words. /wallet/phrase does. 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-empty passkeyCredentialId (Add recovery phrase: renewPasskey, then mnemonicFromPrfFirst on the in-memory PRF bytes, store the account, 12 words only in component state). 'reveal' when the id is set: showPhrase shows 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 runs obtainPrfFirstFromGet of 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 to rememberPhraseFromPrf, so that one prompt also opens the wallet. walletBackupSeenAt is not read. The hook itself does not call rememberSessionPhrase; activate reaches it through renewPasskey when the wallet is configured. hidePhrase hides the words and keeps the tab phrase, so the wallet stays open. No Confirm, no Continue. A passkey without PRF output sets error prfUnsupported, shown as wallet.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 words WALLET_VISUAL_FIXTURE_MNEMONIC), ?visual=error, ?visual=timeout, and ?visual=prf-unsupported pin 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 ProfileChromeLeft via AppShellTopLeft, not the page WalletChromeLeft. surface="entry" is /wallet with its home, Send, and Receive views. surface="phrase" is /wallet/phrase.
  • Inputs: account.passkeyCredentialId from useAuthStore, UseWalletPhraseResult plus optional surface (entry default, or phrase), optional wallet prop for the balance block, and optional send prop 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 from WalletBalance large in the centre (when the wallet prop is present and not disabled), then LoansCard place="wallet" and the WalletHistory payments card while the wallet is ready, followed by WalletFooterActions (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 (no passkeyCredentialId), 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 are WalletPanelView (WalletReceive, or WalletSend with the manual-entry sheet), driven by useWalletPanel, 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 being ready; when the Sent line closes (Done or Back), the view returns home. No word grid and no recovery error. On phrase, only the ceremony: Add recovery phrase, Show recovery phrase, the 12-word grid and the warning wallet.phraseWarning that 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 on entry: in the Send view it first closes the manual-entry sheet, then asks send.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 /welcome when this tab has none. On phrase it hides the words, then does the same. It does not leave the site, and it does not open /wallet as a parent. Opened as /wallet?receive=1 (Add Bitcoin in a pay sheet away from the forum home), useReceiveLink opens the Receive view once and removes receive from the address; the top-left arrow then closes Receive first.
  • Used by: WalletScreen, WalletPhraseScreen.

Function: WalletScreen

  • Purpose: Signed-in /wallet body: the balance, then LoansCard when 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 WalletScreenView with useWalletPhrase(), the wallet prop from useWallet(), and the send prop from useWalletSend(). 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 every setReady, 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, or null), retrying (true while the wallet is at error and the wallet service opens it again automatically, between and during its retries), and downloading (true while the wallet is connecting and 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, and setSetupFailedSession(session). setConnecting, setReady, and reset clear retrying; setReady, setError, and reset clear downloading.
  • Returns / side effects: Wallet state object. Resting status is disabled without a key, else locked. setSetupFailedSession records 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, and reportWallet.

Function: loadWalletSdk

  • Purpose: The only module that imports @breeztech/breez-sdk-spark: its /web entry, by dynamic import, then its init(). 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 /ssr entry 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 narrow WalletSdk (connect → getInfo, getUserSettings, updateUserSettings, addEventListener, registerAddress, listPayments, getPayment (one payment by id through the SDK's getPayment({ paymentId }), mapped with toWalletPayment; a token payment, 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; plus identityPubkey and signAddressLookup); getInfo can request a synchronized read with ensureSynced. The settings surface exposes only sparkPrivateModeEnabled and sparkMasterIdentityPublicKey; its update type can only enable private mode or set a viewer key, never disable privacy or unset the viewer. registerAddress registers only the given username (no availability check is exposed); listPayments asks for one page of Bitcoin payments newest first (assetFilter bitcoin, so token payments whose amounts are not satoshis are left out) and maps each row with toWalletPayment. parse maps the SDK's parse result to a WalletTarget: 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, marked amountFromUri so it is passed to prepare; 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 it unsupported) and comment limit, onchain for a Bitcoin mainnet address on the base chain (its address, the shortened recipient, and amountSats from a BIP21 URI that offers only that address, otherwise null; a BIP21 URI with a Lightning or Spark method uses that method instead), or unsupported (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). prepare calls prepareSendPayment({ paymentRequest: { type: 'input', input } }) (with amount when the text has none; a base-chain address always gets one) or prepareLnurlPay, reads amount and fee, refuses a prepared payment that would send a token rather than Bitcoin, and returns send, which calls sendPayment (a BOLT11 request with preferSpark: false, so the Lightning fee shown is the fee paid) or lnurlPay with that prepare response. For a base-chain address (SendPaymentMethod bitcoinAddress) it reads the feeQuote into onchain: the fee of each speed (fast, medium, slow) is userFeeSat plus l1BroadcastFeeSat, and expiresAtMs is the quote's expiresAt (epoch seconds) in ms; feeSats is the medium fee, and send(speed) calls sendPayment with { type: 'bitcoinAddress', confirmationSpeed: speed } (default medium). listReportPayments asks for the same page of Bitcoin payments (same assetFilter) and maps each row with toWalletReportPayment, for the wallet data report. For social recovery the connection also has signMessage(message) (the SDK's signMessage with compact: true: ECDSA over one SHA-256 of the text with the identity key, returned as { pubkey, signature } hex and nothing else), hasAddress() (whether getLightningAddress finds an address, which looks it up once when it was never read), authorizeAddressTransfer(transfereePubkey) (authorizeLightningAddressTransfer, signing only, wrapped as an opaque WalletAddressTransfer), claimAddressTransfer(transfer) (claimLightningAddressTransfer with that same authorization; the SDK posts /lnurlpay/<own key>/transfer to the app's host), receiveSparkAddress() (receivePayment for a Spark address), and sendToSparkAddress(address, amountSats, idempotencyKey) (prepareSendPayment with exactly that amount, refused with Not a Spark address before anything is sent unless the method is sparkAddress, then sendPayment with the idempotency key, a UUID, so a repeated send is not paid twice). For the Fond's on-chain deposits the connection also has receiveBitcoinAddress() (receivePayment with { type: 'bitcoinAddress' } and no newAddress, so the existing static deposit address), listUnclaimedDeposits() (the SDK's listUnclaimedDeposits({}) mapped to WalletDeposit rows: txid, vout, amountSats, done for a submitted or claimed instant claim or a refund, and maxClaimFeeSats for a recorded fixed ceiling), and claimDeposit({ txid, vout }, maxFeeSats) (the SDK's claimDeposit with maxFee: { type: 'fixed', amount }). identityPubkey(mnemonic) and signAddressLookup(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 key connect derives) and free it afterwards. signAddressLookup signs the UTF-8 bytes of lnurlRecoverMessage(domain, pubkey, timestampSecs) and returns { pubkey, signature } with the signature DER-encoded by derSignatureHex, the lookup the SDK itself sends on connect; the SDK's signMessage refuses that message, which is why the external signer signs it.
  • Inputs: None.
  • Returns / side effects: A WalletSdk. Uses defaultConfig('mainnet') with the api key, lnurlDomain set 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 /recover and openPreviousWallet on /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 enable sparkPrivateModeEnabled only when it is false. A later change to walletViewerPublicKey writes only the viewer key. When each run reaches the front it reads getUserSettings and the account's then-current walletViewerPublicKey, and sets sparkMasterIdentityPublicKey only 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 uses ensureSynced, so a cached balance is not shown as final and the store stays connecting until 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 is connecting with downloading set (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 the error state with Try again. A wallet that a synced refresh already showed as ready is left as it is. Store otherwise goes to ready or error. Subscribes to SDK events and refreshes on synced. 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 at WALLET_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 then online and visibilitychange start 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 stays error with retrying set, never connecting: screens that need the wallet keep the could-not-be-opened state with Try again, and a retry that succeeds makes the store ready. No retry starts while the tab is hidden or the browser is offline; the cycle then waits without a timer. visibilitychange (to visible) and online start 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, on disconnectWallet (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 and ensureWalletConnected), which supersedes a running retry through the run counter, closes its late connection, and starts over at once.
  • Inputs: Optional WalletSdkLoader (defaults to loadWalletSdk).
  • 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 reports Wallet settings not updated only 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 spans wallet.sdk.load, wallet.connect, and wallet.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 level error with the fingerprint ['wallet-open-failed', reason] and the tag wallet_open_reason, and records wallet_open_failed with reason: timeout at the 30 s deadline, error when loading the wallet code, connecting, or the first synchronized read rejected. Both also say why: stage (sdk_load when downloading or starting the wallet code failed, connect when connecting or adding the event listener failed, first_sync when the first synchronized balance read failed, or when a balance read started by a synced event failed before the wallet was ready, deadline at the 30 s deadline), errorName, errorCode, and causeKind from errorCause (all three null at the deadline, where nothing was thrown), elapsedMs since the attempt started, online (navigator.onLine), and visibility (document.visibilityState). The error report carries them as extras and as the tags wallet_open_stage, wallet_open_error, wallet_open_error_code, wallet_open_cause (none when absent), wallet_open_online, and wallet_open_visibility, beside wallet_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 reports errorName unknown). 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 SDK paymentSucceeded event whose payment (mapped by toWalletPayment; 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. Unlike onIncomingPayment, 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 every onPaymentReceived listener 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 the onPaymentReceived listeners; no network, no balance read.
  • Used by: PosTill under the ?visual=pos-received and ?visual=pos-received-unnamed pins.

Function: refreshWallet

  • Purpose: Reads getInfo (with ensureSynced when 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 sets error, after which the automatic retries of connectWallet open the wallet again. The failure of a stale read is ignored. A failure before an open of connectWallet was 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 open and wallet_open_failed) at first_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 sets error. With ignoreFailure, a failed read changes nothing and the wallet stays as it is.
  • Returns / side effects: void. Updates useWalletStore. Times the read as the wallet span wallet.balance (traceWallet).
  • Used by: The synced listener that connectWallet registers, the send that the wallet payment primitive returns, useWalletPay (synced reads every 4 s while insufficient shows), useLoanRepay (synced reads while top-up is open), and WalletSync (a synced read every five minutes while the wallet is ready).

Function: disconnectWallet

  • Purpose: Closes the connection and resets the store (locked, or disabled without a key). Runs when the tab phrase is cleared, which includes logout. Ends the automatic retries after a failed open: their timer and their online and visibilitychange listeners 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 the onPaymentReceived listeners (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: listenForWalletPhrase when 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 to loadWalletSdk).
  • 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's passkeyCredentialId, 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, settlePhraseDerivations waits for it.
  • Inputs: PhraseSource (prfFirst, credentialId, account, sessionToken).
  • Returns / side effects: true when the phrase was remembered, else false. 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), so unlockWalletPhrase answers noPrf or failed without 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 from visualPin.
  • 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: isWalletOpen and hydratesLocked.

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: account and hasPhrase.
  • Returns / side effects: Boolean; one-time wallet setup is deliberately not part of the result. No side effects.
  • Used by: useWalletOpen, and LanguageSwitcher (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-session pin 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 through peekSessionPhrase, delegates account eligibility to walletGateApplies, and reads the pin through visualPin.
  • Returns / side effects: Boolean: true when the wallet gate applies or the held-session pin is set, and the tab has no phrase. True makes hydration store the token as lockedSession instead 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, and unlockWalletPhrase.
  • 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 null while 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 useAuthStore session and account and useWalletOpen.
  • Returns / side effects: The usable session token, or null. A held-back session is already null in 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), and ForumQuotedBody / QuotedForumNote (signed-in quote fetch and the member link), and AmountEntry (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, and useActiveSession) read it to treat a session whose wallet is not open as signed out.
  • Inputs: Auth-store account plus peekSessionPhrase, subscribed through SESSION_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, and useActiveSession.

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, and useWalletPhrase.showPhrase.

Function: unlockWalletPhrase

  • Purpose: Seed-passkey fallback for opening the wallet phrase: obtainPrfFirstFromGet of the account's passkeyCredentialId, then rememberPhraseFromPrf. 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 span wallet.passkey with prompt: unlock (traceWallet); the PRF output is never part of the span.
  • Used by: finishWalletOpen only.

Function: canUnlockWallet

  • Purpose: True when the account has walletRequired === true and a non-empty passkeyCredentialId.
  • Inputs: account or null.
  • 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 /wallet balance block after the central gate has established that the wallet is open. An unconfigured wallet or account that cannot hold one is disabled; there is no rendered locked state. A store that has not connected yet is presented as connecting. An account still needing wallet verification also stays connecting while background setup runs, with downloading set while the wallet code downloads; exhausted setup reports error with setupFailed. After a failed open the status is error with retrying while the wallet service opens the wallet again in the background, and turns ready on its own. While the wallet code is still downloading the status is connecting with downloading set. retry always connects again in this page; it never reloads the page.
  • Inputs: None. Reads the auth store, useWalletStore, useWalletSetup (due, failed), and Playwright-only pins through visualPin (?visual=setup-pending shows 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-payment show ready with the fixture balance, ?visual=balance-reopening shows error with retrying and turns ready with the fixture balance after WALLET_VISUAL_REOPEN_MS, 4 s, and ?visual=balance-downloading shows connecting with downloading).
  • Returns / side effects: { status, balanceSats, retry, downloading, setupFailed, retrying }, where status excludes locked, downloading is true only at connecting while the wallet code downloads, and retrying is true only at error while a retry is on its way (never with setupFailed). retry reconnects 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. Throws wallet-verified on 409, wallet-unavailable on 404 (feature off), and wallet-request on any other failure or an invalid body.
  • Used by: runWalletSetup.

Function: proxyMeWalletPut

  • Purpose: Proxies PUT /me/wallet to the api.
  • Inputs: Incoming Request with Bearer and JSON { sparkPubkey }.
  • Returns / side effects: Upstream Response.
  • Used by: Route PUT /me/wallet.

Function: putRecoveryShare

  • Purpose: PUT /me/recovery-share with 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, with socialRecoverySetUp true. Throws RecoveryError key_in_use on 409 (the wallet is not connected or changed), unavailable on 5xx or 429, and invalid on any other non-2xx. A body that fails accountSchema throws.
  • Used by: useSocialRecoverySetup on /settings/social-recovery.

Function: proxyMeRecoverySharePut

  • Purpose: Proxies PUT /me/recovery-share to the api.
  • Inputs: Incoming Request with 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-wallets with Bearer: the wallets the account used before a social recovery.
  • Inputs: Session token.
  • Returns / side effects: PreviousWallet[] (sparkPubkey, sparkAddress, replacedAt, balanceSats), where balanceSats is the public explorer balance the api read or null when unknown; it is information only. Throws Unauthorized on 401 and Previous wallets are unavailable on any other non-2xx. A body that fails previousWalletsSchema throws.
  • Used by: usePreviousWallets (the previous wallets on /security) and useRemainingBalance (the previous wallet's page checks that its key is listed).

Function: proxyMePreviousWalletsGet

  • Purpose: Proxies GET /me/previous-wallets to the api.
  • Inputs: Incoming Request with Bearer.
  • Returns / side effects: Upstream Response.
  • Used by: Route GET /me/previous-wallets.

Function: deletePreviousWallet

  • Purpose: DELETE /me/previous-wallets/:sparkPubkey with 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 throws Could 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/:sparkPubkey to the api.
  • Inputs: Incoming Request with Bearer, path sparkPubkey (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-shares with 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). Throws Unauthorized on 401 and Held shares are unavailable on any other non-2xx. A body that fails heldShareBoxesSchema throws.
  • Used by: loadHeldShares and relockHeldShares.

Function: putHeldShareBox

  • Purpose: PUT /me/held-shares/:id with 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: created on 201 (the account had no box with this id), otherwise replaced. Any non-2xx (400 for a bad id or box, 409 Box id in use or Too many held shares, 401, 429, 5xx) throws Could not keep the share.
  • Used by: keepHeldShare and relockHeldShares.

Function: deleteHeldShareBox

  • Purpose: DELETE /me/held-shares/:id with 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) and relockHeldShares (a box a re-lock wrote again after it was deleted).

Function: proxyMeHeldSharesGet

  • Purpose: Proxies GET /me/held-shares to the api.
  • Inputs: Incoming Request with Bearer.
  • Returns / side effects: Upstream Response.
  • Used by: Route GET /me/held-shares.

Function: proxyMeHeldSharePut

  • Purpose: Proxies PUT /me/held-shares/:id to the api.
  • Inputs: Incoming Request with Bearer and JSON { ciphertext }, path id (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/:id to the api.
  • Inputs: Incoming Request with Bearer, path id (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; the X-Breez-Signature and X-Breez-Timestamp headers are forwarded), path pubkey.
  • 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), path pubkey.
  • 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), path pubkey (the new wallet key, URL-encoded upstream).
  • Returns / side effects: Upstream Response. Default proxy options, like its /lnurlpay siblings.
  • 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, path pubkey.
  • 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, path username.
  • 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, path paymentHash.
  • 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 matching pos: plus a charge id with no space (/^pos:\S+$/) sets purpose to shop and chargeId to the text after pos:, and does not put that memo back into description. A gift memo (zap: plus 64 hex digits) sets purpose to gift and is also not kept as description. 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 WalletPayment the /wallet payment list and the /wallet/payment screen read (the screen shows only part of info; the invoice's node key is kept but not shown): received or sent, whole sats and whole-sat fees (the SDK amounts are bigint), epoch ms (the SDK time is seconds), status, method (lightning, spark, deposit, withdraw; token and anything else is other), the payer's note from the received-payment metadata, and info: the Lightning or Spark invoice and its description (a Spark description comes from invoiceDetails), 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 the e tag 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: purpose is gift, 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: purpose is shop and the title is Shop payment.
  • Inputs: An SDK payment (id, paymentType, status, amount, timestamp, optional fees, method, and details).
  • 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 Payment from WALLET_PAYMENT_FIXTURES.
  • Returns / side effects: WalletPayment. Pure.
  • Used by: useWalletHistory and useWalletPayment under the ?visual=history-rows pin.

Function: toWalletReportPayment

  • Purpose: Maps one SDK payment to the payment the wallet data report sends: id, direction (in or out), status (an unknown status counts as completed), whole-sat amountSats and feeSats, timestamp (ISO 8601 from the SDK's epoch seconds), method (lightning, spark, token, onchain for the SDK's deposit and withdraw, otherwise unknown), 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, and lnurlComment (the comment sent, else the payer's note received). Blank texts are null.
  • Inputs: An SDK payment (id, paymentType, status, amount, fees, timestamp, method, optional details).
  • 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 at error between automatic retries, which that call supersedes.
  • Inputs: Optional WalletSdkLoader.
  • Returns / side effects: The identity public key. Throws wallet-connect without a key or a tab phrase, or when the connection fails.
  • Used by: runWalletSetup, receiveWalletSparkAddress, signWithWallet, and useSocialRecoverySetup (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 (the lnurlDomain of connect) 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 (receiveSparkAddress of the connection), so a balance can be sent to it.
  • Inputs: Optional WalletSdkLoader, forwarded to ensureWalletConnected.
  • Returns / side effects: The address. Opens the wallet from the tab phrase first when it is not open yet. Throws wallet-connect when the wallet cannot be opened or closed meanwhile, otherwise the SDK's error.
  • Used by: transferRemainingBalance on /settings/previous-wallets/[sparkPubkey], and dfxLoginUrl on /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 WalletSdkLoader forwarded to ensureWalletConnected.
  • Returns / side effects: The signature hex. Opens the wallet from the tab phrase when it is not open yet. Throws wallet-connect when the wallet cannot be opened or closed meanwhile, otherwise the SDK's error. The text and the signature are not logged.
  • Used by: dfxLoginUrl on /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 to receiveWalletSparkAddress and signWithWallet.
  • Returns / side effects: The absolute https://app.dfx.swiss/buy URL with session, blockchain=Spark, and asset-out=BTC. The entire sign-in, including both requests and their response bodies, is limited to DFX_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. Throws wallet-connect when the wallet cannot be opened. Throws dfx-login when that time limit is reached, when DFX answers non-2xx, returns a body that is not JSON, omits a non-empty message or accessToken, or returns an unexpected sign-in text. A failed request rejects with that fetch error. Performs GET https://api.dfx.swiss/v1/auth/signMessage?address=..., checks the returned text exactly before signing, and performs POST https://api.dfx.swiss/v1/auth with { 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-connect without a connection, otherwise the SDK's error. Times the registration as the wallet span wallet.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[]. Throws wallet-connect without 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/payment screen.
  • Inputs: id.
  • Returns / side effects: The mapped WalletPayment. Rejects with wallet-connect while 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[]. Throws wallet-connect without 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, and sparkWalletVerified is strictly false. Older api bodies without the field never qualify.
  • Inputs: Account or null.
  • Returns / side effects: Boolean type guard. Pure; it neither starts setup nor prompts.
  • Used by: runWalletSetup, listenForWalletSetup, useWalletSetup, useWallet, useWalletPay, useWalletSend, useLoanRepay, and PosTill.

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 locked when the recovery phrase is still absent from tab memory, then connects, sends PUT /me/wallet with 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 to loadWalletSdk.
  • 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 yields superseded. After the final failed try, stores that session as setupFailedSession; the phrase remains in tab memory only.
  • Used by: retryWalletSetup and listenForWalletSetup.

Function: retryWalletSetup

  • Purpose: Explicit retry after background setup exhausted its attempts.
  • Inputs: Optional WalletSdkLoader, defaulting to loadWalletSdk.
  • Returns / side effects: Clears setupFailedSession, then returns the promise from runWalletSetup; 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 to runWalletSetup.
  • Returns / side effects: Unsubscribe function. Subscribes to SESSION_PHRASE_EVENT and 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. due is needsWalletSetup of the signed-in account, or true under the ?visual=setup-pending pin (Playwright builds only). failed is true only while the account still needs setup and setupFailedSession matches 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, and visualPin.
  • Returns / side effects: { due, failed, retry }. retry calls retryWalletSetup in this page; it never reloads the page. A pinned fixture leaves retry inert.
  • Used by: WalletSetupNote, useWallet, useWalletPay, useWalletSend, useLoanRepay, WalletReceive, and PosTill.

Function: walletSetupPin

  • Purpose: Screenshot pin for the inline setup note on a money screen.
  • Inputs: Reads visualPin() and matches balance-setup-failed, wallet-pay-setup-failed, or pos-setup-failed.
  • Returns / side effects: Boolean. Because visualPin centralizes 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 with walletSetup.error (Your wallet could not be set up yet.) and a secondary Try again Button under it. Retry starts setup again in this page; it never reloads the page.
  • Used by: WalletBalance (on /wallet and /wallet/payment), WalletPay, WalletReceive, PosTill, and LoanRepayScreen.

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 }: payment is the WalletPayment or null, dismiss stops showing it early. Clears its timer and unsubscribes on unmount. Under the ?visual=wallet-received pin, honoured only in a Playwright build (visualPin), a fixed ₿500 received payment arrives on mount and is held for holdMs like 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) writes text with navigator.clipboard.writeText; each success shows copied for 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: useWalletPayment under 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: usePaymentCounterparty under 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: useWalletPayment under 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: usePaymentCounterparty under 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-member and ?visual=sent-to-member return fixtures without a request. ?visual=received-member-unknown and ?visual=sent-member-unknown return 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/hearts proxy. 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-empty messageId, an integer dayIndex of at least 0, termDays as an integer of at least 1 or null, role borrower or giver, string authorName and text (either may be empty), and a boolean deleted. A body without a repayments array (an api from before repayments) has no repayments; the hearts are read as before.
  • Inputs: A Bearer sessionToken and payment hashes (the caller sends chunks of at most 32).
  • Returns / side effects: { hearts, repayments } (HeartLookup): valid HeartPost[] and RepaymentContext[], 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 uses useActiveSession, requests sequential chunks of at most 32, exposes unresolved hashes as pending, 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-payment and ?visual=history-heart return the Sunday lunch post and an empty pending set without calling fetchHeartPosts, and ?visual=heart-payment-pending and ?visual=history-heart-pending return an empty map and a pending set containing only the visual heart hash, also without a fetch. ?visual=repayment-payment and ?visual=history-repayment return 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 leave pending once settled, are in neither map, and are not retried by a same-input re-render.
  • Used by: WalletHistory, WalletPaymentDetails.

Function: useWalletHistory

  • Purpose: The /wallet payment list: loads WALLET_HISTORY_PAGE_LIMIT (20) payments newest first once the wallet is ready, appends the next page on loadMore (skipping ids it already has), and reloads every loaded page whenever useWalletStore.syncCount changes, which happens after connect and after each SDK synced event, 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-error pins a fixture list only in a Playwright build; history-heart and history-heart-pending are the single heart fixture payment, history-repayment is the received and the sent repayment fixture (REPAYMENT_GIVER_VISUAL_PAYMENT, REPAYMENT_BORROWER_VISUAL_PAYMENT), and history-rows is WALLET_PAYMENT_FIXTURES mapped with toFixturePayment (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: pending is true until the receipt read settles, and false when the payment is not a shop charge. figure is 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 purpose is shop and whose chargeId is a string loads that receipt with fetchShopChargeReceipt. While the read is pending, figure is null and pending is true. A 404 or any other failed read (receipt null) stays figure null. A receipt then goes through committedFiatFigure with the visitor's fiat as preferred. It does not read the spot. A payment that is not a shop charge does not fetch: pending is false and figure is null.
  • Inputs: Payment method details, or null when 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 /wallet home under the balance card while the wallet is ready. Each row is a next/link to its /wallet/payment screen (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 by useHeartContext, 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 that useHeartContext names a loan repayment, for the member as giver or as borrower, shows the lucide HandCoins icon 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 through useShopChargeFigure once 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's repay: 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 reads useSpotRate for 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 /wallet home for connecting, ready, and error states. There is no locked state because the gate only reveals this screen after the wallet is open. Connecting reads wallet.downloading (Downloading wallet…) while the wallet code is still being downloaded, and wallet.connecting (Opening your wallet…) after that. It renders nothing when disabled. Requests the spot rate only in ready. 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, optional setupFailed (default false), and optional downloading (default false).
  • Returns / side effects: A region named Balance, or null when disabled. An ordinary error shows wallet.balanceError and Try again; with setupFailed it renders WalletSetupNote instead. 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 send pays it once, gives up waiting after 30 s (failed with sentLate, 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 of send, reports failed without paying. For a base-chain address the result carries onchain (fees per speed and spendableFeeSats, the balance minus the amount) and send takes the chosen speed. It never sends without a fresh quote: a speed whose fee is above spendableFeeSats is insufficient, and a quote within WALLET_QUOTE_MARGIN_MS (15 s) of its expiry is expired, both without calling the SDK.
  • Inputs: WalletPayRequest: { type: 'input', input, amountSats? } or { type: 'lnurl', request, amountSats, comment? }.
  • Returns / side effects: confirm (amountSats, feeSats, optional onchain, 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 as feeSats, or the SDK says so, without a fee), belowMinimum with minSats (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), or unlock (no connection). The synced balance read also updates useWalletStore while 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. send resolves to paid, insufficient, failed (an error or the 30 s limit), or expired (a base-chain quote that ran out, before the SDK or as its answer; nothing was sent). Never rejects. confirm also carries method (lightning, spark, onchain, lnurl, or unknown: read from the request, and onchain once the SDK quotes a base-chain fee). Times the prepare and the send as the wallet spans wallet.prepare and wallet.send, each with only its route (spark, lightning, or onchain, from the request's method: an LNURL receiver is lightning, an sp1… address is spark, anything else unknown is onchain) (traceWallet). The send's route is onchain when the prepare returned a base-chain fee quote, lightning when the request read as onchain but 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-payment turns 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 failure for reportPaymentFailure; payFromWallet reports nothing itself, because its callers may prepare again (an expired quote, a Spark invoice with a Lightning fallback, a heart after unlock). failure holds stage (prepare; confirm for a send refused before the SDK is asked; send for 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-chain onchainFees, and the SDK rejection as error. Reasons: unlock (no connection), insufficient, below_minimum, disconnected (the connection changed during prepare, the balance read, or before send), balance_read, already_sent (a second send), expired, and for an SDK rejection the shape of its message: expired, no_route, timeout (also the 30 s limit, with sentLate), network, lnurl_error, otherwise sdk_error. The message is read only to classify, never reported: the text of an Error or a thrown string; anything else, or a rejection whose message cannot be read (a throwing getter), classifies as sdk_error without converting it.
  • Interaction log: A send the SDK reports as sent is recorded as payment_sent with 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 after WALLET_SEND_TIMEOUT_MS, send answers failed with sentLate, which resolves true and records payment_sent if the SDK still reports the send, or false if it fails.
  • Used by: useWalletPay (gift pay sheets), useWalletSend (/wallet), sendHeartTip, useLoanRepay (the last through payInvoiceSparkFirst, as useWalletPay).

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 } (sparkInvoice may be null, undefined, or '' when the api issued none; pr is the Lightning payment request of the same invoice), and an optional onSparkFailure callback.
  • Returns / side effects: The WalletPayResult of the Spark prepare, or of pr. Without a Spark invoice it prepares pr at once. When the Spark prepare is failed with reason sdk_error (the wallet refuses that Spark invoice), onSparkFailure gets its failure and pr is prepared instead. Every other Spark outcome is returned as it is (confirm, insufficient, belowMinimum, unlock, and failed for expired, timeout, network, disconnected, or balance_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 }. errorName is the error's name, or its constructor's name, when it is on a fixed list: the built-in JavaScript and WebAssembly error classes (TypeError, RangeError, RuntimeError, …), DOMException and its names (QuotaExceededError, AbortError, TimeoutError, …), ChunkLoadError, and the app's own error classes; otherwise unknown, 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) reports unknown. errorCode is the error's own code when it is a whole number of up to six digits (a DOMException's, so -1, 1.5, or 1e+21 is no code) or one of a short list of known constants (network codes such as ECONNRESET and ETIMEDOUT, and the legacy DOMException names such as QUOTA_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), otherwise null. Both are lists, not shapes, so a key or a name written as a code, or other text before error:, is never sent. causeKind is the first row of CAUSE_KINDS that 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 (a RuntimeError unreachable in each browser's wording), wasm_runtime (any other RuntimeError), 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 is unknown. 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's name, message, code, and constructor are 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 only unknown. Never throws.
  • Used by: connectWallet and refreshWallet (the Wallet did not open report and the wallet_open_failed event).

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 (stage prepare | confirm | send, a short reason code, method lightning | spark | onchain | lnurl | unknown, amountSats, feeSats, optional onchainFees and error, as payFromWallet or the screen built it), the PayFlow that started it (send for the /wallet Send view, pos for a shop charge read there, gift for a gift on a note, reply, or habit comment, reaction for a paid reaction, post_fee for the posting fee, repay for a loan repayment on /loans/repay, inbox for the inbox pay sheet, heart for a heart, recovery for the balance move of a social recovery on /recover, previous_wallet for Transfer remaining balance of a previous wallet, fond_payout for the automatic Fond payout loop), and optionally the session the payment ran under and the sentLate of a timed-out send.
  • Returns / side effects: None. Records the member event payment_failed with stage, reason, method, flow, and amountSats (scalars only; dropped when session is no longer the current one). Sends captureMessage('Payment failed') at level error with the fingerprint ['payment-failed', stage, reason] (one issue per stage and reason, not one per payment), the tags pay_stage, pay_reason, pay_method, and pay_flow, and the extras amountSats, feeSats, onchainFees, errorName, and errorCode. No text of the rejection is ever reported, because SDK and api messages can carry invoices, addresses, or keys: errorName is the Error subclass 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 as LnurlRelayError; any other name is Error), or the JavaScript type of anything else (a thrown string or byte array is string or object); errorCode is the relay's reason (LnurlRelayError) or the SDK's error kind at the start of its message (Network error: … → network, letters only), otherwise null. A rejection that cannot be read (a throwing getter) keeps only its name, so reporting never throws. The event still passes the beforeSend scrubber (see sentryOptions). Member state (unlock, insufficient, below_minimum) and hearts (which keep Heart not sent) are never sent to error reporting, only recorded. A timeout with sentLate is sent to error reporting at once; payment_failed follows only when sentLate resolves false, and a send that still went out is sent once more as sent_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, otherwise sdk_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 by payFromWallet itself, 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 parse on the current connection.
  • Inputs: Text as pasted; it is trimmed.
  • Returns / side effects: target with the WalletTarget, invalid for blank or unreadable text, unreachable when text that names a receiver by name@domain or LNURL cannot be read (the receiver's server did not answer this browser; there is no relay), or unlock without 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 sparkInvoice when the api issued one, otherwise pr; a Spark invoice the wallet refuses at prepare falls back to pr (payInvoiceSparkFirst). A wallet that is unavailable or the account cannot hold reports unavailable. 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 at confirm, including for a zero fee. While setup is due it reports preparing; if setup gives up, it reports setupFailed and no payment continues by itself.
  • Inputs: sparkInvoice (string, null, or undefined), pr (fallback request for the same invoice), amountSats (the exact whole-sat amount the sheet shows), and flow (the PayFlow of the sheet). Reads the auth store, useWalletStore, and useWalletSetup.
  • Returns / side effects: { view, sent, feeSats, missingSats, pay, retry }. sent says where the last send stands: pending from Send until the wallet answers (a send the app stopped waiting for stays pending until its sentLate resolves), paid only once it went out, null before a send and after one that did not go out; a pinned paying or unconfirmed view reports paid. Views are unavailable, preparing, confirm, paying, insufficient, failed, setupFailed, or unconfirmed. 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. pay is 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 becomes unconfirmed. 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 through visualPin and leave actions inert.
  • Interaction log: A send the SDK reports as sent is recorded as gift_sent with the amount, also when the sheet closed before the send finished. A send the app stopped waiting for is recorded as gift_sent once its sentLate resolves true.
  • Failure report: Every prepare that does not reach confirm (also insufficient, 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 its sentLate) goes to reportPaymentFailure under flow, 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: the confirmLabel (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 (the PayFlow passed to useWalletPay for its failure report), optional chargeFigure (a stored { code, amount } shown as-is; null or omitted uses the current spot), optional postsOnPay (default false; Pay {amount} and post stays bitcoin only), and optional confirmLabel (a function from the amount with its fiat — a passed chargeFigure as-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 useWalletPay view in one flex w-full flex-col items-stretch gap-3 column. failed shows its alert and a full-width secondary Try again. setupFailed renders WalletSetupNote: walletSetup.error and a secondary Try again button. preparing and paying show a spinner and status; confirm shows the size="lg" button (or Pay {amount} and post when postsOnPay), with the fee row only for a fee above ₿0; insufficient shows the alert, Still missing with fiat, and Add Bitcoin; unconfirmed is neutral. Inside a PaySheet it reports through usePaySheetSent whether a payment is out (paying or unconfirmed), 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, and InboxScreen. Loan repayments use LoanRepayScreen, not this invoice slot.

Function: useWalletSend

  • Purpose: Drives the /wallet send 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 (walletWait opening, busy) and read on its own once the wallet is ready. A payment whose fee is not known yet shows the quote step (amount and recipient, no fee) and is prepared on its own once the wallet is ready, then shows confirm. While the wallet cannot be opened (useWallet error, also when the one-time setup gave up), walletWait is error and retryWallet opens the wallet again (useWallet retry) or runs the one-time setup again (useWalletSetup retry); the text and the step stay. When the account has no wallet it can use here (useWallet disabled), a step that needs the wallet ends on the input step with the unavailable alert 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, then parseWalletInput. 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, payFromWallet prepares 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 to parseWalletInput below; a balance too low for the charge shows the insufficient alert. 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> as ownShop writes it: Continue first asks fetchMemberSparkInvoice for a Spark invoice of exactly the amount entered, with the message trimmed and cut to the receiver's limit, and payFromWallet prepares 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 the insufficient alert. 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, or postLnurlInvoice then payFromWallet for 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 (failed for those two), never to an amount step. The recipient of an LNURL for /.well-known/lnurlp/<name> (bech32, lightning:, or an https /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 a bitcoin: 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 carries onchain: the fee of each speed, the largest fee the balance covers, and the chosen speed (medium, or slow when the balance does not cover medium); setSpeed chooses another covered speed and feeSats follows 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, and renewed; when the wallet can no longer send by then, that prepare waits on the quote step 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 the unreadable alert (a prepare that throws, with failed), so a pasted, typed, or scanned text never leaves the input step silent. A Lightning address or LNURL on another host (lnurlRelayTarget) skips parseWalletInput: postLnurlPayRequest gives the bounds (whole sats, at least 1) and comment length, postLnurlInvoice returns the invoice for the amount in millisats, and payFromWallet prepares that invoice; a prepared amount other than the one entered fails. Not a payable address, Address not found, and Address could not be reached return to the input with the notPayable, notFound, and relayUnreachable alerts; Amount out of range and Comment too long keep the amount step with the amount or comment alert; anything else, or no session, is failed; 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 leaves ready, the amount step stays, an idle confirm step becomes the quote step 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 the unreadable or failed alert); a send in flight is kept. When the account leaves wallet mode while a step waits, the flow ends on the input step with the unavailable alert. 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 leaves ready (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 reportPaymentFailure with 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 its sentLate, 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 stage prepare, method lnurl, as relay_not_payable, relay_not_found, relay_unreachable, relay_amount, relay_comment, or relay_failed. The flow is pos for a shop charge, including the wallet read its failed Spark attempt falls back to (one report when both fail), and send otherwise; an amount the member types after that fallback is their own payment and reports as send. 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 }; sending is true only while a confirmed payment is being sent, so busy without it on the confirm step is the renewal of an expired quote. walletWait is opening or error while a read on the input step, or the quote step, waits for the wallet, otherwise null. abandon leaves 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.step is input (with error, one of which is unavailable), amount, quote (recipient and amount, before the fee is known), confirm, or sent (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-error pins a fixture step (recipient bob@example.com, ₿2'100, fee ₿0; the request target is sp1qexample…a9f2; send-confirm-fixed is the confirm step of the point-of-sale QR of shop@21.gifts, named through lnurlPayAddress, for ₿7'000 with the Lightning fee ₿3, and send-confirm-shop the same step paid with the shop's Spark invoice, fee ₿0; send-confirm-member is the confirm step of ₿2'100 to the member alice@21.gifts without an open charge, paid with that member's Spark invoice, fee ₿0; the base-chain pins use bc1qar0srr…wf5mdq, ₿50'000, and the fees fast ₿2'840, medium ₿1'420, slow ₿710: send-amount-onchain its amount step, send-amount-onchain-min that step with the SDK minimum ₿294, send-confirm-onchain its confirm step on medium, send-confirm-onchain-fast on fast, send-confirm-onchain-slow on slow, send-confirm-onchain-low with a balance that covers at most a ₿2'000 fee, so fast is disabled, and send-confirm-onchain-renewed after an expired quote) for screenshots, only in a Playwright build; send-confirm-sending and send-confirm-onchain-sending also report a send in flight (busy and sending); send-confirm-onchain-renewing reports a quote being renewed (busy without sending); send-input-opening and send-input-wallet-error pin a read on the input step that waits for the wallet (walletWait opening or error, busy), send-confirm-opening and send-confirm-wallet-error the quote step of ₿2'100 to bob@example.com, and send-confirm-opens that quote step until WALLET_SEND_PIN_OPEN_MS (1.5 s) later, when it shows the send-confirm fixture; under send-confirm-wallet-error, retryWallet shows opening and the same fixture that long after (under send-input-wallet-error it only shows opening); actions are inert while pinned (and under any ?visual=balance-…, ?visual=history-…, or other ?visual=send-… value in a Playwright build), except that under send-input-busy and send-amount-busy Continue marks that step busy, and under an idle base-chain confirm pin setSpeed chooses 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 /wallet send flow can ask it for an open charge: a Lightning address <name>@<host> (an optional lightning: prefix is removed), or an LNURL of https://<host>/.well-known/lnurlp/<name> (bech32, lightning:, or in an https /pl/?lightning= link, read through lnurlPayAddress). The own host is the one lnurlRelayTarget uses (giftsLightningAddress of this page; case, www., and a trailing dot are ignored; a local boot counts as 21.gifts).
  • Inputs: text as pasted or scanned, hostname (window.location.hostname).
  • Returns / side effects: { name, address } with the lower-case name and <name>@<own host>, or null for 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 (username null) it uses GET /pay/charges/:id. A 404, any other non-OK response, or a body that is not a receipt is missing.
  • Inputs: chargeId (the text after pos:) and username (the local part of the paid Lightning address, or null). 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 its charge is pending (or carries no status) and has not run out, POST /pay/:username/invoice with { amountSats } of that charge, then GET /pay/:username again. Since the api also issues a Spark invoice to a member without a charge, the invoice counts only while the same charge (same id, 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 no sparkInvoice (or names another amount), or another charge is open on the second read. Never rejects. The invoice request is fetchMemberSparkInvoice without a message.
  • Used by: useWalletSend.

Function: fetchMemberSparkInvoice

  • Purpose: Spark invoice for exactly the amount a member typed in the /wallet send 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/invoice with { amountSats }, plus comment when the message is not empty.
  • Inputs: The member's username, amountSats (whole sats), and comment (already trimmed and cut to the receiver's limit, or '' for none).
  • Returns / side effects: The sparkInvoice string, or null when 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 /wallet send 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 domain giftsLightningAddress uses for this page (a local boot counts as 21.gifts); the comparison drops www. 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's parse.
  • Inputs: text as pasted (trimmed; an optional lightning: prefix is removed), hostname (window.location.hostname).
  • Returns / side effects: The address or LNURL to send as target, or null when 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-request with { target } and the Bearer session.
  • Inputs: sessionToken, target (user@domain or a bech32 LNURL).
  • Returns / side effects: { target, minSendableMsat, maxSendableMsat, commentAllowed, description, domain } (lnurlPayRequestSchema). Throws LnurlRelayError: 400 Not a payable address is notPayable, 404 Address not found is notFound, 502 Address could not be reached is unreachable; any other status or text, a network error, or a body that fails the schema is failed.
  • 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/invoice with { 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 (from postLnurlPayRequest), amountMsat, optional comment (omitted when empty).
  • Returns / side effects: { pr } (lnurlInvoiceSchema), the BOLT11 invoice the wallet pays. Throws LnurlRelayError with the reasons of postLnurlPayRequest, plus 400 Amount out of range as amount and 400 Comment too long as comment.
  • Used by: useWalletSend.

Function: LnurlRelayError

  • Purpose: Typed rejection of postLnurlPayRequest and postLnurlInvoice, so the send flow can choose its alert without reading English api text.
  • Inputs: reason: notPayable, notFound, unreachable, amount, comment, or failed.
  • Returns / side effects: Error named LnurlRelayError with a readonly reason. The api error text is matched only together with its status; an unknown pair is failed.
  • Used by: postLnurlPayRequest, postLnurlInvoice, useWalletSend.

Function: WalletSend

  • Purpose: The Send view on /wallet and 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 marked data-port-fill fills the visible page port edge to edge (absolute to the AppShell scrollport, which globals.css makes its containing block only while such a layer is in the page; bottom corners follow the frame), with QrScanner inside 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 are Button variant="overlay"; until the preview plays, when the camera is off, or when the scanner reports that the picture is not showing, they are variant="secondary" tone="dark": Paste (wallet.sendPaste, lucide ClipboardPaste) 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 small role="alert" pill over the camera for four seconds, while the camera keeps running. Enter manually (wallet.sendEnterManually, lucide Keyboard) 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 through send.setText, and once the field holds it send.submitInput runs 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 has role="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 calls send.retryWallet and keeps the text. The unavailable input alert is Your 21.gifts wallet is not available here, so this cannot be paid. (wallet.payUnavailable). The amount step uses AmountEntry; 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 the AppShellFooter a 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) in text-base semibold, 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. The quote step 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 a Loader2 and role="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), and onManualEntry (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 /wallet and over /welcome: the label Receive, the member's Open CryptoPay QR (profile.giftsQr, profileQrLogo; the profile QR, shown on every user agent), the profile.giftsHeading label, 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 (ButtonLink to /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 (useWalletSetup due), a Loader2 and role="status" Opening your wallet… (wallet.connecting) stand where the QR, address, and Copy go, and a setup that gave up (failed) shows WalletSetupNote there instead; Set an amount stays.
  • Inputs: None. Reads account from useAuthStore, useWalletSetup, useCopied, and the page host. Under Set an amount, an account with hadExternalWallet === true (missing hides it) also gets the underlined muted text button Move Bitcoin from another wallet (moveFunds.open), which calls requestMoveFunds.
  • 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: WalletReceive or WalletSend, each in a Card surface={false} with an sr-only h1 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 (UseWalletSendResult or undefined), manualEntry, and onManualEntry.
  • Returns / side effects: The view's column, or null for 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, lucide ArrowDownRight, pointing in) and Send on the right (wallet.sendButton, lucide ArrowUpRight), equal Button size="lg" in a max-w-sm two-column grid (data-footer-actions). They follow the page scroll: a progress from 0 (full: 56 px tall, text-base, 20 px icons, grid pt 0.5rem, footer bottom padding 1.25rem) to 1 (slim: 36 px, 0.875rem text, 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-glide cubic-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 carries SCROLL_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 a calc on --footer-collapse, which the component writes on the shell's frame body (AppShellContext bodyEl) together with data-footer-snap during a glide, so the footer padding and the forum home + follow; at rest (unset) every value equals the full size. Above them an aria-hidden, pointer-events-none 18px 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 is px-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, optional focus (receive | send | null): when the buttons come back after a view closed, that button takes the focus, and optional folded (default false). The buttons carry data-wallet-tour (receive, send), the targets of WalletTour.
  • 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-folding and 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 /wallet and /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 (or undefined), and whether a ?visual=send-… pin opens Send on mount (/welcome only; read through visualPin, so only in a Playwright build).
  • Returns / side effects: { shown, returnFocus, openReceive, openSend, manualEntry, setManualEntry, stepBack, close }. returnFocus names the view that just closed (for WalletFooterActions focus), null while a view is open. openSend does nothing without a send flow. stepBack closes 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 with send.abandon() and the page comes back. It returns false when no view is open. close (the wordmark and the Menu's Home) calls send.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 gets null.
  • 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-…), and useRemainingBalance (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 WalletHistory and WalletPaymentDetails.
  • 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 null for 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-rows pin (read through visualPin, 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 calls getWalletPayment(id), and again whenever useWalletStore.syncCount changes, 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 is missing; any other failed read is error with a retry that shows loading and reads again; a later read that fails keeps a payment already shown, and a wallet that stops being ready drops it back to loading; an answer after unmount is dropped. Under the ?visual=history-rows pin (Playwright builds only) it shows the WALLET_PAYMENT_FIXTURES payment with that id through toFixturePayment (or missing), under ?visual=heart-payment and ?visual=heart-payment-pending the heart fixture when the id matches (otherwise missing), under ?visual=repayment-payment the received or the sent repayment fixture whose id matches (otherwise missing), under ?visual=received-from-member, ?visual=received-member-unknown, ?visual=sent-to-member, and ?visual=sent-member-unknown the respective member payment fixture when the id matches (otherwise missing), under ?visual=history-error a failed read (error, whose retry does nothing), and reads nothing.
  • Inputs: id from the address, or null.
  • 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 in Suspense). Card surface={false} with an sr-only h1 Payment. Ready: a centred head with the direction icon in a round bg-app-card-muted badge, 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 by useHeartContext, 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 lucide HandCoins icon 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 and termDays, or only the day when termDays is 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. The repay: 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-3xl semibold), signed + / − (failed: struck through and muted). A shop payment shows the currency figure stored on that charge under it, from useShopChargeFigure (committedFiatFigure of 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 reads useSpotRate. 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> when memberAccountId is 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 (IconButton ghost, 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 opens https://mempool.space/tx/<txid> only after ExternalLinkWarning is 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 call useSpotRateState and 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, WalletBalance is shown with no balance sats. A session whose wallet is not open in this tab sees WalletLoginCard from OnboardingGate in place of this screen; the balance-locked-prf-unsupported pin adds the no-PRF alert above Log in. With no wallet here (useWallet disabled) 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 id query 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 AppShell with WalletChromeLeft top-left (the one arrow: the previous in-app view, the list when opened from it, or /welcome when this tab has none), SignedInChrome top-right, and OnboardingGate screen="wallet" around Suspense and WalletPaymentDetails.
  • 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 through listenForWalletPhrase and listenForWalletSetup while mounted, then unsubscribes both on cleanup. After every successful wallet read (syncCount changes while ready: the login, each SDK sync, and the read after a payment) it calls reportWallet. Every WALLET_REPORT_INTERVAL_MS (five minutes) while the wallet is ready it reads the synchronized balance with refreshWallet({ 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 useAuthStore and the status, balance, and identity key from useWalletStore.
  • Returns / side effects: A promise that never rejects. Without a session or a ready wallet nothing is sent. It lists every payment with listWalletReportPayments in pages of WALLET_REPORT_PAGE_SIZE (200) and posts them in requests of at most 200 with postWalletReport. 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 after WALLET_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 waits WALLET_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 as payment_received_seen with its id and amount. The body holds only the fields of WalletReportPayment: 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 usePathname and whether useAuthStore holds a session.
  • Returns / side effects: null. Runs startInteractionLog while mounted. While signed in it records screen_view for every path (query and fragment are never sent), and profile_opened with 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 events wallet_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), and wallet_move_done (amountSats), or recovery_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_failed carries reason, stage, errorName, errorCode, causeKind, elapsedMs, online, and visibility, 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, searchMentionAccounts their sessionToken; payFromWallet's send, useWalletPay and reportWallet the session at the start of the send or report; reportPaymentFailure the 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/:viewKey and /view-key/:viewKey is 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, or null, 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 most INTERACTION_BATCH_SIZE (50) events and 60 000 UTF-8 bytes of request body, each request with keepalive, 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_failed and wallet_open_failed together, the wallet_tour_* / wallet_move_* events together, and recovery_done as the group recovery (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) and startInteractionLog.

Function: logLogout

  • Purpose: Records logout and 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_EVENT on window while that session is still the current one, so a listener can still record its own event under it (the move-funds sheet records wallet_move_closed); those events go out with the queue below. Builds logout like logInteraction and sends it at once with POST /me/events in 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 every LOGOUT_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 every LOGOUT_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), logLogout resolves at once without waiting for the queue. LogoutButton bounds 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 after INTERACTION_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 on pagehide. Returns the function that stops the timer and removes both listeners.
  • Used by: InteractionLog.

Function: WalletPhraseScreen

  • Purpose: /wallet/phrase body. Recovery phrase or recovery error, with no receive QR.
  • Inputs: None.
  • Returns / side effects: Renders WalletScreenView surface="phrase" with useWalletPhrase().
  • 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/begin and parse options.
  • Inputs: Optional viewKey string and optional name string. A non-empty viewKey POSTs JSON { viewKey } with Content-Type: application/json and ignores name. Otherwise a non-empty name POSTs JSON { name } with Content-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. Sends X-App-Build (getBuildId). 503 code logins_closed throws LoginsClosedError; 403 code app_outdated throws AppOutdatedError.
  • Used by: usePasskeyLogin.submitName for a new account, and usePasskeyLogin.register only 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 only authenticateHeld limits allowCredentials (see Returns). Login PRF output is used only when that request's prf.eval.first equals the app's own prfEvalFirstSalt; a missing, unreadable, or different salt counts as absent. login authenticates with an existing passkey. When authenticate returns NotAllowedError and isInAppBrowser() is false, status becomes choice and registration is not started. When authenticate returns NotAllowedError while isInAppBrowser() is true, status becomes unsupported and register is not started. From choice, authenticate never falls through to register; register() (no view key) sets status name and starts neither startPasskeyRegistration nor credentials.create. submitName normalizes and, when valid, calls startPasskeyRegistration(undefined, normalized) then the existing create ceremony. register(viewKey) starts the claim immediately and does not show name. User cancel (NotAllowedError or AbortError) after a named create returns to name, not choice. After a choice was offered, user cancel (NotAllowedError or AbortError) on those ceremonies returns to choice; direct authenticate / register(viewKey) from ViewProfileClaim never sets that flag, so cancel returns to idle. Status unknown is authenticate finish Unknown credential: the hook calls signalUnknownCredential best-effort with the ceremony rpId and credential.id before showing it, and a later user-cancel returns to unknown while that flag is set. On iOS/iPadOS WebKit (including iPadOS desktop-site: Macintosh UA, MacIntel, maxTouchPoints > 1), credentials.get / credentials.create omit AbortSignal. cancel aborts an in-flight WebAuthn prompt and clears the choice flag. register(viewKey?) forwards an optional view key for public profile claim; retry after register(viewKey) resends the same key. login never sends a view key. Finish WrongAccountError clears the session (a held-back lockedSession stays, so its login card stays and shows login.wrongAccount), sets wrongAccount, status error with that message, and does not fall through to discoverable registration. register requires WebAuthn PRF on create, confirmed by one get() under the registration options' rp.id (obtainPrfFirst); missing PRF, a missing rp.id, or a get() that differs from create() aborts with wallet.prfUnsupported and 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 to rememberPhraseFromPrf just before the session is stored with setAuth (no extra prompt; what is sent to the api is unchanged); with the wallet configured, a login reports client.passkey.login.prf with prfPresent as a boolean only; without PRF output nothing happens. login / authenticate call clearSessionPhrase. On iPhone, iPad, or iPod below iOS 18, a named create still does not finish the account. NotAllowedError or AbortError from create or from the extra-key read reports client.passkey.register.ceremony with name, prfPresent: false, the begin challengeId, accountId when user.id decodes as a UUID, and message iOS <installed> below 18 at create or at prf, then the browser text when it fits the diagnostic allowlist. A missing extra key reports client.passkey.register.prf with prfPresent: false, those same ids, and message iOS <installed> below 18 at prf.absent. Both throw login.iosVersion instead of a silent cancel or wallet.prfUnsupported. On Android below 9, a named create does not finish the account. NotAllowedError or AbortError from create or from the extra-key read reports client.passkey.register.ceremony with name, prfPresent: false, the begin challengeId, accountId when user.id decodes as a UUID, and message Android <installed> below 9 at create or at prf, then the browser text when it fits the diagnostic allowlist. A missing extra key reports client.passkey.register.prf with prfPresent: false, those same ids, and message Android <installed> below 9 at prf.absent. Both throw login.androidVersion instead of a silent cancel or wallet.prfUnsupported. Every failed login posts client.passkey.login.fail before the card changes, even when no account id exists: the browser name, the allowlisted message when that text fits, and the begin challengeId when it is 64 hex. That row is written when credentials.get throws, when the assertion is missing, and when an in-app browser stops the ceremony first (stage login or authenticate, message in-app browser). A dismissed register that is not an old-iOS or old-Android stop posts client.passkey.register.fail with those fields, and accountId only when user.id decodes 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 with iOS <installed> or Android <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 on name; claim and paths before the name stay choice, idle, or unsupported. Begin and finish failures keep their own rows and do not need an account id.
  • Inputs: None (reads useAuthStore; calls isInAppBrowser on authenticate NotAllowedError, iosPasskeyBlock and androidPasskeyBlock on register, and iosInstalledVersion and androidInstalledVersion when a failed attempt is reported).
  • Returns / side effects: { status, login, register, submitName, authenticate, authenticateHeld, retry, cancel, error, recoveryPending, walletPasskeyMissed, nameError }. authenticateHeld limits the prompt to lockedCredentialId (allowCredentials) until that prompt ended without an answer for this held-back session (noteLockedPasskeyMissed), which sets walletPasskeyMissed until 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 has status with status in idle | starting | error | unsupported | choice | unknown | name | closed | outdated. error is the last Error.message when status === 'error', else null. nameError is invalid, taken, or null while status === 'name', else null. After a named create, retry returns to the name form and does not start create again. retry after register(viewKey) sends the same key again. retry after authenticate repeats 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 starts rememberPhraseFromPrf before setAuth, so listeners reacting to the new session wait for that derivation, then starts the sparse owner-account refresh after setAuth; that refresh is tied to the stored session token, so cancel or 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 span wallet.passkey with prompt: login (traceWallet). LoginsClosedError from any begin or finish sets closed and AppOutdatedError sets outdated, both with error null; neither retries on its own, clears a held-back session, or opens another card. RecoveryPendingError from authenticate finish (409 recovery_pending: the passkey belongs to a social recovery that is not finished yet) sets error with recoveryPending true and never calls signalUnknownCredential, because that passkey may become the account's only one; recoveryPending is a typed marker, true only while status === 'error', and every new run or cancel clears it.
  • Interaction log: After the session is stored, a completed registration is recorded as signup_completed and a completed login as login.
  • Used by: OnboardingGate, LoginCard, LogoutButton, and ViewProfileClaim.

Function: fetchComposeTarget

  • Purpose: GET /messages/compose-target so 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. firstPostFree is true only when the api sends true; 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, otherwise A reply needs a Bitcoin payment; postMessageVideo: Could not post your message).
  • Returns / side effects: Error instance named PostFeeRequiredError with 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/repayment with 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 carries paidSats and paidAmount, so a partially paid line remains due/scheduled while dueSats is its remainder. A due line carries waiting when its giver cannot receive yet, and waitingShares counts 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 startsOn from the api adds First repayment day: <date>. with the localized UTC date; a null or missing startsOn (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, when fundedAt is null, or when any day has no dueOn. 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'). Optional onLedger, 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 dueSats when present; when an older api omits it, the validated compatibility remainder is sats - paidSats (with a missing paidSats treated as zero). A fiat row likewise subtracts paidAmount from amount in integer cents, so a partial row, chart bar, split, and still-owed total all show only its remainder. On list="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) until fundedAt is set or a day has no dueOn; 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 is due, 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 marks waiting (its giver cannot receive yet; without that flag from an older api, a due line whose giver has canReceive: 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", with onLedger feeding LoanBlock). 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 from CreditLedger (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 is PublicMessageChrome. No OnboardingGate. No second back control. The note id is not validated as a UUID here.
  • Inputs: Dynamic route params (id). Loads GET /messages/:id/repayment through getRepayment (via CreditLedger). No session is required to view. Chrome follows the hydrated session.
  • Returns / side effects: CreditLedger with list="page" inside PublicMessageChrome. No generateMetadata.
  • Used by: Route /messages/[id]/repayment-list. The Repayment list link on a collapsed ForumGoalBar and on CreditLedger summary.

Function: proxyMessagesRepaymentGet

  • Purpose: Same-origin proxy for GET /messages/:id/repayment.
  • Inputs: App Router Request and 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 Request and 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/invoice with { sats }, { sats, text } when the visitor attached a reply comment, heart: true when the optional heart flag is set (a heart of the requested sats with no comment), and amountUsd, amountChf, amountEur, amountPhp when a preview rate is on screen. Empty text is 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, and amountPhp (each a two-decimal string or null), optional heart (true only). 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. sparkInvoice is the request the member's in-app wallet pays first (a string or null; pr is 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. 409 missing_requirements throws MissingRequirementsError; 409 credit_closed throws CreditClosedError. 404 throws NoteDeletedError instead of the collapsed payment copy. A 400 with code wallet_required throws WalletRequiredError (the member's own wallet is not set up yet) and one with cannot_receive throws CannotReceiveError (the receiving wallet cannot take this payment) (via throwIfWalletAnswer), recognised by the body's code only. A 403 body is read so a SUNDAY_REST heart is reported as sunday. A 503 body { error: 'HEART_UNAVAILABLE' } throws an Error whose message is HEART_UNAVAILABLE, so a heart is reported as heart_unavailable; any other 503 keeps the collapsed copy.
  • Used by: ForumLoader, MemberProfileScreen, PublicMessageThread, sendHeartTip.

Function: sendHeartTip

  • Purpose: One-click heart: postMessageInvoice of the click's heartSats with heart: true, then payFromWallet on sparkInvoice only. When rateDay is set, the four amounts are the spot of that amount. When rateDay is missing, those amounts stay omitted. A heart is exactly heartSats and fee-free: without a non-empty sparkInvoice, or when the confirm result is not amountSats heartSats with feeSats 0, nothing is sent and the reason is heart_unavailable; the Lightning pr is never paid. Otherwise send() runs at once. No amount dialog and no gift sheet. A wallet snapshot that is ready with less than heartSats stops with no_balance before any request. In a Playwright build only (visualPin), ?visual=heart-paid returns paid, ?visual=heart-needs-balance returns no_balance, and ?visual=heart-cannot-receive returns author_cannot_receive, both without invoicing. A send that ends failed with sentLate (the app stopped waiting after WALLET_SEND_TIMEOUT_MS) keeps that note's Spark invoice in tab memory. When sentLate resolves true the earlier heart counts as sent and the optional onPaid(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. When sentLate resolves false the 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 is pending, not listed yet (for up to HEART_TIP_UNSETTLED_MS, ten minutes), or the list cannot be read. A retap while that outcome is still in flight keeps the timeout_pending or paid settlement behavior; a failed payment, 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, optional rateDay, and heartSats), and an optional onPaid(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 a HeartTipFailure code: sunday (local Sunday or the api's SUNDAY_REST), no_balance (the wallet snapshot is ready below heartSats, before any request), insufficient_balance (prepare or send answers insufficient, or the live wallet is ready with a balance below heartSats, after the tap already showed the +1), wallet_setup_due (setup still due, or the api's wallet_required), author_cannot_receive, credit_closed (the invoice target is a loan that no longer collects), rate_limited, heart_unavailable (not heartSats fee-free, no Spark invoice, or a 503 HEART_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), and in_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 failed outcome except no_balance is sent to error reporting with captureMessage('Heart not sent') at level error, the tag heart_reason set to the code, and messageId as the only extra. No amount, name, invoice, or token is attached, and the event passes the same beforeSend scrubber 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_sent with the message id and amountSats heartSats, under the session of the click, next to the payment_sent that payFromWallet records; a send the app stopped waiting for is recorded once its sentLate resolves true. Every prepare or send of a heart that does not pay is passed to reportPaymentFailure with the flow heart and amountSats heartSats, so it is recorded as payment_failed but 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 below heartSats), and a prepared heart other than heartSats at ₿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. pressed stays while the remaining extra is above 0 or the +1 still shows. A refusal because the author cannot receive (author_cannot_receive) sets cannotReceive; credit_closed sets creditClosed. 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-messageId heart machine for the three callers. A tap passes the current spot as rateDay and the account's stored heartSats (default 1). A tap on a signed-in, writable board vibrates and shows the filled heart with +1 at once, before any request, for HEART_TIP_PLUS_ONE_MS (700 ms, the length of the +1 animation); sendHeartTip pays in the background. After 700 ms only the +1 leaves; the fill and the count remain. Session hearts not yet in the server heartCount are extra; 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's extra; it is also reported. The one exception is a wallet snapshot that is ready with less than heartSats (or the heart-needs-balance pin): then there is no vibrate, no new fill, and no +1, only the role="alert" line forum.heartNeedsBalance under the heart, and nothing is sent. The Playwright-only heart-credit-closed-refreshed pin applies creditClosed to 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 reports sentLate true restores that tap's 1 in the stored session extra, reconciles it against the current server count, and calls onPaid once 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 the timeout_pending or paid settlement 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 optional onPaid(messageId).
  • Returns / side effects: { onHeartTip, heartTipViews } passed to ForumBoard; each view is { pressed, plusOne, needsBalance, extra }, plus cannotReceive: true after cannot_receive or creditClosed: true after credit_closed. The board shows forum.payErrorAuthorWallet or the localized forum.payErrorCreditClosed loan-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") with MessagesChromeLeft in Suspense top-left (fallback ProfileChromeLeft), SignedInChrome top-right, and OnboardingGate around InboxLoader. Conversation HTTP is under /conversations.
  • Used by: Route /messages.

Function: InboxLoader

  • Purpose: Client loader for /messages. Session and account from useAuthStore; returns null without a session. Fetches the unpaged GET /conversations list, opens ?c= via onOpen router.push, and posts replies. An open thread sets showAttach true: camera photos or JPEG/PNG/WebP gallery stills (cap 10) via prepareForumPhoto; photo-only send allowed. Send is disabled while posting || preparing. Thread stills load with fetchConversationMessagePhoto. 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 calls fetchConversation(session, openId) without a cursor for the newest 20-message page. An IntersectionObserver on InboxScreen's nearStartRef (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 set nextCursor and 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 (no onBack handler). Moderators get showFilter true; members see the unfiltered inbound list. ?c= opens only after the inbox list loaded. For a moderator an unlisted ?c= first resolves fetchModeratorGroup once per id (neutral Loading…, not the list, while it runs); when that id matches, the thread never opens and fetchConversation is not called. A listed moderator_group row never opens either. Other roles, and a failed lookup, fall through to fetchConversation; the api rejects accounts that may not read the thread. Also calls useSpotRate() and passes rateDay to InboxScreen. 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 null without a session. Calls fetchConversations, fetchConversation, fetchModeratorGroup (roleAtLeast(role, 'moderator'), unlisted ?c= only), prepareForumPhoto, fetchConversationMessagePhoto, postConversationMessage, postConversationInvoice. After a successful thread fetch, local unread: false and unreadMessageCount: 0, then fire-and-forget markConversationRead, bumpUnreadAppBadgeEpoch and refreshUnreadAppBadge (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 or postConversationMessage, the matching list row is also unread: false and unreadMessageCount: 0 (including when the first thread fetch failed). When that poll fills a thread whose first fetchConversation failed (messages === null), it also clears messagesError and takes nextCursor from the poll page so older history can still prefetch. Must not fail the thread view. A WalletRequiredError (api code wallet_required) from postConversationInvoice sets the form error walletRequired. When the open thread's row has canReceive: 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 MentionTextarea and sats amount field (showAmount false 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 (AmountEntry layout="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 through ForumQuotedBody so a pasted https://21.gifts/messages/<uuid> unfurls as a nested quoted-note card, using the same rateDay (a stored string as-is; a null or missing field on a passed stored object shows the current spot, and stays off the line only when that spot is not loaded; omitting stored uses the current spot rate). A stored mentions list turns @username into a profile button for /members/<accountId>. That mark does not notify the person. photoUrls (${messageId}:${index}) render attached stills. When showFilter is true (moderator), the list is filtered by the origin control (Direct / Contact / Damus; default Direct). Rows with kind moderator_group are never listed; the closed staff room lives on /moderate/group. Members (showFilter false) see inbound rows except moderator_group and no control. Each list row and the open-thread header show an origin label from conversation.kind (Contact / Direct / Damus / Moderators chat group). Unread inbound rows use font-semibold names, text-app-fg last 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 when unread is true and the count is 0), and aria-label inbox.threadUnread with {name} and {count}. The word Unread is not visible text. Read inbound last text is a muted preview. When lastFromMe is true and lastText is non-empty, the list preview is inbox.sentPreview (You: {text}) in a filled chip; gift-only last messages (lastSats > 0, empty lastText) show the formatted amount . The list does not offer Translate. Thread remainders go through ForumQuotedBody with conversationId (translateConversationMessage); nested forum quotes stay on translateNote. Thread incoming messages are full-width muted note cards; fromMe messages render as filled app-btn bubbles on the right labelled inbox.you. Gift-only bubbles use forum.giftReply; text+sats shows the amount under the body. An open invoice shows the bottom PaySheet (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 (no onBack, no in-card back). Heading and incoming author names with accountId are inbox.authorProfile buttons to /members/:id; fromMe stays inbox.you text; Damus/missing id stays plain text. A staff viewer sees another staff reply as an incoming muted card with that person's name (profile link when accountId is set). fromMe / inbox.you only 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 via preferredFiatSuffix: 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 optional rateDay (the current spot rate). A message whose giftFor points at another message renders via groupThreadGifts as a nested role="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, nearStartRef attaches 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 (openId set, 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 to window while the node is missing (window only 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 is WalletPay, which pays from the member's in-app wallet (sparkInvoice when the api issued one, otherwise pr, which is also paid when the wallet refuses the Spark invoice); the sheet shows no invoice QR on any device. When the open thread has canReceive: 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 InboxLoader or ModeratorGroupScreen.
  • Returns / side effects: React element. InboxScreen itself does not fetch; ForumQuotedBody may call fetchPublicMessage for pasted /messages/<uuid> URLs. Form error walletRequired renders role="alert" with the wallet-required link (inbox.errorWalletRequired) to /wallet. With an open invoice, the pay sheet is a PaySheet (inside a Collapse with holdMs PAY_SHEET_HOLD_MS) titled Send to {name} with the open thread's name (Send without one), its WalletPay button Send {amount}, and its success step Sent to {name} (or Sent); Close calls onPayCancel.
  • Used by: InboxLoader, ModeratorGroupScreen.

Function: fetchConversations

  • Purpose: GET /conversations with Bearer and parse { conversations, unreadCount }. Missing unread defaults false; missing unreadCount defaults 0; missing unreadMessageCount defaults 0. The api returns incoming threads, plus the member's own 21.gifts contact thread when it has a message. GET /conversations never lists the moderator_group thread, even for moderators. Each row includes required kind: member_member | member_platform | member_damus | moderator_group, required lastFromMe (true when the last message was sent by this session as the actor, not when another staff member sent as the platform), required lastSats, optional accountId (counterpart), unread, and unreadMessageCount (inbound unread messages). Envelope unreadCount is 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/:id with Bearer, always sending limit=20, plus optional cursor and sinceMessageId. Parses { messages, nextCursor? }. Each message includes required fromMe (true iff this session is the actor) and sats, plus hasPhoto / photoCount (client default 0 when omitted). For a staff viewer, incoming name and optional accountId are the actor when the api sends them. The newest page is returned first and messages inside each page are oldest-first; nextCursor is supplied only for a full page.
  • Inputs: Session token, conversation id, optional { sinceMessageId, cursor, signal }.
  • Returns / side effects: { messages, nextCursor }, normalizing an omitted nextCursor to null, or throws visitor copy.
  • Used by: InboxLoader, ModeratorGroupScreen.

Function: postConversationMessage

  • Purpose: POST /conversations/:id with { text } and, when photos is non-empty, { photo, photos } (first still duplicated as photo, at most 10 JPEG/PNG/WebP stills). Empty text is allowed when photos are present (Moderators group and /messages Direct/Contact/Damus). Staff replies on official threads still send as the platform account on the api, but the created message's fromMe, name, and accountId follow 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/photo or /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: GET on /conversations/[id]/messages/[messageId]/photo and /photo/[file].

Function: postConversationInvoice

  • Purpose: POST /conversations/:id/invoice with { sats }, { sats, text }, and amountUsd, amountChf, amountEur, amountPhp when a preview rate is on screen. Empty text is omitted. A missing preview omits those four fields.
  • Inputs: Session token, conversation id, sats, optional text, optional shown amountUsd, amountChf, amountEur, and amountPhp (each a two-decimal string or null).
  • Returns / side effects: { pr, amountSats, messageId, sparkInvoice? }, or throws api/visitor copy. sparkInvoice is optional and may be null, as on postMessageInvoice. A 400 with code wallet_required throws WalletRequiredError and one with cannot_receive throws CannotReceiveError (via throwIfWalletAnswer); InboxLoader maps CannotReceiveError to authorWallet.
  • Used by: InboxLoader.

Function: openConversation

  • Purpose: POST /conversations with { forumMessageId }.
  • Inputs: Session token and forum note/reply id.
  • Returns / side effects: Conversation row, or throws on 400/404/other.
  • Used by: MemberProfileScreen Message (profile.message).

Function: markConversationRead

  • Purpose: POST /conversations/:id/read with 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: InboxLoader after a successful thread fetch (fire-and-forget; failures are ignored). ModeratorGroupScreen after 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 Request and 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 Request and 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 Request and 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 Request and 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") with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate screen="welcome" around NotificationsLoader. Notification HTTP is under /forum/notifications (no route.ts beside this page).
  • Used by: Route /notifications.

Function: NotificationsLoader

  • Purpose: Client loader for /notifications. Fetches GET /forum/notifications (posts, replies, payments, hearts, moderator appointment, and moderator proposal). After a successful list fetch, bumpUnreadAppBadgeEpoch then set the badge to remaining inbox unread plus staff-room unread (0 or 1; notifications treated as 0; visiting /notifications does not force badge 0 when inbox or staff-room unread remains). Repeats after markAllNotificationsRead if the session is unchanged. Fetches conversations (fetchConversations) and, when roleAtLeast(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 a moderator_proposal row goes to /moderate/proposals without markNotificationRead. Opening a moderator_appointed row waits for markNotificationRead then goes to /welcome (still navigates if that POST fails; skips navigation if the session changed). A forum_reply or forum_mention goes to /messages/{replyId} without waiting. A forum_post, zap, or heart goes to /messages/{parentId} without waiting. Ids are URI-encoded.
  • Inputs: None (session from the auth store).
  • Returns / side effects: React element or null without a session. No composer. After a non-cancelled successful list fetch, marks all read fire-and-forget, then bumpUnreadAppBadgeEpoch and sets the home-screen badge to remaining inbox unread plus staff-room unread (0 or 1; notifications treated as 0). Repeats after markAllNotificationsRead if the session is unchanged. Fetches conversations (fetchConversations) and, when roleAtLeast(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 with readAt set, 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_appointed title uses notifications.moderatorAppointed with no {name} placeholder; post text or Photo, except a forum_post whose text equals name omits 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 when text is non-empty — empty text omits the body line and does not use notifications.photoPost / photoOnly; time; unread semibold). onOpen receives the row object. No composer, no thread view, and no filter. Unread rows (readAt === null) are a section above rows that already have readAt, 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/notifications with Bearer and parse { notifications, unreadCount }.
  • Inputs: Session token.
  • Returns / side effects: { notifications, unreadCount }, or throws visitor copy Could not load notifications. Please try again.
  • Used by: NotificationsLoader, useUnreadCount, refreshUnreadAppBadge, ForumLoader (welcome appointment banner).

Function: markNotificationRead

  • Purpose: POST /forum/notifications/:id/read with 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: NotificationsLoader on row click; ForumLoader when the welcome appointment pill is clicked.

Function: markAllNotificationsRead

  • Purpose: POST /forum/notifications/read-all with Bearer and optional JSON { endpoint } when this browser has a push subscription. Non-ok throws. When the body has a tags array, those local notifications are closed. A body without tags closes nothing.
  • Inputs: Session token.
  • Returns / side effects: void.
  • Used by: NotificationsLoader fire-and-forget after a successful list fetch.

Function: markNotificationsReadForMessage

  • Purpose: POST /forum/notifications/read-by-message with Bearer and JSON { messageId, endpoint? }. endpoint is sent only when the current push endpoint is a non-empty string. Non-ok throws visitor copy Could not mark notification as read. On success, closes local notifications for string tags; a missing tags field is [].
  • Inputs: Session token and forum message id.
  • Returns / side effects: { ok: true, tags: string[] }.
  • Used by: ForumLoader when a note becomes expanded, NoteTranslate when Translate is requested for a forum note while a session is present (not for a conversation message), PublicMessageLoader when a signed-in message page is ready, MemberProfileScreen when a profile note becomes expanded, and PublicMessageThread when a thread note becomes expanded.

Function: markVisibleForumNoteRead

  • Purpose: POST /forum/notifications/read-visible with Bearer and JSON { messageId, endpoint? }. endpoint is sent only when the current push endpoint is a non-empty string. Non-ok throws visitor copy Could not mark notification as read. On success, closes local notifications for string tags; a missing tags field is [].
  • Inputs: Session token and forum message id.
  • Returns / side effects: { ok: true, tags: string[] }.
  • Used by: ForumLoader when 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 than epsilonPx is false. A card 2px past the root is false. A card exactly 1px past is true.
  • Inputs: Card and root DOMRectReadOnly picks (top, bottom, left, right, width, height), and optional epsilonPx (default 1).
  • Returns / side effects: Boolean. No side effects.
  • Used by: ForumLoader when measuring li[data-message-id] inside the shell scroller.

Function: activeMention

  • Purpose: Find the @username token 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 }, or null when 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 @username and 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 People listbox. Inserts the chosen handle through onChange.
  • Used by: The post composer and reply composer in ForumBoard, the ask-for-money text step in ForumAskWizard, the shop text step in ShopAddWizard, and InboxScreen (inbox and the moderator room).

Function: searchMentionAccounts

  • Purpose: Load username suggestions for an @ token. Calls same-origin GET /forum/mentions, adding q only 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 as search with 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 string id, username, and name. 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, and ForumLoader.

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 Request and 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 Request and 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), and SignedInChrome with one. OnboardingGate screen="welcome" allowGuest. HTML /statistics is the page, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left and OnboardingGate screen="welcome" allowGuest around StatisticsScreen. No route.ts beside 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 /moderate is the hub, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left, SignedInChrome top-right, and OnboardingGate screen="welcome" around ModerateScreen. Hidden HTTP lives under /forum/messages/hidden; proposal HTTP under /trust/proposals; grant-application HTTP under /funding/applications (no route.ts beside 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 by roleAtLeast.
  • 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 role meets or exceeds min by numeric rank. An equal rank meets the minimum. A missing account (null/undefined role) is never at least any role.
  • Inputs: role — live account role, or null/undefined when 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 for initiator and founder, false for every lower role (including fond and software_developer) and for null / undefined.
  • Inputs: role — live account role, or null/undefined when 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, or null / undefined when signed out; noteAccountId — the note's accountId if 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, and PublicMessageThread (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 } or null when the account snapshot is missing; parentAccountId — the parent note's accountId if the api sent one (a missing id is not treated as exempt).
  • Returns / side effects: Boolean. Pure, no side effects; delegates to isOwnNote and roleAtLeast.
  • 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: false for a live member note (accountId set, no deletedAt) 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, or null / undefined when signed out.
  • Returns / side effects: Boolean. Pure, no side effects.
  • Used by: ForumBoard (label, disabled heart, Gift, Lend, and reaction amount), ForumLoader, MemberProfileScreen, and PublicMessageThread (a reply never invoices a gift to that author).

Function: utcDayFromMs

  • Purpose: UTC calendar day YYYY-MM-DD of an instant, taken from toISOString (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 — UTC YYYY-MM-DD.
  • Returns / side effects: Previous UTC day string. Pure; no I/O. Delegates to utcDayFromMs.
  • Used by: StatisticsScreen and ModerateScreen to pick yesterday.

Function: countOnDay

  • Purpose: Person count on yesterday from officialCount. First matching day wins.
  • Inputs: series — spendOverTime oldest-first; yesterday — UTC day to look up.
  • Returns / side effects: That day's officialCount, 0 when the day is missing, or null when any point omits officialCount. Pure; no I/O.
  • Used by: StatisticsScreen.

Function: chartRows

  • Purpose: Last 30 UTC days ending on today, oldest first, with person counts from officialCount.
  • Inputs: series — spendOverTime oldest-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 locale for the yesterday sentence.
  • Inputs: day — UTC YYYY-MM-DD; locale — active UI locale.
  • Returns / side effects: Locale date string in the UTC zone. Pure; no I/O.
  • Used by: StatisticsScreen in the yesterday sentence.

Function: chartDayLabel

  • Purpose: Axis tick label for a UTC day as numeric day and month in locale.
  • Inputs: day — UTC YYYY-MM-DD; locale — active UI locale.
  • Returns / side effects: Short numeric day-month label in the UTC zone. Pure; no I/O.
  • Used by: ShopActivityChart and PeopleCountChart for 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/spot with no Authorization. The body is { asOf, source, rates }; rates leaves out a code the api could not price. Without any quote the api answers asOf and source null and rates {}, which is "no rate".
  • Inputs: None. fetch('/fx/spot') with no Authorization.
  • Returns / side effects: FxSpot parsed by fxSpotSchema (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 is export const GET = proxyFxSpotGet on /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/activity with 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 via fetch. Does not require the last day to be the browser's today.
  • Used by: StatisticsScreen shop panel.

Function: proxyShopActivityGet

  • Purpose: Same-origin proxy for api GET /shops/activity. App route is export const GET = proxyShopActivityGet on /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=20 with no Authorization. ShopList calls it whether or not an account is signed in. An optional cursor is sent as &cursor=. A missing nextCursor is the end of the list. nextCursor: null is rejected. A shop npub that fails SHOP_NPUB_RE is rejected. place may be null, and address may be null. A body that omits place, or omits address on a place object, is rejected. Otherwise this throws and the list shows shops.loadError.
  • Inputs: Optional cursor string. Omit it for the first page. fetch('/shops/list?limit=20') sends no Authorization header.
  • Returns / side effects: { shops: ShopListItem[]; nextCursor: string | null }. Network via fetch. Throws Could not load shops. Please try again. when the response is not ok or the body fails shopListResponseSchema.
  • Used by: ShopList.

Function: proxyShopListGet

  • Purpose: Same-origin proxy for api GET /shops. App route is export const GET = proxyShopListGet on /shops/list. No bearer is required. Forwards the incoming request unchanged, including limit and cursor.
  • 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/places with no Authorization. GrantPlacesPanel calls it on the grant pages. The body must match grantPlacesSchema (round and nextGoalShops positive integers, places, admitted, and placesLeft nonnegative integers, startsAt a string); otherwise this throws.
  • Inputs: None.
  • Returns / side effects: GrantPlaces. Network via fetch. Throws Could 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/goal with Authorization: Bearer. GrantGoalsScreen calls it only when a session exists. The body must be 7 unique contiguous UTC days, oldest first, plus a nonnegative qualifyingShops; otherwise this throws and the goals page shows its error state. Does not call fetchShopActivity.
  • Inputs: sessionToken — bearer session. fetch('/funding/goal') sends that token and does not invent one.
  • Returns / side effects: GrantContinuation (days, qualifyingShops). Network via fetch. 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 is export const GET = proxyFundingGoalGet on /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 is fill-app-subtle; other bars are fill-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, and ariaLabel.
  • Returns / side effects: SVG figure. No network.
  • Used by: StatisticsScreen (30 days) and GrantGoalsScreen (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 is fill-app-subtle; other bars are fill-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, and ariaLabel.
  • 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. When roleAtLeast(..., 'moderator') and yesterday's person count is a number (including 0; not loading and not the people error panel, including omitted officialCount), closed StaffFunctions sits after the people chart and before the shop panel; its only child is the payout ButtonLink (href /moderate/payouts, variant secondary, size lg, label moderate.payouts.link). Basis and verified never render StaffFunctions. A signed-out visitor never renders StaffFunctions.
  • Inputs: Account from useAuthStore; catalog and locale via useTranslations.
  • Returns / side effects: A React element. No session still fetches. Fetches GET /gifts/stats and also calls fetchShopActivity. Does not return null.
  • Used by: StatisticsPage.

Function: ModerateScreen

  • Purpose: Client moderation hub of staff tools. Staff (roleAtLeast(..., 'moderator')) see a labeled Goals ButtonLink (variant="secondary" size="lg") → /grants/goals (first tool), a labeled Hidden notes ButtonLink (variant="secondary" size="lg") → /moderate/hidden, a labeled Open proposals ButtonLink (variant="secondary" size="lg") → /moderate/proposals that shows proposalCount plus moderate.proposals.unread when greater than zero, a Moderators chat group ButtonLink → /moderate/group that shows the staff-room unread count plus moderate.groupUnread when unread, a labeled Handbook ButtonLink (variant="secondary" size="lg") → /moderate/handbook, a labeled Show payout per person ButtonLink (variant="secondary" size="lg") → /moderate/payouts, and a labeled Show activity per shop ButtonLink (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 from useUnreadCount. Renders null without a session. No un-hide control.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations; useUnreadCount(true, { writeBadge: false }) for Open proposals proposalCount and Moderators chat group staff-room unread (network for those counts; does not write the home-screen badge).
  • Returns / side effects: React element or null without a session. Does not fetch GET /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/handbook is the handbook page, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around ModerateHandbookScreen. 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 and HandbookCopyLink tone="app". Non-staff signed-in visitors see the heading plus forbidden copy and no chapters. Renders null without 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 via useTranslations.
  • Returns / side effects: React element or null without 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/hidden is the hidden-notes page, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around HiddenNotesScreen. Hidden HTTP is under /forum/messages/hidden (no route.ts beside 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 listHiddenMessages and show the lead copy plus the newest-hidden-first list (a non-interactive External badge next to the name when the row has a via value) (or empty / loading / try-again). A 21.gifts author name is a Link to /members/:accountId. The time is a Link to /messages/:id. An external name stays text inside the note link. The note text sits outside that link in TranslatableNoteBody (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. Renders null without 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 via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /forum/messages/hidden only 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/payouts is the table, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around FundingPayoutsScreen. JSON lives under /funding/payout-days because Next.js forbids a route.ts beside 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 fetchFundingPayoutDays and 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 with accountId links 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. Renders null without 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 via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/payout-days only 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/shops is the table, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around ShopActivityShopsScreen. 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 fetchShopActivityShops and 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 as N / windowDays, and the last charge day as a medium localized UTC date or Never. A shop with activeDays 0 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. Renders null without a session. The page chrome owns the back; this screen renders no back control.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /shops/activity/shops only 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/proposals is the queue, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around ProposalsScreen. Proposal HTTP lives under /trust/proposals because Next.js forbids a route.ts beside 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 fetchTrustProposals and 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. when proposedBy.id === account.id. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Renders null without a session. The page chrome owns the back; this screen renders no back control. A failed confirm or reject shows trustChain.actionFailed.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /trust/proposals only when the role is at least moderator. Confirm posts POST /trust/confirm-moderator; reject posts POST /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/applications is the queue, not a GET proxy. /moderate/applications redirects there. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around FundingApplicationsScreen. Application HTTP lives under /funding/applications because Next.js forbids a route.ts beside this page.
  • Inputs: None.
  • Returns / side effects: The open-applications screen inside fill AppShell.
  • Used by: Route /grants/applications. /moderate/applications redirects here.

Function: FundingApplicationsScreen

  • Purpose: Client queue of open 21 gifts grant applications. Staff (at least moderator) fetch fetchFundingApplications and 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. Renders null without a session. The page chrome owns the back; this screen renders no back control.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/applications only 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. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around FundingApplicationDetailScreen. 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 fetchFundingApplication and answer two questions against living-room posts (no replies; post text uses TranslatableNoteBody, the applicant name stays plain; each post keeps its own time; there is no application time under the name). The first is funding.review.question.staff, with an About link to /about. Yes shows funding.review.truth. Yes there posts postFundingAdmit. No on either question posts postFundingReject while the grant is pending or trial. A failed decision shows trustChain.actionFailed. Non-staff signed-in visitors see the heading plus forbidden copy and do not fetch. Renders null without 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 from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/applications/:accountId only when the role is at least moderator. Decide buttons only when grant.status is pending or trial. Successful Admit / Reject leaves the buttons disabled and returns to /grants/applications with returnToView (a step back when the queue opened this page, otherwise a replace). When Admit throws FUNDING_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 of trustChain.actionFailed, and the member stays on the page. A decision answer for an application that is no longer on screen (another accountId) 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 AppShell with ProfileChromeLeft and SignedInChrome, OnboardingGate screen="profile" (name, username, and rules agreement, like /settings), then SecurityScreen.
  • Used by: Route /security.

Function: SecurityScreen

  • Purpose: Signed-in /security body: securing the account, the shares kept for others, and the recovery phrase and previous wallets, for members who are not technical.
  • Inputs: session and account from useAuthStore (sparkWalletVerified, socialRecoverySetUp, passkeyCredentialId).
  • Returns / side effects: null without a session or before the account has loaded. Otherwise a Card surface={false} with h1 Account security (nav.security) and three sections, each labelled by an h2 in the section ramp and separated by a rule. Protect my account (security.protect, id protect): 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) when socialRecoverySetUp is 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 a ButtonLink 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, id help-others): the muted security.helpBody and a secondary Shares I keep for others (socialRecovery.heldLink) to /settings/held-shares. More options (security.more, id more): with a non-empty passkeyCredentialId a secondary Recovery phrase (settings.recoveryPhrase), otherwise the muted wallet.addPhraseHint and a primary Add recovery phrase (wallet.addPhrase), both to /wallet/phrase; then PreviousWalletsRow. 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 AppShell with ProfileChromeLeft and SignedInChrome, OnboardingGate screen="profile" (name, username, and rules agreement), then SettingsScreen.
  • Used by: Route /settings.

Function: SettingsScreen

  • Purpose: Signed-in /settings body: the home of the member's preferences and account actions. Profile keeps identity only.
  • Inputs: session and account from useAuthStore (username, amountUnit), the preferred fiat from useFiatPreference, getAppVersion(), and the page host for the address.
  • Returns / side effects: null without a session or before the account has loaded. Otherwise a Card surface={false} with h1 Settings (settings.heading) and five sections, each labelled by an h2 in the section ramp and separated by a rule: Wallet (wallet.title, id wallet): 21.gifts address (id address): giftsLightningAddress in font-mono with an icon-only ghost Copy (wallet.payment.copyValue; Check in text-app-success and a polite sr-only Copied for two seconds), or, while no username is set, Set a username first. and UsernameForm variant="overlay" in place, and then Default amount (settings.defaultAmount): a neutral SegmentedControl ₿ / the preferred fiat code bound to account.amountUnit that saves through saveAmountUnit, with the muted hint settings.defaultAmountHint, then Heart amount (settings.heartAmount), which saves the amount sent by a heart, and, while the in-app wallet is ready (or a pin dfx-login, dfx-login-busy or dfx-login-error is set), Log in at DFX (settings.dfxLogin) with the muted hint settings.dfxLoginHint: a press opens a new tab and clears that tab's opener right after it opens, before any wait, then calls dfxLoginUrl and, unless the member has closed the tab, sends it to the DFX Buy page; whether dfxLoginUrl answers 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 shows settings.dfxLoginBusy, a blocked tab opens nothing, does not call dfxLoginUrl, and shows settings.dfxLoginError in a role="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, id notifications): PushToggle. Account (settings.account): LogoutButton. About & legal (settings.about): next/link rows 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 (id previous-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, and useSpotRate (read only while some wallet shows a positive balance).
  • Returns / side effects: null while 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 calls retry. 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 for null, Empty for 0, else formatBitcoin with the current spot in the member's fiat after ·, or bitcoin alone while the spot is not loaded), and a secondary ButtonLink 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: session and account.sparkWalletVerified from useAuthStore.
  • 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 is ready and empty; an api that does not mount the route (no LNURL server) then shows no load error either. wallets is empty unless ready. retry reads again (loading until 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 AppShell with ProfileChromeLeft and SignedInChrome, OnboardingGate screen="profile" (name, username, and rules agreement, like /settings), then HeldSharesScreen.
  • 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 from useAuthStore, and the UI locale.
  • Returns / side effects: null before the account has loaded. Every list step is a Card surface={false} with h1 Shares I keep for others (heldShares.title) and the intro (heldShares.intro). Opening: BusyLine heldShares.opening. Unlock: the muted heldShares.unlockHint, the alert of a failed prompt in the recovery phrase's wording (wallet.prfUnsupported, wallet.timeout, or wallet.errorGeneric), and the primary Button size="lg" Open my shares (heldShares.unlock, disabled with a spinner while the prompt runs). Load error: the alert heldShares.loadError and Try again (login.retry). List: the notice of the last scan or delete (You now keep a share for @username. as role="status", or a role="alert" with shareCode.invalid, heldShares.own, heldShares.duplicate naming the owner, heldShares.saveError, heldShares.deleteError, or heldShares.lockedDeleteError for the boxes that do not open), the primary Button size="lg" Keep a share (heldShares.keep; BusyLine heldShares.saving in 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 ghost IconButtons Show code for @username (lucide QrCode, heldShares.show) and Delete share of @username (lucide Trash2 in text-app-danger, heldShares.delete), then, when boxes do not open with the current words, one muted row heldShares.lockedOne or heldShares.lockedMany with the icon-only Delete the shares that cannot be opened (heldShares.deleteLocked). Each trash opens InlineConfirm (heldShares.deleteConfirm or heldShares.deleteLockedConfirm, check heldShares.deleteYes, X heldShares.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) holding QrScanner with copy heldShares.scanHint, heldShares.cameraDenied, and heldShares.cameraUnavailable. Code: an sr-only h1, h2 Share of @username (heldShares.qrTitle), heldShares.qrBody, and QrCode of the payload labelled Share code (heldShares.qrLabel, no logo). The one top-left arrow (AppShellTopLeft with ProfileChromeLeft 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-shares for the signed-in member, whose account.id is 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, or removeLocked asked while a keep, a delete of one share, or the delete of the boxes that do not open runs does nothing.
  • Inputs: session and account.id from useAuthStore; the words from tab memory (settlePhraseDerivations, then peekSessionPhrase) or from useWalletPhrase (showPhrase, the passkey prompt of Show recovery phrase, then hidePhrase); uses heldShareBoxKey, loadHeldShares, keepHeldShare, deleteHeldShareBox, and parseShareCode.
  • Returns / side effects: { load, unlocking, unlockError, shares, lockedCount, saving, view, notice, confirmDelete, confirmDeleteLocked, unlock, reload, scan, onScanResult, showQr, askDelete, remove, askDeleteLocked, removeLocked, cancel, back }. load is opening (words looked up or boxes read), unlock (no words in tab memory: unlock() asks for the passkey, unlocking and unlockError mirror that prompt), loadError (words that give no key or boxes that cannot be read; reload() tries again), or ready. shares are sorted by owner username; lockedCount counts the boxes that do not open with the current words, which are never deleted on their own. view is list, scan, or { qr: share }. scan() (only when ready and no keep or delete runs) clears the notice and pending confirms and opens the camera. onScanResult(text) returns to the list, sets saving, and keeps the share (keepHeldShare: the box that already holds the code, otherwise a new box): stored with the owner's username, or the refusal invalid, own, duplicate (that owner and set among the opened boxes), or saveError, with the username when the payload was readable. showQr(share) opens its code. askDelete(share) sets confirmDelete to its box id, askDeleteLocked() sets confirmDeleteLocked, cancel() clears both. remove(share) deletes its box and drops it from the list, or gives deleteError and keeps it. removeLocked() deletes every box that does not open; the ones the api did not delete stay counted with lockedDeleteError. back() returns true after stepping from the camera or a code to the list, and false on 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 AppShell with ProfileChromeLeft and SignedInChrome, OnboardingGate screen="profile" (name, username, and rules agreement, like /settings), then SocialRecoveryScreen.
  • Used by: Route /settings/social-recovery.

Function: SocialRecoveryScreen

  • Purpose: Body of /settings/social-recovery, the owner side of Social Recovery: the steps of useSocialRecoverySetup under one page title.
  • Inputs: useSocialRecoverySetup(), the signed-in account from useAuthStore (socialRecoverySetUp for the renew note), and the client-side router.
  • Returns / side effects: null before the account has loaded. Otherwise a Card surface={false} with h1 Secure my account (secure.title) and one step. Intro: the muted secure.introBody, the warning secure.introWarning in font-medium text-app-fg, secure.introAccounts, secure.introRemote, and secure.introRenew only when socialRecoverySetUp is true, then a primary Button size="lg" Continue (secure.start); while checking, a BusyLine with Checking your wallet… (secure.checking) stands in its place. Person 1 / Person 2: h2 secure.shareHeading, secure.shareBody, on person 2 also secure.shareDifferent, the QrCode of that person's payload labelled secure.shareQr (no logo), a primary Button size="lg" Person {n} has scanned it (secure.scanned), and under the muted secure.refusedHint a secondary Button size="lg" Start again with new codes (secure.resplit). Saving: the BusyLine Saving the 21.gifts backup… (secure.saving). Done: h2 secure.doneTitle, secure.doneBody, and a primary Button size="lg" Done (secure.done) that calls returnToView('/security', router). An error replaces the step with p[role=alert] (secure.walletMismatch, wallet.balanceError, secure.saveError, or secure.walletChanged) and, except for the mismatch, Try again (login.retry) calling retry. The one top-left arrow (AppShellTopLeft with ProfileChromeLeft onBackClick) runs back: 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 from useAuthStore (id, username, sparkPubkey, sparkWalletVerified); uses splitPhrase, encodeShareCode, and putRecoveryShare. In a Playwright build only (visualPin), ?visual=sr-checking, sr-share-1, sr-share-2, sr-done, sr-mismatch, and sr-save-error open 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 }. step is intro, checking, share1, share2, saving, or done. start() (Continue) reads the tab phrase (none → error wallet), awaits ensureWalletConnected (a throw → wallet), and stops with mismatch unless the account's sparkWalletVerified is true and its sparkPubkey equals the wallet key in lower case; then it splits the words (splitPhrase checks every pair) and builds the payloads of shares 1 and 2 for the account's id and username (a failure → wallet), and lands on share1 with codes and the set's identifier. scanned() moves share1 to share2, and on share2 uploads share 3 (PUT /me/recovery-share with the key checked by start): success stores the returned account (setAccount, only for the same session) and gives done; RecoveryError key_in_use (409) gives changed and drops the words; any other failure gives save and keeps share 3. resplit() splits the same words again into a new set and shows person 1's new code. retry() runs start after wallet, the same upload after save, and returns to the intro after changed; it does nothing after mismatch. back() returns true after stepping share2 → share1 or share1 → intro (which drops the words and codes), and false on 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 /login card: the quiet link on its idle view, or the secondary control on a login problem.
  • Inputs: None.
  • Returns / side effects: Fill AppShell with align="center", ProfileChromeLeft with HomeWordmark, and the light LanguageSwitcher (the /login chrome), then RecoverScreen. Not behind OnboardingGate: 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 of useRecoveryFlow under one title, Recover your account (recover.title, the h1 of every view; sr-only over the camera).
  • Inputs: useRecoveryFlow() and the client-side router.
  • Returns / side effects: A Card surface={false} with one view, or, for scan, the camera layer of OldWordsInput. start: recover.intro, a primary Scan two codes (recover.scan) and a secondary Type my 12 words (recover.type). type: OldWordsInput mode="type". opening: a BusyLine with recover.opening, or recover.openingWait while waiting. blocked: LoginBlockedNotice; under closed a primary Try again (login.retry, resume) and a secondary Start over (recover.again), because the view outlives the page; outdated is the notice without Reload (reload={false}), since only the login card and the profile claim may reload the document. refused: p[role=alert] with recover.notFound, recover.alreadyDone (plus a primary Log in, login.submit, which drops the recovery and calls returnToView('/login', router)), recover.operator, shareCode.otherAccount, or recover.noWallet, then a secondary Start over (recover.again). retry: recover.unavailable or wallet.balanceError, a primary Try again (login.retry), and Start over. found: h2 recover.found, recover.restart after a restart, recover.foundBody, the alert of the last try (view.claimError, wallet.timeout, wallet.prfUnsupported, or wallet.balanceError), and a primary Create new passkey (recover.createPasskey), disabled with a spinner while busy. transfer: h2 recover.transferTitle, recover.transferBody, an ol of Account (recover.stepAccount), 21.gifts address (profile.giftsHeading), and Balance (wallet.balanceHeading), each with a Check image named recover.stepDone when done, the status line recover.transferWait while waiting, the alert recover.transferError or recover.balanceError, a primary Transfer (recover.transfer, disabled with a spinner while busy), and after generic a secondary Start over, after balance a secondary Move the balance later (recover.balanceLater). done: DoneStep with view.balanceMissing. The one top-left arrow (AppShellTopLeft with ProfileChromeLeft and HomeWordmark) first steps from the warning of DoneStep back to that step, otherwise runs back: 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 of RecoverScreen: 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.doneShares in font-medium text-app-fg, then recover.balanceMissing when a balance stayed, otherwise recover.doneDeleteOld, because moving a leftover balance can still need the old shares; a primary ButtonLink Secure my account (socialRecovery.secure) to /settings/social-recovery and a secondary Button Not now (recover.later). Not now calls onWarn, and warning replaces the step on the same page with h2 Continue without protection? (recover.laterTitle), recover.laterBody, a primary Secure my account, and a secondary ButtonLink Continue anyway (recover.laterContinue) to /welcome. RecoverScreen holds 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 /recover or 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 (scan or type), onWords(words, ownerAccountId), and optional expectedOwnerAccountId.
  • Returns / side effects: scan: a section named Scan two codes with data-port-fill that fills its positioned parent (the camera layer of the wallet Send view), holding QrScanner with Scan code {n} of 2 (recover.scanHint, hintVars) and the recover.cameraDenied / recover.cameraUnavailable alerts. Each code goes through parseShareCode. 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 white Button 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 with phraseFromShareCodes, and the words go to onWords with the owner they name. A text that is not a share code (shareCode.invalid), the same code twice (Slip39Error members, shareCode.same), codes of different setups or that do not combine (shareCode.otherSet), or a code of an account other than expectedOwnerAccountId (shareCode.otherAccount) stops the camera and shows its alert in white over the black layer with an overlay Try again that starts the camera again. type: a form with a multiline Field Your 12 words (no autocomplete, autocorrect, or spellcheck), the hint recover.wordsHint (its aria-describedby), and Continue (recover.wordsSubmit); the words are trimmed, lower-cased, and single-spaced, and anything but 12 valid BIP-39 words shows recover.wordsInvalid (aria-invalid) until the field changes; valid words go to onWords with owner null. Nothing is handed over after unmount.
  • Used by: RecoverScreen and RemainingBalanceScreen.

Function: useRecoveryFlow

  • Purpose: State and actions of /recover: the view of useRecoveryStore and the presses that drive the recovery flow.
  • Inputs: useRecoveryStore, the recovery-flow functions, and, in a Playwright build only (visualPin), the ?visual= pins recover-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, and recover-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 }. scan and type show those steps; onWords calls rememberOldWords; retry calls openAndBegin; resume calls resumeRecovery; createPasskey calls createNewPasskey; transfer calls transfer; balanceLater calls finishWithoutBalance; startOver calls resetRecovery. back() returns true after stepping from scan or type to start, otherwise false, so the arrow leaves. The recovery stays in memory when the page closes, also on blocked, so coming back resumes it; leaving the done step calls resetRecovery.
  • 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) is start, 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, or null; busy), transfer (done of account, address, signedIn, balance; busy; waiting; error: generic, balance, or null), or done (balanceMissing). Starts at start.
  • Used by: useRecoveryFlow and 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 (null disables the recovery), appHost, Date.now, a setTimeout pause, crypto.randomUUID, and navigator.credentials.create / get.
  • Used by: rememberOldWords and openPreviousWallet (their default deps).

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, and deps (host, sleep).
  • Returns / side effects: { connection, balanceSats } after connect(words, apiKey, host) and a synced getInfo({ ensureSynced: true }), both within WALLET_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 with wallet-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), createNewPasskey and transfer (the new wallet, and opening it again for a later address claim), and openPreviousWallet.

Function: rememberOldWords

  • Purpose: Starts a social recovery on /recover with 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, or null for typed words), and optional deps (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, from OldWordsInput).

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 (apiKey null) the view is refused noWallet and no wallet code loads. Otherwise opening; the old wallet's key is worked out offline (identityPubkey), the wallet connects with openWordsWallet (which also lets the SDK look up the address it holds), and a failure is retry wallet. Each begin signs a fresh lookup (signAddressLookup with the app host and the current second; a signing failure is retry wallet) and calls startPasskeyRecovery. While it answers unavailable the view is opening with waiting, the flow waits RECOVERY_SETTLE_WAIT_MS (31 s), and asks again, up to RECOVERY_BEGIN_TRIES (3) calls; then retry unavailable. not_found, done, and operator are refused; LoginsClosedError and AppOutdatedError are blocked; WrongAccountError is refused operator; any other failure is retry unavailable. An account other than the scanned codes' owner is refused otherAccount; otherwise the begin is kept and the view is found with 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 on retry (useRecoveryFlow), and resumeRecovery.

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 found is shown, idle, with an open old wallet and a begin.
  • Returns / side effects: found turns busy. The begin's creation options (creationOptionsFromJSON) get the PRF request (mergePrfExtension) and go to createCredential, timed as wallet.passkey with prompt: recovery. No credential, a dismissed or failed prompt is found error cancelled, a prompt that timed out timeout (classifyWebAuthnError), and no PRF output (obtainPrfFirst null under the begin's rp.id, also when the confirming get() differs from create()) prf. The 12 words come from mnemonicFromPrfFirst (never rememberSessionPhrase), the wallet opens with openWordsWallet, and its key (identityPubkey) and Spark address (receiveSparkAddress) are read; any failure there closes a half-open wallet and is found error wallet, 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 is transfer.
  • 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 transfer is 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) with signMessage; a failure or another key ends the press with generic. finishPasskeyRecovery stores the pending recovery; RecoveryError challenge (the account did not move) begins again at once, which on a new begin restarts the attempt (found with restart, the new wallet closed, every part of the attempt dropped); any other refusal ends the press (generic, or blocked / 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 as wallet.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, then startPasskeyAuthentication, getCredential limited to the new credential (wallet.passkey, prompt: recovery), and finishPasskeyAuthentication, without signalUnknownCredential. Success clears the tab phrase, starts rememberPhraseFromPrf with the new PRF bytes, starts relockHeldShares with 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), starts refreshOwnerAccount(session.token) without awaiting it, logs login and recovery_done, and marks the account, address, and sign-in done. RecoveryPendingError waits until RECOVERY_SETTLE_WAIT_MS after the claim settled and begins again; UnknownCredentialError begins again at once. A begin again that answers done signs in once more (an unknown passkey then means refused done); operator and not_found are refused; unavailable three times, a dismissed prompt, or another failure ends the press with generic. Balance: reads the old wallet's synced balance and sends all of it to the new Spark address (sendToSparkAddress, wallet.send with route: 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: stage send, method spark, flow recovery, the reason from sdkFailureReason, 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 to RECOVERY_SEND_TRIES (3) sends per press; any failure is balance. A synced read of 0 closes the old wallet, drops every word and connection, and shows done.
  • Used by: useRecoveryFlow (transfer).

Function: finishWithoutBalance

  • Purpose: Move the balance later after the balance error: the account has moved and is signed in, so the recovery ends without the balance.
  • Inputs: The recovery in progress; no-op unless transfer with error balance is shown and idle.
  • Returns / side effects: Closes the old wallet, shows done with balanceMissing, 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 the blocked view, which outlives the page, never leaves the member stuck.
  • Inputs: The recovery in progress; no-op without one, and unless blocked closed is 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 shows transfer with the attempt's done parts and the generic error (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 shows found for 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 start at 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), and RecoverScreen (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 AppShell with ProfileChromeLeft and SignedInChrome, OnboardingGate screen="profile" (like /settings), then RemainingBalanceScreen for that key.
  • Used by: Route /settings/previous-wallets/[sparkPubkey].

Function: RemainingBalanceScreen

  • Purpose: Body of the previous wallet's page: the steps of useRemainingBalance under the title Transfer remaining balance.
  • Inputs: sparkPubkey, the signed-in account (id for the codes), useRemainingBalance, useSpotRate (while a balance shows), useFiatPreference, and useNumberFormat.
  • Returns / side effects: null before the account and the list have loaded. Otherwise a Card surface={false} with h1 remaining.title (sr-only over the camera) and one step: loadError previousWallets.loadError with Try again; notFound the muted remaining.notFound with nothing to press (the top-left arrow leaves); start remaining.intro, Scan two codes, Type my 12 words; scan / type OldWordsInput (scan with expectedOwnerAccountId = the account); opening BusyLine recover.opening; mismatch remaining.mismatch and walletError wallet.balanceError, each with Try again; balance / sending the overline remaining.balance with ₿ 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 0 remaining.emptyBody, the removal, and Done; error the balance, remaining.error, and Try again; done remaining.done (role="status"), the removal, and Done. The removal is a secondary Remove previous wallet (previousWallets.remove), or the open InlineConfirm (previousWallets.removeConfirm, icon buttons previousWallets.removeYes / removeNo, busy spinner, previousWallets.removeError). The one top-left arrow runs back. 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 from useAuthStore, and the client-side router. In a Playwright build only (visualPin), ?visual=prev-opening, prev-mismatch, prev-balance, prev-empty, prev-sending, prev-error, and prev-done open 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 }. Reads fetchPreviousWallets once per session and reload: the key not listed is notFound, a failure loadError, otherwise start. onWords first starts relockHeldShares with the entered words and, once the running phrase derivations have settled (settlePhraseDerivations), the words of the open wallet in tab memory (or null when there are none, which moves nothing; not awaited), then opens the wallet (openPreviousWallet): mismatch, walletError (the words stay for retryOpen, which opens again; after mismatch it returns to start and drops them), or balance with the synced balance. transfer (on balance or error) runs transferRemainingBalance with the session: done (balance 0) or error. removable is true only with a synced read of 0 (balance at 0, or done); then askRemove opens the confirm, cancelRemove closes it, and confirmRemove calls deletePreviousWallet (busy meanwhile; a wallet that is already removed counts as removed, so Remove after a lost answer still ends), then closePreviousWallet and returnToView('/security', router), or error. leave (Done) calls returnToView('/security', router). back() steps from scan or type to start, otherwise returns false. Unmount drops the words and calls closePreviousWallet; 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 optional deps (loadSdk, apiKey, host, sleep, randomUUID; defaultRecoveryDeps() by default).
  • Returns / side effects: wallet without 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 not expectedPubkey, or that are no phrase, are mismatch before anything connects. Otherwise a wallet still open from an earlier call is closed, the wallet opens with openWordsWallet (wallet on 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 answers wallet, and nothing connects; a wallet that opens after the page closed it is closed and answers wallet.
  • 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 by openPreviousWallet.
  • Returns / side effects: error without 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.send with route: spark) and reads again, with a new idempotency key after each send that went out, up to RECOVERY_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: stage send, method spark, flow previous_wallet, the reason from sdkFailureReason, the amount, under session). Answers sent only once a synced read gives 0; any failure, or funds still arriving after the last send, answers error.
  • 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 openPreviousWallet is closed once it opens.
  • Used by: useRemainingBalance (unmount, and after a removal) and openPreviousWallet (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 spinning Loader2 and the label.
  • Used by: SocialRecoveryScreen (checking, saving), RecoverScreen (opening), and RemainingBalanceScreen (opening).

Function: GrantsPage

  • Purpose: Next.js page for /grants. Fill AppShell with ProfileChromeLeft, SignedInChrome, and OnboardingGate screen="profile" around GrantsScreen.
  • 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 /me without 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 merges walletViewerPublicKey and legacy grantPayoutToday into the current account. When the stored account has no funding object and the answer has one, the answer's whole funding object is taken. When both have one, the stored object and its locally writable fields stay, and only funding.payoutToday, funding.shopPaymentDue, funding.shopPaymentSats, and funding.shopPaymentRequiredSats are 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 answer funding leaves 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, and FundingWithdrawControl after a successful withdrawal.

Function: discardOwnerRefreshes

  • Purpose: Drops every refreshOwnerAccount round still in flight after a caller stored a newer owner payout itself, so a GET /me started earlier (for example when /grants opened) cannot copy its older funding.payoutToday, funding.shopPaymentDue, funding.shopPaymentSats, and funding.shopPaymentRequiredSats onto 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 own refreshOwnerAccount) 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 from account.funding.payoutToday whenever funding is an object (an explicit null stays unavailable), or from account.grantPayoutToday only when funding is null or absent. Paid and due states explain the result; a blocked state names only its one missing step. A shop_payment block with both funding.shopPaymentSats and funding.shopPaymentRequiredSats non-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 is formatBitcoin, a middle dot, and formatFiatDisplay of satsToFiatAmount at the current spot (useSpotRate, enabled only while those amounts show) in the useFiatPreference currency; bitcoin stands alone while no spot is available. With either sum null or absent, or on the grantPayoutToday fallback, 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 Goals ButtonLink (funding.goals.link) goes to /grants/goals, under the grant card and above the staff queue. A missing account shows no link. When canEditDailyPayoutRoster is true (at least initiator: initiator and founder), three secondary large ButtonLinks, 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. When roleAtLeast(role, 'moderator'), loads open applications. A count above zero is a secondary large ButtonLink to /grants/applications labeled 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. Renders null without a session.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations; grouping via useNumberFormat; currency via useFiatPreference; current spot via useSpotRate. Payout fixes reuse /trust-chain, /grants/apply, /wallet, /settings/social-recovery, /shops, and /welcome plus requestForumCompose.
  • Returns / side effects: React element or null without a session. The payout sentence itself is the link when that member can act: admission links only for none/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. Fetches GET /funding/applications only when roleAtLeast(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/goals loads GET /funding/goal. Renders GrantPlacesPanel under the payout group for every signed-in account, with the owner's grant status (none when missing) as its reloadKey, so the panel loads again when that status changes on this page.
  • Used by: GrantsPage.

Function: GrantGoalsPage

  • Purpose: Next.js page for /grants/goals. Fill AppShell with ProfileChromeLeft, SignedInChrome, and OnboardingGate screen="profile" around GrantGoalsScreen.
  • 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, ShopActivityChart for 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. Renders null without a session and does not fetch then.
  • Inputs: Session from useAuthStore; catalog and locale via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/goal through fetchGrantContinuation only when a session exists. Does not call fetchShopActivity.
  • Used by: GrantGoalsPage.

Function: DailyPaymentCommentPage

  • Purpose: Next.js page for /grants/payments/comment. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around DailyPaymentCommentScreen. Amounts are a separate page. Roster HTTP lives under /funding/daily-roster because Next.js forbids a route.ts beside 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 fetchDailyRoster and 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 shows funding.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 plus funding.daily.forbidden and does not fetch. Renders null without a session. The page chrome owns the back; this screen renders no back control. A failed load shows funding.daily.error and Try again.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/daily-roster only when canEditDailyPayoutRoster is true. The comment save goes to POST /funding/daily-roster/comment. A save failure shows a funding.daily.* catalog sentence and leaves the field open.
  • Used by: DailyPaymentCommentPage.

Function: DailyPaymentAmountsPage

  • Purpose: Next.js page for /grants/payments/amounts. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around DailyPaymentAmountsScreen. The comment is a separate page. Roster HTTP lives under /funding/daily-roster because Next.js forbids a route.ts beside 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 fetchDailyRoster and may turn payments on or off and add, update, or delete a recipient. The loaded editor shows funding.daily.defaultNote with {amount} from roster.defaultAmountUsd via formatUsdDisplay. 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.edit plus that label), and the trash share one line. The pencil opens a Field; the check saves and the X cancels. Amounts are the stored USD figure (Field, not AmountEntry). The total uses formatUsdDisplay and 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 plus funding.daily.forbidden and does not fetch. Renders null without a session. The page chrome owns the back; this screen renders no back control. A failed load shows funding.daily.error and Try again.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations; grouping via useNumberFormat.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/daily-roster only when canEditDailyPayoutRoster is true. Saves go to the payments, add, update, and delete daily-roster POSTs. A save failure shows a funding.daily.* catalog sentence.
  • Used by: DailyPaymentAmountsPage.

Function: DailyPaymentModeratorsPage

  • Purpose: Next.js page for /grants/payments/moderators. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around DailyPaymentModeratorsScreen. The comment and recipient amounts are separate pages. Roster HTTP lives under /funding/daily-roster because Next.js forbids a route.ts beside 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 fetchDailyRoster and may turn moderator payments on or off and add, update, or delete a moderator. There is no funding.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.edit plus that label), and the trash share one line. The pencil opens a Field; the check saves and the X cancels. Amounts are the stored USD figure (Field, not AmountEntry). The total sums moderators only, via formatUsdDisplay and the visitor grouping style. The list label is funding.daily.moderators. An empty list shows funding.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 plus funding.daily.forbidden and does not fetch. Renders null without a session. The page chrome owns the back; this screen renders no back control. A failed load shows funding.daily.error and Try again.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations; grouping via useNumberFormat.
  • Returns / side effects: React element or null without a session. Fetches GET /funding/daily-roster only when canEditDailyPayoutRoster is true. Saves go to the moderator payments, add, update, and delete POSTs. A save failure shows a funding.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. Loads fetchGrantPlaces without a session. Loading shows the shared Loading…; failure shows Could not load the grant places. Please try again. with Try again. data-grant-places is loading, error, or ready so screenshot tests wait for the load.
  • Inputs: Optional reloadKey (on /grants the 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/places per mount, per retry, and per new reloadKey; 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 one h1 21 gifts grant at the app page ramp, with no hairline above it. basis sees not-verified copy and how in-person verification works (no apply). Verified and above see funding status from account.funding (missing or null treated as none): none/rejected show 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} when admittedAt is a number). Under those three status texts, FundingWithdrawControl offers the quiet way out: Withdraw my application for pending, Leave the grant for trial and admitted. none and rejected do not show it.
  • Inputs: Session and account from useAuthStore; catalog via useTranslations.
  • Returns / side effects: React element or null without a session or account. none/rejected offer 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 for pending, Leave the grant for trial and admitted. Pressing it opens InlineConfirm in 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, or admitted); session and account from useAuthStore.
  • 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 replaces account.funding with the answer (status none), so FundingStatusCard shows the apply state, GrantsScreen reloads GrantPlacesPanel, and SignedInChrome and every other reader of funding.status follow without a page load. The answer carries no payoutToday, so it first drops older owner refreshes (discardOwnerRefreshes, so the GET /me started when /grants opened cannot copy the old payout back) and then calls refreshOwnerAccount, and the Today's payout line of GrantsScreen takes the new reason from GET /me without 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 /me answers 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. Fill AppShell with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="profile" around FundingApplyScreen. /profile/apply redirects to this path.
  • Inputs: None.
  • Returns / side effects: FundingApplyScreen inside fill AppShell: the apply walk for a verified account with status none or rejected, 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 null without 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 none or rejected sees 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 none or rejected sees 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 null when all three are present. Used by the apply walk. Every verified account with status none or rejected sees 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/group is the group page, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left (the only back control: the arrow returns to the previous in-app view in this tab, or /welcome when this tab has none; the wordmark is not that control), SignedInChrome top-right, and OnboardingGate screen="welcome" around ModeratorGroupScreen. Group HTTP lives under /conversations/moderator-group (no route.ts beside 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')) fetch fetchModeratorGroup then the newest 20-message page with fetchConversation(session, group.id) and reuse InboxScreen as the open thread (showFilter false; showAmount false; showAttach true; no in-card back; row name replaced by the catalog moderate.groupLabel so the heading is always Moderators chat group). An IntersectionObserver on InboxScreen's nearStartRef (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 set nextCursor and 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) via prepareForumPhoto; photo-only send allowed. Send is disabled while a pick is still preparing (posting || preparing). Thread stills load with fetchConversationMessagePhoto. Losing staff while mounted bumps pickGeneration, 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 calls useSpotRate() and passes rateDay to InboxScreen. 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 plus moderate.groupForbidden and do not fetch. Renders null without a session. The top-left arrow returns to the previous in-app view in this tab, or /welcome when 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 via useTranslations.
  • Returns / side effects: React element or null without a session. Fetches GET /conversations/moderator-group then GET /conversations/:id?limit=20 (optional cursor for 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-group with Bearer and parse { conversation } via conversationResponseSchema. Returns the singleton closed staff-room row (kind moderator_group).
  • Inputs: Session token.
  • Returns / side effects: Conversation row, or throws visitor copy.
  • Used by: ModeratorGroupScreen, InboxLoader (/messages unlisted ?c= guard for a moderator), useUnreadCount (staff unread), refreshUnreadAppBadge (when moderationUnreadOverride is omitted and roleAtLeast(account?.role, 'moderator')), and NotificationsLoader (remaining badge after mark-all-read, staff only).

Function: listHiddenMessages

  • Purpose: GET /forum/messages/hidden with Bearer and parse hiddenListSchema.messages. HTTP 401/403 throw Failed to list hidden notes: status; other failures visitor copy Could 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-card HandbookImageViewer. English card text comes from screens.md. German, Spanish, and Filipino come from the screen-card locale file for the request locale.
  • Inputs: Request locale from getRequestLocale (cookie locale, otherwise Accept-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 prefix functions).
  • 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 compact HandbookFigure cards. 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 required description).
  • Returns / side effects: React element or null when 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 null when empty. No network.
  • Used by: HandbookImageViewer.

Function: HandbookSectionHeading

  • Purpose: Chapter (h2) or screen (h3) permalink heading with HandbookCopyLink.
  • 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 is screenChapter (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 (1 or -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] become accountId.
  • 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 opens HandbookLightbox unless onOpen is set, and a written description. Scrolls into view when location.hash matches #id.
  • Inputs: id, label, description, src, alt, optional onOpen (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> with id. Hash scroll on mount/hashchange. No network.
  • Used by: HandbookImageViewer and HandbookMarkdown (image-only paragraphs).

Function: HandbookLightbox

  • Purpose: Full-size handbook image overlay on marketing tokens (bg-ink, border-paper/10, bg-app-overlay scrim, ghost IconButton + X). Close via X, backdrop click, or Escape. Optional previous/next chevrons when onPrevious/onNext are set: ChevronLeft shows the previous image (handbook.previousImage) and ChevronRight the 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, optional onPrevious, optional onNext.
  • Returns / side effects: role="dialog" overlay when open, otherwise null. 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.md into 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, or fil), 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, or fil has 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-light when present, else the first listed, else null).
  • 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 via basis-full w-full and renders InlineConfirm. Idle/confirm/error copy is forum.delete* for posts and forum.deleteReply* for replies. Calls deleteMessage on explicit confirmation, then onDeleted. Error keeps the post or reply and permits retry. When deleteMessage throws OPEN_CREDIT_DELETE_ERROR (a credit post that has received sats and is not fully repaid), the alert is forum.deleteOpenCreditError instead of the retry error; Cancel clears it.
  • Used by: ForumBoard on 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), optional description (a muted line under the question, linked to the group with aria-describedby), confirmLabel, cancelLabel, onConfirm, onCancel, optional busy, and optional error.
  • Returns / side effects: A role="group" with the question, an optional alert, a check (a spinner while busy), and an X. Both actions are disabled while busy. 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), and FundingWithdrawControl (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 exactly OPEN_CREDIT_DELETE_ERROR (An open credit cannot be deleted) throws an Error with that message, so the caller can name the reason. Other statuses throw Message deletion failed; network errors propagate. Hide/omit semantics: the API keeps the row with deleted_at and 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, or null to clear).
  • Returns / side effects: PATCH /forum/messages/:id/place with JSON { place }. Resolves to the public message JSON (place omitted when cleared). A 400 preserves its API reason for adjacent form feedback; other failures throw Could 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/photos with JSON { photos }. A blank takenAt is omitted. Resolves to the public message JSON. A 400 preserves its API reason for adjacent form feedback; other failures throw Could 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/text with JSON { text }. Resolves to the public message JSON. A 400 preserves its API reason for adjacent form feedback; other failures throw Could 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 the edits array (text, place, or shop account, with actor id, name, and role). Throws Could not load edit history on a non-2xx status.
  • Used by: ShopNoteEditControl when 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, or null to clear).
  • Returns / side effects: PATCH /forum/messages/:id/shop-account with JSON { username }. Resolves to the public message JSON (shopAccount omitted when cleared). A 400 preserves its API reason. A 404 throws No account with that username only when that is the API reason; another 404 and other failures throw Could not save account.
  • Used by: ShopAccountControl.

Function: proxyForumMessageGet

  • Purpose: Forward an authenticated GET /messages/:id for the app path /forum/messages/:id. Staff sessions receive soft-hidden rows.
  • Inputs: Incoming Request (Bearer) and messageId.
  • Returns / side effects: Proxied GET /messages/:id with encoded id and authorization.
  • Used by: App Router GET on /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 DELETE on /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 omits place.
  • Used by: App Router PATCH on /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 PATCH on /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 PATCH on /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 GET on /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 omits shopAccount.
  • Used by: App Router PATCH on /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 / fil stopwords (with extra weight for German umlauts and Spanish ñ¿¡).
  • Inputs: Raw note text string.
  • Returns / side effects: en/de/es/fil when one UI locale wins, other when the text is long enough but not those four, or null when 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 text and the active UI locale.
  • Returns / side effects: false when detection is null or equals locale; true for other or a different UI locale. No I/O.
  • Used by: NoteTranslate.

Function: fetchTranslateAvailable

  • Purpose: Query same-origin GET /translate and cache the shared promise. Failures and non-{ available: true } bodies resolve to false.
  • Inputs: None.
  • Returns / side effects: Promise<boolean>. One in-flight GET is reused for the module lifetime. Does not throw.
  • Used by: NoteTranslate on 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 UI target locale, and optional session Bearer. A non-empty string is sent as Authorization: Bearer … (hidden staff permalink). Omitted, null, or empty leaves the request unsigned so public notes still work.
  • Returns / side effects: The translatedText string. Throws when the route is non-2xx or translatedText is missing, not a string, or empty after trim.
  • Used by: NoteTranslate on 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 } → api POST /messages/:id/translate.
  • Inputs: Incoming Request with 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 api POST /conversations/:id/messages/:messageId/translate.
  • Inputs: Incoming Request, conversationId, and messageId from the route segments.
  • Returns / side effects: { translatedText, cached } or 400 when the body is not JSON or target is 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, UI target locale, and the bearer session. An empty session omits Authorization.
  • Returns / side effects: { translatedText, cached }. Throws when the route is non-2xx or translatedText is missing, not a string, or blank.
  • Used by: NoteTranslate when source.kind is conversation.

Function: NoteTranslate

  • Purpose: Control-only client: Translate, Show original, and Show translation are the same Languages IconButton (aria-label forum.translate, forum.translateShowOriginal, or forum.translateShowTranslation; no visible label). The error and the spinner stay. Does not render ForumNoteText or the translated body — exclusive original XOR translation lives in TranslatableNoteBody. Offers the control when the note language differs from the active UI locale and GET /translate reports available. Identity is source + messageId + text + locale (not text + locale alone). Translate sits in the card footer icon row with react / pay / copy when placement is row (ForumBoard supplies a controlSlotId to TranslatableNoteBody, 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) and text (raw prose body). Optional source (default { kind: 'message' }, or { kind: 'conversation', conversationId }). Optional tone (default | onButton, for bg-app-btn bubbles). Optional placement (block under the body, default; row uses display: contents so the icon sits in a parent footer flex row). Parent-owned showingTranslation (true while the translated body is on screen). onTranslated after a successful POST. Optional onTranslateRequest, called synchronously when Translate is clicked, before the request, and not from Show original / Show translation. onToggleShowing for Show original / Show translation. No plain, bodyClassName, or onShowingTranslation.
  • Returns / side effects: The control, or null when the text is blank, translation is unavailable, or shouldOfferNoteTranslate is false. Calls fetchTranslateAvailable on mount and, on click, translateNote for a forum message or translateConversationMessage for a conversation message. A change of source, 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. onButton paints the control with text-app-btn-fg. Does not mount the note body. Uses useActiveSession: 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 useEffect after 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 is source + messageId + text + locale. Holds translatedText and showingTranslation; a successful POST sets both so the original unmounts in that commit.
  • Inputs: Required messageId (stored forum or conversation message id) and text. Optional source (default forum message, or { kind: 'conversation', conversationId }). Optional plain. Optional truncate (default true; applies only to the original body — ForumNoteText vs LinkedText). A visible translation is always the full text via LinkedText (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. Optional className (default whitespace-pre-wrap text-sm text-app-fg; text-app-btn-fg selects NoteTranslate tone="onButton"). Optional formatTranslated (applied only to the visible translation, not the original; not part of the identity key). Optional controlSlotId (when set, portals NoteTranslate with placement="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 null when text is empty. Mounts NoteTranslate under the body, or portals it into controlSlotId when 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, including via === 'nostr'), PublicMessageLoader, ForumQuotedBody, QuotedForumNote (any caption when translate is true; plain only when via === 'nostr'), AboutMeSection, HiddenNotesScreen, FundingApplicationDetailScreen, and FundingApplyScreen (apply walk for every verified account with status none or rejected).

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, gift day or null, fiat code.
  • 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 satsToFiatAmount on the same rate. A positive amount that rounds to 0 becomes 1 sat.
  • Inputs: Fiat amount, gift day or null, fiat code.
  • 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 is invalid, not no-rate, so a unit toggle can round-trip. A positive fiat amount whose rate for that currency is missing, or zero is no-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 is invalid.
  • Inputs: unit (btc or fiat), raw draft, gift day or null, fiat code.
  • 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, typing unit, gift day or null, fiat code.
  • Returns / side effects: Whole sats, empty, or invalid. 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.00 stay fiat. 21, 1000, and 0 stay the reported bitcoin unit.
  • Inputs: shown (the unit the field last reported), accountUnit (the signed-in preference; missing means bitcoin), raw draft.
  • Returns / side effects: btc or fiat. 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, typing unit, gift day or null, fiat code.
  • 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, raw draft, gift day or null, fiat code, and whether the rate request has settled.
  • Returns / side effects: quiet, no-rate, invalid, or null when 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, raw draft, gift day or null, fiat code, and whether the rate request has settled.
  • Returns / side effects: quiet, no-rate, invalid, or null when 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. loading stays 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, or null; 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. is 12 and 1,50 is 1.50. The spot of the sats is not this figure.
  • Inputs: unit (btc or fiat), raw draft, fiat code.
  • Returns / side effects: { code, amount } or null. No I/O.
  • Used by: attachTypedFigure, WalletSend, PayLinkScreen.

Function: attachTypedFigure

  • Purpose: Copies value and, when the draft is a typed fiat amount, adds that figure from typedFiatFigure. A bitcoin field, or a draft that is not a fiat amount, is returned unchanged.
  • Inputs: value (an object), unit (btc or fiat), raw draft, fiat code.
  • 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 12 plus 1.00 is 13.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: left and right decimal 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-unit with JSON { unit } (btc or fiat) and the bearer session.
  • Inputs: Session token and unit.
  • Returns / side effects: Parsed owner Account. Throws when the response is not ok or fails accountSchema.
  • Used by: saveAmountUnit.

Function: setHeartSats

  • Purpose: POST /me/heart-sats with 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, including heartSats. Throws 'Could not save the heart amount.' on a non-ok response or the schema error when the body fails accountSchema.
  • 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-unit through setAmountUnit.
  • Inputs: Session token, the store account before the choice, the chosen unit (btc or fiat), and an optional onRollback(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 onRollback receives 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 onlyIfUnset boolean.
  • Returns / side effects: Sends JSON { locale, onlyIfUnset }, returns the parsed owner Account, 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, and onlyIfUnset boolean.
  • Returns / side effects: Sends JSON { fiat, onlyIfUnset }, returns the parsed owner Account, and throws on an invalid or failed response.
  • Used by: FiatPreferenceSwitcher and AccountPreferenceSync.

Function: proxyMeAmountUnitPost

  • Purpose: Same-origin Bearer proxy of api POST /me/amount-unit with JSON { unit }.
  • Inputs: Incoming Request with Bearer session and JSON { unit }.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/amount-unit.

Function: proxyMeHeartSatsPost

  • Purpose: Same-origin Bearer proxy of api POST /me/heart-sats with JSON { sats }.
  • Inputs: Incoming Request with Bearer session and a whole-sat JSON body.
  • Returns / side effects: Upstream Response via proxyApiRequest.
  • Used by: Route POST /me/heart-sats.

Function: proxyMeLocalePost

  • Purpose: Same-origin Bearer proxy of api POST /me/locale.
  • Inputs: Incoming Request with JSON { locale, onlyIfUnset }.
  • Returns / side effects: Returns the owner-account upstream response; onlyIfUnset=true preserves a stored locale.
  • Used by: Route POST /me/locale.

Function: proxyMeFiatPost

  • Purpose: Same-origin Bearer proxy of api POST /me/fiat.
  • Inputs: Incoming Request with JSON { fiat, onlyIfUnset }.
  • Returns / side effects: Returns the owner-account upstream response; onlyIfUnset=true preserves 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 is HabitTrackerTopRight. OnboardingGate screen="welcome" allowGuest. HTML /habit-tracker is the page, not a GET proxy. Fill AppShell (align="center") with ProfileChromeLeft top-left around MemberHabits.
  • 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-tracker header. 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), and SignedInChrome with one. The page stays a server component.
  • Inputs: None. Reads the auth store session and lockedSession.
  • Returns / side effects: The top-right control. No request.
  • Used by: HabitTrackerPage.

Function: MemberHabits

  • Purpose: Loads GET /habits and writes POST /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 neutral SegmentedControl and 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 in HabitComments. Comment and delete use SundayWritingGate and send Time-Zone. Add sends Time-Zone and 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, sends Time-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 with code: 'cannot_receive' (CannotReceiveError from postMemberHabit) shows the author-wallet error in the pay sheet. A reload that marks the open gift's comment canReceive: false closes the sheet; an invoice request still waiting is discarded and does not come back when a later reload says the author can receive again, sends Time-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, and founder), also inside that gate, and sends Time-Zone. Send Bitcoin on someone else's comment uses ForumPaySheet inside the zap gate and sends Time-Zone. A comment with canReceive: false shows 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; MemberHabits posts comment, deleteComment, and invoice. The gift on a comment is a ForumPaySheet with the commenter as recipient, inside a Collapse with holdMs PAY_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, or null when signed out. A blank string sends no Authorization header.
  • 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 device Time-Zone header.
  • Returns / side effects: The JSON body when the response is OK. Throws CannotReceiveError when the body carries code: 'cannot_receive'; otherwise throws the api error string 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 null for 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 null when 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, and bg-home-card tokens. A shop is listed only when its tech provider is exactly 21.gifts. Country, name, blockchain, asset, and activity are FilterMenu, and each is shown only when its options split the unfiltered 21.gifts rows. Map | Table is SegmentedControl tone="neutral". Country labels use countryDisplayName. 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. Below sm, only Name, Location, and Activity columns are visible; when Shop and Country columns exist, their values are stacked under the name. From sm, 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's scrollHeight plus 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 ArrowRight shares 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. Below sm, the closed pill shows the label above the selected value, with the chevron centered on the right, at least 44px height, and rounded-2xl corners. From sm, it keeps one line, 44px height, rounded-full corners, 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 /, and WalletUsageDashboard on /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 Scrollport when 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-Zone header when the browser can resolve one.
  • Returns / side effects: Returns validated { sundayRest, loans, lenderWaiting }. Each loan includes closedAt, maxSats, and maxAmount when 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, and next.sats are valid null values while their stored fiat amounts stay available. Each loan's due.waitingShares counts 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 (sats null 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 throws Could not load your loans.
  • Used by: useMyLoans for 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-Zone header and no body.
  • Returns / side effects: Returns validated { bills, waiting }; each bill defaults a missing sparkInvoice to null. Wallet codes become typed wallet errors, matching 409 bodies become MissingRequirementsError, and other refusals use the existing payment error mapping.
  • Used by: useLoanRepay once 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.prepayWaiting preserves these rows from the prepay response for the muted waiting display.
  • Used by: useLoanRepay and LoanPayMore.

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 becomes MissingRequirementsError; other refusals are typed LoanRepaymentError values.
  • 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 Error named LoanRepaymentError with readonly code, status, and maximum fields; amount/share maximum refusals preserve both limits.
  • Used by: closeLoan, prepayLoan, and useLoanRepay.actionError mapping.

Function: prepayLoan

  • Purpose: Requests recipient bills for a freely chosen repayment amount, including future shares, through POST /messages/:id/repayment with 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. amountSats is 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_high and too_many_shares carry maxSats and maxAmount, wallet and missing-requirement refusals keep their established typed errors, and 429/503 remain distinguishable.
  • Used by: useLoanRepay.prepay before the shared wallet preparation/send path.

Function: proxyMeLoansGet

  • Purpose: Same-origin proxy helper for api GET /me/loans.
  • Inputs: Incoming Request with a Bearer session.
  • Returns / side effects: Returns the upstream Response through proxyApiRequest.
  • Used by: Route GET /me/loans.

Function: proxyMessagesRepaymentDuePost

  • Purpose: Same-origin proxy helper for api POST /messages/:id/repayment/due.
  • Inputs: Incoming Request with 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 Request with 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 are bigint sats 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: checkLoanAmount and 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's goalCurrency, and the stored next amount in 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 creditSmallestUnits reads 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) and LoanRepayScreen (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 reads maxSats, while fiat requires a non-null maxSats exchange-rate signal and reads maxAmount as cents.
  • Returns / side effects: Returns bigint sats/cents, or null when maxSats is unavailable, the fiat maxAmount is unavailable, or that amount is malformed. It is pure.
  • Used by: checkLoanAmount for 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 MyLoan currency/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 maxSats text for BTC, the api's unchanged maxAmount for fiat only while maxSats is 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 fundedAt is null and closedAt is null or omitted; a manually closed but unfunded loan remains repayable and is not collecting. It is pure.
  • Used by: LoansCard, LoanRepayScreen, ForumBoard, LoanPayMore, and useLoanRepay.

Function: summarizeLoans

  • Purpose: Combines all loans into the totals and state needed by the loans card, Menu row, and repayment screen.
  • Inputs: A validated MyLoans body 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 summed next.sats and 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 has next.sats: null, while its defined amount still sums the stored next.amount strings 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 own ForumGoalBar. It is pure and performs no I/O.
  • Used by: LoansCard, MenuAccountHeader, and LoanRepayScreen.

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 sats and fiat amount plus optional paidSats and paidAmount.
  • Returns / side effects: Returns paid sats as a bigint only 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. The hasAmount flag 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, and LoanRepayScreen.

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, optional paidSats, and optional authoritative dueSats.
  • Returns / side effects: Returns dueSats when the api provides it and the partial satoshi relationship is valid; for an older api body, returns sats - paidSats (with missing paidSats treated as zero), or null when sats is unknown or less than paidSats. It is pure and performs no I/O.
  • Used by: dueShares and CreditLedger.

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 api waiting; without it, the giver's canReceive is false), remaining dueSats before the original sats, and for matching fiat currencies the remaining amount - paidAmount in integer cents. Missing paidAmount means zero cents only when paidSats is null or zero; positive paidSats without its stored fiat amount, or any supplied malformed or overpaid paidAmount, makes the remaining amount null so callers fall back to bitcoin/current spot. A foreign-currency ledger row also keeps its remaining sats and has amount: null, so that figure never reaches the list, a send-now link, or shareAmounts/sentAmounts. It is pure and performs no I/O.
  • Used by: LoanRepayScreen to 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.00 for 3000.
  • Inputs: A non-negative bigint of cents.
  • Returns / side effects: The string. It is pure and performs no I/O.
  • Used by: definedDueLabel and LoanRepayScreen (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 (payable reads due.payableAmount, waiting reads due.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 to definedFiatAmounts. 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), and MenuAccountHeader (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, or PHP, 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 that creditSmallestUnits cannot read. It is pure and performs no I/O.
  • Used by: definedDueLabel, definedFiatAmounts, and LoanRepayScreen (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), and useLoanRepay exposes the per-currency inputs as sentAmounts.

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: LoanRepayScreen for the send-now balance limit.

Function: useMyLoans

  • Purpose: Keeps one shared, session-keyed GET /me/loans body 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 } through useSyncExternalStore (server snapshot null). The first mounted consumer reads only while that session has no loaded body; later consumers reuse it. Every explicit reload performs 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, and LoanRepayScreen.

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 onlyShares keys 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 /due or a free-amount /repayment request 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 reload function from useMyLoans; pay receives current loans plus optional share keys and stored amounts, prepay receives one loan and a validated amount string, and closeCollecting receives one still-collecting loan. prepay substitutes prepayLoan only for bill acquisition and then enters the same baseline, prepare, balance, send, settlement, and reload path as pay.
  • Returns / side effects: Returns wallet phase and balance, activeAction (due, prepay, or close plus the per-loan messageId), sent amounts/names, prepayWaiting plus its prepayMessageId, prepayAllWaiting (true only after a free-amount prepay whose response had no bills (every share waiting) returned to idle; LoanPayMore clears 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 when activeAction.kind is due; each LoanPayMore consumes them only when the prepay/close message id matches its loan. The waiting recipients and message id come from the latest free-payment request so LoanRepayScreen passes them only to that loan's LoanPayMore. actionError includes that same messageId, typed close/prepay codes, and the api's maxSats/maxAmount for amount_too_high or too_many_shares; an untyped close or failed post-close reload becomes a scoped request_failed action error. Closing posts once and reloads without touching the wallet. Each bill is prepared Spark first with the Lightning fallback of payInvoiceSparkFirst. Free repayment validates amountSats against 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 fresh repaidSats baseline, 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, as amount_mismatch, and a refused Spark invoice before its Lightning fallback) is reported with reportPaymentFailure under the flow repay; 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, either welcome or wallet; reads useMyLoans, the preferred fiat and number format, and the current spot rate.
  • Returns / side effects: Returns null while loans are unavailable or empty. Otherwise shows funding totals, then a ForumGoalBar for each loan with exactly that loan's goalCurrency, goalAmount, goal snapshots, collected snapshots, and rateDay. 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: WelcomeScreen and WalletScreenView.

Function: LenderWaitingCard

  • Purpose: Card on the welcome screen for a lender who is owed repayments but cannot receive them yet (no verified wallet), from lenderWaiting of GET /me/loans.
  • Inputs: No props; reads useMyLoans, the preferred fiat and number format, and the current spot rate.
  • Returns / side effects: Returns null while loans are unavailable, when the body has no lenderWaiting, or when lenderWaiting.shares is 0. Otherwise a neutral region whose 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 when sats is not null (nothing when it is null), and the labeled ButtonLink Open 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 after LoansCard.

Function: LoanRepayScreen

  • Purpose: Renders the all-loans repayment body: the unchanged due flow first, then per-loan progress and LoanPayMore free 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 activeAction keeps 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 dueSats before the original sats; its stored fiat due amount is amount - paidAmount in 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 reuses WalletOwnAddress with 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 marks waiting is 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 whose currency differs from the loan's goalCurrency keeps 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, or shareAmounts/sentAmounts. The per-loan Repaid line of a fiat-defined loan uses definedFiatSum over fully paid rows plus the positive paidSats/paidAmount of partial due or scheduled rows only when the ledger currency matches the loan and their paid-satoshi sum equals repaidSats; then it adds the bitcoin from repaidSats (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. When totalSats is 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 use definedFiatAmounts over 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 from useLoanRepay().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's behindDays as it is.
  • Correctness details: A positive partial paidSats with missing paidAmount has no derived remaining fiat and falls back to bitcoin/current spot. Free-payment waiting rows use only prepayWaiting from the matching prepayMessageId; they never repeat under another loan or use another loan's currency.
  • Used by: LoanRepayPage at /loans/repay.

Function: LoanPayMore

  • Purpose: Per-loan free repayment form using the shared AmountEntry in 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, shared phase, activeAction, message-scoped actionError, errorKey, prepayWaiting, prepayAllWaiting, sundayRest, current rateDay, flags for local wallet/shortfall status, wallet balance / shortfall / top-up state, username and preferred-fiat sats formatter, plus the open-top-up, onPay and onCloseCollecting callbacks from useLoanRepay.
  • 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 missing maxSats reports the unavailable rate; when maxSats exists but maxAmount is absent, zero, or malformed it instead reports that the repayment maximum is unavailable. A BTC loan with a missing or zero maxSats also 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 matching activeAction.messageId can render shared prepay/close progress, failure, unconfirmed state, waiting rows, or shortfall, and actionError.messageId must 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 via prepayAllWaiting clears 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: LoanRepayScreen once 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 AppShell with WalletChromeLeft, SignedInChrome, and OnboardingGate screen="wallet" around LoanRepayScreen. 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, optional copy (default false), and optional hint catalog key (default wallet.payAddFunds, the own top-up sentence); reads the browser hostname and localized labels.
  • Returns / side effects: Returns null until the host is known or when no address can be formed. Otherwise shows the hint sentence, truncated monospaced address, and profile-style Open CryptoPay QR on every device; copy also adds an icon-only IconButton whose 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: LoanRepayScreen after Top up your wallet, and FondDeposit (Instant payment, with fond.depositLightningHint).

Function: fetchFondPayouts

  • Purpose: GET /fond/payouts (same-origin Bearer proxy of api GET /fond/payouts) and parse fondPayoutListSchema. Lists today's open Fond payout rows in the api's order: { id, kind, status, utcDay, paymentHash } per row, with kind daily | moderator | welcome and status owed | issuing | invoiced | settling. paymentHash is string | null and optional: the api sends the stored hash for invoiced and settling rows and null for owed and issuing, 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 session of the Fond account.
  • Returns / side effects: { ok: true, payouts }, or { ok: false, status, error } without throwing on an HTTP status. status is the HTTP status of the same-origin proxy answer (also for a 2xx whose body is unreadable or fails the schema, then with error: null), or 0 when the request itself failed (network error); error is the api's error text or null. Status 404 means the api's Fond surface is off, 403 means the session is not the Fond account, and every other failure is retried by the next tick.
  • Used by: FondPayoutSync through runFondPayoutTick.
  • 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 api POST /fond/payouts/:id/invoice) and parse fondPayoutInvoiceSchema as { 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. sparkInvoice is the recipient's fee-free Spark invoice when the api has one, otherwise null.
  • Inputs: Bearer session of the Fond account and the payout row id, URL-encoded into the path.
  • Returns / side effects: { ok: true, invoice }, or { ok: false, status, error } without throwing on an HTTP status (0 for a network failure). A 403 stops the loop as forbidden. Every other non-200 (409 in progress / not payable / below one sat, 503, including a 404 for an unknown or gone row) skips the row for this tick; error carries the api text but is never shown or logged with the invoice. The loop pays sparkInvoice, or bolt11 without 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: FondPayoutSync through runFondPayoutTick.

Function: fondE2eWallet

  • Purpose: Playwright-build-only fake Fond wallet, gated by getE2eNow(). It lets e2e drive runFondPayoutTick, runFondPayoutTickOnce, and FondDepositSync through 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, so FondPayoutSync and FondDepositSync keep the real wallet functions.
  • Inputs: No arguments. Its payFromWallet takes a WalletPayRequest; only { type: 'input', input } is payable (the fixture Spark invoice, or the BOLT11 when the api returns no Spark invoice); the input FOND_E2E_REFUSED_SPARK_INVOICE (spark1e2erefused) fails at prepare as an SDK refusal (sdk_error), so e2e reaches the Lightning fallback. Its listWalletPayments takes a WalletPaymentPage.
  • Returns / side effects: null outside a Playwright build. In a Playwright build, { payFromWallet, listWalletPayments, receiveBitcoinAddress, listUnclaimedDeposits, claimDeposit }. receiveBitcoinAddress resolves the fixed BIP-86 mainnet address bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr; listUnclaimedDeposits returns one open 50,000-sat deposit, and claimDeposit records its ceiling on it, as the SDK does. For payouts: prepare returns kind: 'confirm', and its send() resolves { kind: 'paid' }, records a completed sent payment for that input, and posts { input } to /e2e/wallet-send without 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 fixed spark1… fixture invoice unless a session fixture asks for sparkInvoice: null, and the api detects the send; the fake wallet sends no proof and has no preimage.
  • Used by: FondPayoutSync and FondDepositSync, 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: sparkInvoice first, and bolt11 when 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. A settling row is skipped.
  • Inputs: session; isCancelled (true after unmount, sign-out, or an account change); the two api calls fetchFondPayouts and postFondPayoutInvoice; payFromWallet; and listWalletPayments.
  • Returns / side effects: { paid, skipped, stop }. A list 404 sets stop: 'off' and a list 403 sets stop: 'forbidden'. A 403 from an invoice request also sets stop: 'forbidden'; a 404 there is skipped because the api answers an unknown id the same way. Any other list failure returns with stop: null so 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: any completed or pending match skips the row, and with no match or only failed matches the row is paid once. A row whose own send this tab saw as paid is 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, true treats the row as sent and joins the remembered paid ids, and false forgets it so a later tick may pay. An insufficient prepare 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 with reportPaymentFailure under flow fond_payout, including the sentLate of 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, before payFromWallet, and before send; 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, and FondPayoutSync through 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 FondPayoutTickDeps as runFondPayoutTick: session, isCancelled, fetchFondPayouts, postFondPayoutInvoice, payFromWallet, and listWalletPayments.
  • 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 in finally after 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: FondPayoutSync for 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 calls fondE2eWallet() once on mount. It calls runFondPayoutTickOnce with the real api functions, the fake wallet when that returned one and the real wallet functions otherwise, and isCancelled: () => stopped for 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 is ready or fondE2eWallet() returned the Playwright fakes. In that build the fakes replace payFromWallet and listWalletPayments; in every other build fondE2eWallet() is null and the real wallet functions stay. It runs one tick on activation and then every FOND_PAYOUT_INTERVAL_MS (60 s). Each tick pays sparkInvoice, or bolt11 without 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 result forbidden (403) or off (404) stops the loop only for the runKey (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 after WalletSync.

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 neutral SegmentedControl (group fond.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) and onchainAddress (the summary's onchainAddress, or null).
  • Returns / side effects: A section. Instant payment is selected on every load and renders WalletOwnAddress with copy and hint="fond.depositLightningHint": the Fond's username@domain, its Open CryptoPay QR, and the icon-only Copy. On-chain renders the muted fond.depositOnchainHint, the address in mono type broken anywhere (break-all) within the QR width, a plain QrCode of the BIP21 URI bitcoin:<address> (no amount, label fond.depositOnchainQr), an icon-only Copy / Copied (useCopied) that copies the bare address, and the muted line fond.depositOnchainConfirmations. The selector is shown only when onchainAddress passes isMainnetBitcoinAddress; 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) or bc1p (62), or base58 1… / 3… (26 to 34 characters). No checksum; it keeps free text, a testnet address, or a URI out of the deposit QR.
  • Inputs: value string.
  • Returns / side effects: true for a plausible mainnet address, otherwise false. No side effects.
  • Used by: FondDeposit.

Function: putFondDepositAddress

  • Purpose: PUT /fond/deposit-address (same-origin Bearer proxy of api PUT /fond/deposit-address) with JSON { address } and parse fondDepositAddressSchema.
  • Inputs: Bearer session of the Fond account and the wallet's static deposit address.
  • Returns / side effects: { ok: true, address }, or { ok: false, status, error } (FondPayoutFailure) without throwing on an HTTP status; 0 for a network failure, and a 2xx body that fails the schema keeps its status with error: 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: FondDepositSync through registerFondDepositAddress.

Function: proxyFondDepositAddressPut

  • Purpose: Proxies PUT /fond/deposit-address to the api.
  • Inputs: Incoming Request with Bearer session and JSON { address }.
  • Returns / side effects: Upstream Response with the api's status and body, or 502 when the api is unreachable. It forwards the Authorization header 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), and putFondDepositAddress.
  • Returns / side effects: registered when the api stored the address; stop on 403 or 404, so the caller sends nothing more for that session (as the payout loop stops); retry on 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-spark 0.26.0) claims a deposit by itself only while the claim fits maxDepositClaimFee, which defaults to 1 sat/vbyte; a dearer deposit stays unclaimed until the app claims it. This pass calls the SDK's claimDeposit with a fixed maxFee per deposit. The SDK records that ceiling on the deposit and applies it to its own later attempts, early or at maturity.
  • Inputs: listUnclaimedDeposits and claimDeposit of the wallet, and isCancelled, 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 of FondPayoutSync so each stays single-purpose: that one pays, this one receives.
  • Inputs: Reads the auth store (session, account id, role) and the wallet store status; calls fondE2eWallet() once on mount.
  • Returns / side effects: null. Active on the same condition as FondPayoutSync: a session, roleAtLeast(account.role, 'fond'), and a ready wallet or the Playwright fake. On activation it calls registerFondDepositAddress once per session:accountId: registered and stop (403 / 404) settle that key, so a wallet reconnect sends nothing again; retry or 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 after registered for the current session:accountId does it run claimFondDeposits, then again on every newDeposits or unclaimedDeposits report (onWalletDeposits), so an account at rank fond or 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's receiveBitcoinAddress, listUnclaimedDeposits, and claimDeposit replace the wallet functions. Sign-out, a locked wallet, or unmount stops listening.
  • Used by: RootLayout, right after FondPayoutSync.

Function: receiveWalletBitcoinAddress

  • Purpose: Reads the static Bitcoin deposit address of the connected wallet (receiveBitcoinAddress of the connection: the SDK's receivePayment with { type: 'bitcoinAddress' } and no newAddress, so the existing address).
  • Inputs: None.
  • Returns / side effects: The address. Throws wallet-connect without a connection, otherwise the SDK's error. It does not open the wallet.
  • Used by: FondDepositSync through registerFondDepositAddress.

Function: listWalletUnclaimedDeposits

  • Purpose: Lists the on-chain deposits the connected wallet tracks and has not finished claiming (the SDK's listUnclaimedDeposits), as WalletDeposit rows: txid, vout, amountSats, done (claim submitted or claimed, or refunded), and maxClaimFeeSats (a recorded fixed ceiling, else null).
  • Inputs: None.
  • Returns / side effects: The deposits. Throws wallet-connect without a connection, otherwise the SDK's error.
  • Used by: FondDepositSync through claimFondDeposits.

Function: claimWalletDeposit

  • Purpose: Claims one deposit of the connected wallet with a fixed fee ceiling (the SDK's claimDeposit with maxFee: { type: 'fixed', amount }).
  • Inputs: { txid, vout } and maxFeeSats.
  • Returns / side effects: Resolves once the SDK answered (settled, submitted, or deferred). Throws wallet-connect without a connection, otherwise the SDK's error (for example a matured deposit whose claim exceeds the ceiling).
  • Used by: FondDepositSync through claimFondDeposits.

Function: onWalletDeposits

  • Purpose: Subscribes to the SDK's newDeposits and unclaimedDeposits events 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/payouts to the api. The route answers the Fond payer's session the open rows for today.
  • Inputs: Incoming Request with Bearer session.
  • Returns / side effects: Upstream Response with the api's status and body, or 502 when this proxy cannot reach the api. It forwards the Authorization header and never logs the body.
  • Used by: Route GET /fond/payouts.

Function: proxyFondPayoutInvoicePost

  • Purpose: Proxies POST /fond/payouts/:id/invoice to the api. The api issues or returns the row's BOLT11, payment hash, and fee-free Spark invoice (or null).
  • Inputs: Incoming Request with Bearer session and the path id, 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/summary to 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 route GET /fonds/[username]/summary then compares the body's username with the path handle.
  • Used by: Route GET /fonds/[username]/summary.

Function: fetchFondSummary

  • Purpose: Reads the same-origin GET /fonds/:username/summary proxy and validates the body with fondSummarySchema. A body without onchainAddress (an api that does not send it yet) reads as onchainAddress: null.
  • Inputs: username — Fond handle from the route.
  • Returns / side effects: The FondSummary, or null on 404 (no Fond, or another handle). Throws on any other non-2xx status or a body that fails validation.
  • Used by: FondSummaryLoader on /fonds/[username].

Function: FondPage

  • Purpose: /fonds/[username] page. Wraps FondSummaryLoader in the unsigned public AppShell (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 StatsDashboard is the ink marketing stats page with charts and a fiat picker, and ViewProfileScreen renders a member profile with gift charts; neither shows Fond totals.
  • Inputs: username. Fetches fetchFondSummary(username) on mount and after Try again.
  • Returns / side effects: Loading (forum.loading), not-found (fond.missing), error (fond.error with Try again), or the card: the handle with the Fond ForumRoleTag and hint, three KPI tiles (fond.received, fond.paidOut + fond.fees, fond.balance + fond.balanceAsOf / fond.balanceNotReported), FondDeposit with the handle and the summary's onchainAddress, and fond.payoutsPaid. Every amount uses formatBitcoin with the preferred fiat from the current spot (useFiatPreference + useSpotRate + formatFiatDisplay) under it; the spot is not stored.
  • Used by: FondPage.
Functions — Handbook — 21.gifts