Skip to content

feat(flashcard): top up a Cashu card from the Cash wallet - #747

Merged
islandbitcoin merged 7 commits into
mainfrom
jabariennis/eng-616-top-up
Sep 30, 2026
Merged

islandbitcoin merged 7 commits into
mainfrom
jabariennis/eng-616-top-up

Conversation

@islandbitcoin

@islandbitcoin islandbitcoin commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Third of the ENG-616 (Flashcard v2) PRs: top up a Cashu card from the Cash wallet. Stacked on #746 (itself on #745), so the diff here is only the top-up; GitHub retargets it as those merge.

Built to the decisions of 2026-09-30:

  • D1: sats by default, USD as an option. A card holds one unit. A card holding value tops up only in that unit, so a card is never mixed; an empty card may choose USD. A top-up paid for and not on the card yet fixes the card's unit the same way. The USD option ships switched off behind the Remote Config flag cashuCardUsdEnabled: flash-pos prices every card proof as sats today, so a USD card tapped at a till would be charged many times over (ENG-619, filed). Flip the flag once ENG-619 item 1 ships. While it is off, a card set to USD, by its value or by an unfinished USD top-up, takes no new top-up and says why. An unfinished USD top-up can still be finished.
  • D2: the app mints at the mint it's connected to (CASHU_MINT_URL), never through the Flash backend.
  • D3: custom-amount sends are v0.8.0, not here.

How a top-up runs

  1. Amount. The standard amount input shows how many of the card's slots the amount takes (one per power of two). It won't continue past the card's empty slots less those an unfinished top-up of the card will take, the mint's 1,000,000 limit, or the Cash wallet's balance. Spent slots are not room: a spent slot is owed until it settles at the mint (cashu-javacard spec/CARD-FILE.md), and this app never clears one.
  2. PIN check (cards with a PIN). One tap, VERIFY_PIN, before anything is paid. A wrong PIN found only at the load would spend tries on value already paid for, and on applet 0.3 a PIN blocked there strands it for good.
  3. Quote. NUT-04 at the mint, locked (NUT-20) to a key only this app holds. The outputs are built only as canonical card secrets (flash-pos's and cashu-client's serialization, pinned to the J3R180 silicon fixture). Quote, lock key and blinding data are saved before the invoice is paid.
  4. Pay. From the Cash wallet, through lnInvoicePaymentSend under an idempotency key that is always sent: a top-up never goes out keyless. The top-up has its own copy of the mutation that selects each error's code, because whether a refused payment may still have left the wallet depends on which refusal it was:
    • failed ("nothing left your wallet", fresh key next time) only for a refusal made before execution (INSUFFICIENT_BALANCE, TRANSACTION_RESTRICTED, TOO_MANY_REQUEST, INVALID_INPUT, INVOICE_DECODE_ERROR), or IBEX's own corroborated FAILED status, which comes with no error;
    • everything else is unknown, same key: the busy lock on a same-key request that is still executing (flash maps ResourceAttemptsLockServiceError to UNEXPECTED_CLIENT_ERROR, "Unexpected error occurred, please try again or contact support if it persists (code: ResourceAttemptsLockServiceError: Unknown error)"), IBEX's generic error (IBEX may have debited), a key the server has seen with other parameters.
    • A retry refused before it ran is unknown too. It says nothing about the earlier dispatch whose answer was lost. IBEX's FAILED is different: flash caches it under the key and replays it to every retry, so the key can never pay. A retry answered with it retires the key, and the next Pay goes out under a fresh key as a first dispatch.
    • A sat top-up is a Lightning payment, not intraledger. Forge's sat backend is phoenixd, so the Cash wallet's payment leaves IBEX over Lightning, where fees, PENDING and route failures are normal. A USD top-up (the flagged path) has no Lightning hop, since IBEX pays its own invoice. It still takes two IBEX calls before the quote can be minted: the payment (lnInvoicePaymentSend pays through IBEX), then the mint's check of the invoice (Flash's lnInvoicePaymentStatus asks IBEX). Flash's IBEX client sets no timeout on either. The fee comes from lnUsdInvoiceFeeProbe and is shown only when the probe answers.
    • A quote is paid only while a quarter of its life is left, at least 40 s and at most 2 minutes: 2 minutes for a sat quote, and 40 s for a USD quote, which lives 60 s, so a USD quote is paid only in its first 20 s. The window counts from just before the quote was asked for, so the time the quote took to arrive counts against paying it. If it was never sent, it is quoted again first, and the fresh quote is checked again before it is paid. If it was sent, it is left to the mint.
    • How old a quote is comes from the phone's own clock: the time since the quote arrived, against the quote's life (its expiry less its bolt11 timestamp). It never comes from the phone's clock against the mint's expiry, which a phone hours fast would read as long dead and a slow one as younger than it is. Dropping a quote, Dismiss and "the mint no longer issues it" need the mint's expiry read on the phone's clock to agree too, so a clock set right since the quote arrived cannot fake its age. The pay window goes by the age alone, and a clock set back since the quote arrived is not paid on. This follows the send flow's isInvoiceExpired.
  5. Mint. When the mint's own quote state says PAID (the wallet's answer is not the authority), the app mints. It needs no card. Nutshell refuses to mint a PAID quote once its expiry has passed. With MINT_QUOTE_TTL unset, that expiry is the invoice's: phoenixd's for sat, and 60 s for USD. Forge's USD invoice is a Flash invoice, and IBEX caps every non-sat receive invoice at 60 s (flash src/domain/bitcoin/lightning/invoice-expiration.ts, src/services/ibex/client.ts; the ENG-555 invoice in invoice-expiry.ts is one). So the app mints paid top-ups from an app-level pass (advanceTopUps) that runs at launch, on every return to the foreground, and whenever the screen sends a payment. It then keeps asking every 15 s, in the foreground, until the quote dies. The top-up screen itself polls ~15 s, then hands over. Every signature must carry a valid DLEQ proof, and every proof must rebuild on this card (right key, canonical secret) before it is saved. A mint call whose answer was lost is recovered with NUT-09 restore, never a second mint. A quote state of PENDING (a mint call running) means wait. Any state but UNPAID saves the top-up as paid before it is minted. A refusal the mint will repeat (a PAID quote past its expiry, a signature that fails its DLEQ check) is saved on the record: no background pass asks the mint about it again, and Finish still asks once more. The mint's own expired-quote answer decides that, whatever the phone's clock reads: NUT code 20007 (Nutshell main's QuoteExpiredError), or 0.20.3's "quote expired" detail under code 11000. Only a mint call that got no answer is judged by the quote's age and the phone's clock.
  6. Load tap. VERIFY_PIN (if any), then LOAD_PROOF for each proof into empty slots only. CLEAR_SPENT is never sent, on purpose against the cashu-javacard spec, whose top-up flow sends it before every load (spec/NUT-XX.md:193, spec/APDU.md:278 and :453 at v0.2.0, the same on both 0.3 branches; spec fix filed as spec: the top-up flow sends CLEAR_SPENT before every load, which can destroy unsettled value cashucard/javacard#27). A card without the empty slots is refused before anything is written. A resumed load asks the mint (NUT-07, before the tap, so the card session stays offline) about every proof. It reads the card's inventory (spent slots too) and writes only the proofs the card lacks that the mint holds UNSPENT. A SPENT proof is never written back, even if its slot was cleared since. A PENDING one waits for a later load. When the mint can't be asked, nothing touches the card, and the screen says the mint couldn't be reached, not that no card was found. The provider's re-read also reads the keyset split when the balance moved, so the card screen names the unit again right after.

Where the money is, whatever interrupts

Everything is saved in the Keychain before its step runs.

Interrupted after Saved What happens next
the quote, before paying quote, lock key, blinding data nothing was sent: leaving the screen drops it, and a quote left behind (app killed) is dropped once it has expired
a payment was sent + "ever sent" (sticky), the key, when the quote arrived by the phone's clock, the quote's life kept until the mint holds the quote UNPAID 10 minutes past the end of its life, by the quote's age and by the mint's expiry read on the phone's clock, even if the wallet's answer read as a refusal
the payment went out, answer lost same the mint's quote state decides: PAID → mint; UNPAID → retry with the same key, while the quote has 2+ minutes left by its age; a retry answered with IBEX's cached FAILED → a fresh key
paid, before minting same minted without the card at the next pass: launch, foreground, a nudge, or the 15 s poll. It is still minted if the payment landed after the user left the screen. A PAID quote is saved as paid before the mint call. One the mint no longer issues (past its expiry) stays paid, no pass asks about it again, and Finish says so: contact support
the mint call went out, answer lost same the quote is ISSUED → NUT-09 restore
minted, before the tap + the proofs, DLEQ-checked Finish on the card screen, any time later
partway through the tap + "load started" mint (NUT-07) then card inventory; loads only what is missing and unspent

The card screen lists each top-up that is paid for and not on the card yet, or whose payment may still be out, with Finish. One whose invoice died unpaid gets Dismiss, which asks the mint once more and drops it only if the mint still holds it unpaid. One the mint holds as paid is saved as paid on the way, and a refused Dismiss says why the top-up stays and reads the list again. A paid top-up never gets Dismiss. A quote with no payment out (never sent, or refused) isn't listed.

Storage. The Keychain (flashcard-v2-topups), not redux-persist. A paid top-up that isn't on the card yet is money only its record can deliver, so it survives sign-out (the value belongs to the card). Reads are strict: a Keychain failure or an unreadable value throws, and never reads as "nothing saved" that the next write would overwrite. Writes run one at a time, and a drop is conditional (removeIf) so it never removes a record that changed since it was read. The 20 most recent loaded top-ups are kept for the history PR.

Refused before any amount:

  • a blocked PIN (on v0.2.0 it spends for anyone; on 0.3 it never loads again);
  • a PIN state or a unit this app can't read;
  • a card holding more than one unit, or value from a mint this app doesn't know;
  • a card with an unfinished top-up in a unit other than its own.

cashu-ts, and what it costs the bundle

@cashu/cashu-ts 4.11.0, flash-pos's version. It and the @noble/@scure v2 packages nested under it are ESM-only, so metro.config.js resolves package exports only for a request for a @cashu package or from a file inside one. #745's review showed that switching exports on app-wide re-resolved hundreds of shipped modules.

Proof (first round): I bundled Android release at #746's head and at 9a5df5c and compared the sourcemaps.

  • 4,863 → 4,890 modules. 0 removed, 0 re-resolved.
  • Added: cashu-ts (1), its nested @noble/curves (9), @noble/hashes (7), @scure/base (1) and @scure/bip32 (1), plus the 8 new app files.
  • +478 KB minified (18.36 → 18.84 MB). Most of that is noble v2 alongside the app's own noble v1.

Review round (18ad5ca): 9a5df5c re-bundled in a scratch worktree came to 4,890 modules and 18,839,066 bytes, matching the figures above. The fix commit bundled to 4,891 modules. The one added is app/utils/cashu-card-topup/minter.ts. 0 removed, 0 re-resolved, no new dependency. 18,870,923 bytes (+32 KB). 25ca5cb on top of it changes comments only.

Round 3 (4d07c68): I bundled Android release at 25ca5cb in a scratch worktree and at 4d07c68, and compared the sourcemaps. 4,891 modules in both: 0 added, 0 removed, 0 re-resolved. The engine's new imports (@galoymoney/client for the bolt11 decode, and the send flow's invoice-expiry) are modules the send flow already bundles, and clearSpent was a function, not a module. 18,870,926 → 18,879,886 bytes (+9 KB).

Not in this PR

  • Paying from the Bitcoin wallet (Breez). Not because of Lightning: the Cash wallet's sat top-up routes over Lightning too. The reason is that Breez sends are local SDK calls with no server-side idempotency key, so a lost answer could not be retried safely, and the mint's quote would be the only record of whether it landed. Cash wallet only for now.
  • Reclaiming spent slots. The app never sends CLEAR_SPENT, and clearSpent is not in this PR. Clearing is safe only once every spent slot's proof is SPENT at the mint (NUT-07), read in the same session. That belongs with the sweep (PR 3), which settles them first and adds clearSpent behind that gate.
  • Minting while the app is in the background. JS timers can't be relied on there. The next foreground asks again. Ops, separately: a longer MINT_QUOTE_TTL on forge would let a PAID quote stay mintable longer than its invoice. The invoice's own expiry still bounds when it can be paid, but watch the pending-invoice watcher's polling load.
  • USD cards at flash-pos terminals: ENG-619, and the flag stays off until then.
  • Sweep to wallet (PR 3), history (PR 5), custom-amount sends (v0.8.0).
  • A cap on how much a card may hold is an open product question. Today the only limits are the mint's 1,000,000 per top-up and the wallet's send limits; the card is a bearer instrument (SECURITY-MODEL: keep balances small).

Firmware notes (cashu-javacard, found while building this)

  • LOAD_PROOF has no duplicate check: the same proof loaded twice takes two slots, and the second spend fails at the mint after burning its slot. Hence the inventory on resume.
  • LOAD_PROOF writes the slot's status byte before its data (processLoadProof, not in a transaction). A tear mid-write can leave a garbage "unspent" slot that GET_BALANCE counts. That's threat Ibex #11 (tear-off, unanalysed); worth a transaction in the applet.
  • CLEAR_SPENT zero-fills every spent slot, and the applet marks a slot spent before it signs. A card lifted mid-SPEND_PROOF holds a proof the mint has never seen, and the only copy of its nonce and C is in that slot. Hence no CLEAR_SPENT here, though the spec's own top-up flow sends it before every load: spec: the top-up flow sends CLEAR_SPENT before every load, which can destroy unsettled value cashucard/javacard#27.

Tests

  • Engine, against a mint that really signs (BDHKE, DLEQ, NUT-20, NUT-09, NUT-07) and refuses a PAID quote past its expiry as Nutshell does, and a card that stores slots like the applet:
    • saved before paid; dispatched and "ever sent" saved before the wallet is asked;
    • the mint asked before paying; a fresh key after a refused first dispatch; the same key, still a retry, after a refused retry or an unknown;
    • a quote near its expiry re-quoted before a first payment, and never paid late once sent;
    • a record read as refused whose invoice then settles is never cancelled, and is minted; dropped only past expiry + grace with the mint saying UNPAID, never when PAID;
    • minting without the card after the user left; a paid quote left past its expiry can't be minted; PENDING waits; two mints at once mint once;
    • restore on a lost answer; ISSUED resumed by restore alone; DLEQ tampered or missing; every quote-check clause;
    • resumed load skips what's on the card (spent or not); the phantom: a proof spent, settled and cleared since is never written back; a PENDING one is held; a resume without the mint's word touches nothing; spent slots never cleared, an unsettled burn stays readable;
    • unfinished top-ups hold their slots and their unit;
    • a phone clock 2 h fast, 30 min slow, and set back: a fresh quote paid as it is and kept while its payment is pending, then minted; a failed mint call never read as the quote's expiry; nothing dropped or dismissable before its life and the grace are really over; no invoice paid, or retried, with less than its pay window left; nothing paid on a clock set back; on a phone 30 min slow, a paid quote the mint refuses as expired is asked about once and Finish says so; on a clock set right since the quote arrived, a mint call with no answer is not read as the quote's expiry;
    • the pay window sized to the quote (2 min, a quarter, the 40 s floor); a fresh quote whose whole life is shorter than the 40 s floor is never paid, even quoted again;
    • a USD top-up against a 60 s quote (the fake mint now has a usd keyset): paid and minted under the usd keyset; retried under the same key after an unknown answer; quoted again and paid once a never-sent quote is past its first 20 s; a sent one never retried there; the time a quote took to arrive counted against paying it;
    • the mint's refusal: Nutshell 0.20.3's form read the same as main's; any other refusal from the mint never read as the quote's expiry; an invoice with no issue time is refused before anything is saved;
    • a PAID quote past its expiry is saved as paid and refused, no later pass POSTs for it, Finish asks once more, Dismiss refuses; a quote the mint holds paid is saved as paid before a mint call that fails; a DLEQ refusal is never asked about again;
    • a retry answered with IBEX's cached FAILED retires the key, and the next Pay is a first dispatch.
  • Store: strict reads, concurrent writes, pruning, conditional removal.
  • Mint client: quote states (PENDING passes, unknown refused), NUT-07 answers paired by Y.
  • Minter loop: polls while a payment may land, stops when none may, nothing in the background, one pass at a time.
  • Outputs: the silicon fixture, splitPow2, refusal of a proof locked to another card or in cashu-ts's own P2PK form.
  • Hook: every payment answer in the server's own shape, codes included (the busy lock as flash really sends it, IBEX's generic error, balance, the send guard, IBEX's FAILED as definitive, key reuse, a refused key field), never keyless, the fee probe, NUT-07 asked before the tap and a mint that can't be asked failing as mint-unreachable with no tap, the focus pass, Dismiss and a refused Dismiss reading the list again, the app-level minter.
  • Screen: eligibility (including an unfinished top-up's unit), room net of unfinished top-ups, both PIN paths, cancel, payment failed/unknown/expired, leaving before vs. after a dispatch and while the quote is prepared, prepare failures ("nothing was paid"), mint still waiting, mint answer refused, paid quote expired at the mint, no room, a held load, both resumes, a mint unreachable at the load, a top-up gone from the store. Card screen: Dismiss for a dead quote, none on a phone clock running fast, a paid top-up the mint no longer issues shown as paid with Finish, a refused Dismiss saying why, a refused quote hidden. With the USD flag off: a card holding USD and an empty card with an unfinished USD top-up refuse a new top-up with their own copy, and an unfinished USD top-up still finishes.
  • Provider: the split re-read after a value move, and the old split's late answer never landing.
  • Mutation-checked. The first round reported 19 mutants caught. Round 2: 18 mutants of its guarantees each fail a test. Among them: any FAILURE read as failed; a refused retry retiring the key; cancel trusting the retry flag alone; a resumed load ignoring the mint; room or unit ignoring unfinished top-ups; the card-free pass not minting; paying near expiry; no grace; PENDING restoring; spent slots counted as room; removeIf ignoring its test. Round 3 (4d07c68): 19 mutants, each failing a test: dropping or dismissing by the phone's clock against the mint's expiry alone; dropping by the quote's age alone; the pay window by the phone's clock; the pay window ignoring a clock set back; no re-check after a re-quote; "the mint no longer issues it" by the phone's clock; a quote the mint holds paid not saved as paid before minting; a pass asking again about a repeated refusal; the refusal not saved; a retry answered with IBEX's FAILED keeping its key; any refused retry retiring it; cancel not saving a paid quote as paid; a quote that expires before its invoice was issued accepted; IBEX's FAILED not read as definitive; no mint-unreachable wrap before the tap; a refused Dismiss not reading the list again; the engine's load refusals read as no card; a not-found top-up read as saved; a refused Dismiss swallowed. Round 4 (40baf21): 5 mutants, each failing a test: a fixed 2-minute window; no 10 s floor; the clocks deciding a refusal the mint gave; quoteExpired by the quote's age alone; no USD flag gate. Round 5 (090f99e): 3 mutants: the window counted from the quote's arrival; the old 10 s floor; the request time read after the quote arrives.
  • Full suite 154 suites / 1,821 tests. tsc, changed-lines lint, prettier, translation drift, check:translations, check:codegen and graphql-check are clean.

Device check owed

CASHU_MINT_URL is forge.flashapp.me, a mainnet mint: a device top-up moves real sats. Use a small amount from a prod-configured build, or point CASHU_MINT_URL at a test mint.

Both phones, a real card:

  • PIN-less card: top up 21 sats; confirm the card screen shows 21 sats in sats.
  • PIN card: the PIN check tap comes before the pay; enter a wrong PIN once and confirm nothing is paid.
  • Recovery: kill the app after paying and before the tap. Reopen and wait a few seconds: the launch pass mints without the card. Then tap the card, and Finish goes straight to the load tap with no "Getting the funds ready" step. Lift the card mid-load, then Finish again; the card must end with exactly the top-up's proofs (cardctl inventory: no duplicate nonces).
  • Refusals: a card with too few empty slots is refused before paying, even when it has spent slots.
  • Flag on (dev): an empty card takes USD, and a card holding sats doesn't offer it. A USD quote is paid only in its first 20 s, counted from when it was asked for, which is before the fee probe and the confirm screen. Tap Pay about 15 s after the confirm screen appears: whether or not Pay quotes again first, it must pay and mint. Note how long Pay takes to reach the load step; if it is anywhere near 40 s, the window must grow.
  • Flag off: a card holding USD shows "This card holds USD, and this app can't top up USD yet." and no amount entry.
  • Clock: set the phone's time by hand two hours ahead, then top up a PIN-less card with 21 sats: it pays and loads, and while the payment is on its way the card screen shows it as waiting, never with Dismiss. Set the time back to automatic afterwards.

🤖 Generated with Claude Code

@linear

linear Bot commented Sep 30, 2026

Copy link
Copy Markdown

ENG-616

Dread and others added 7 commits September 30, 2026 17:00
…onnected mint

The engine for loading value onto a Cashu card (ENG-616 PR 2, D2): the app
quotes at the mint it is connected to (CASHU_MINT_URL), the user's wallet
pays the invoice, and the app mints outputs locked to the card and writes
them with LOAD_PROOF. No Flash backend call mints anything.

cashu-ts 4.11.0 (flash-pos's version) is the rail. It and the @noble/@Scure
v2 packages nested under it are ESM-only, so Metro resolves package exports
for requests FOR a @CASHU package or FROM a file inside one, and for
nothing else: switching it on app-wide re-resolved hundreds of shipped
modules (#745).

- Card outputs (ported from flash-pos): the canonical P2PK secret, pinned to
  the silicon fixture; outputs built only from it; a proof is checked to
  rebuild on the card before it may be written.
- CLEAR_SPENT (0x31) in the codec.
- The store keeps unfinished top-ups in the Keychain, not redux-persist: a
  paid top-up not yet on the card is money only its record can deliver, so
  it survives sign-out. Reads are strict (a Keychain failure or an unreadable
  value throws, never reads as empty) and writes run one at a time.
- The engine saves each step before its outside effect:
  - the quote (NUT-20 locked to a key only this app holds) and the blinding
    data are saved before the invoice is paid;
  - the payment is marked dispatched before the wallet is asked, and the
    mint's own quote state decides "paid", so a paid invoice is never paid
    again;
  - a mint answer that was lost is recovered with NUT-09 restore, never a
    second mint;
  - every proof is DLEQ-checked and checked to rebuild on this card before
    it is saved, and the saved proofs are what gets loaded;
  - a resumed load reads the card's inventory (spent slots too) because the
    applet accepts the same proof twice; CLEAR_SPENT runs only when the
    empty slots cannot take the rest.
- runCardOperation: an operation that moves value re-reads the keyset split
  in the same session, so the card screen names the units again after a
  top-up; the old split's late mint answer still never lands.

Tests run against a mint that really signs (BDHKE, DLEQ, NUT-20, NUT-09)
and a card that stores slots like the applet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The top-up screen and its entry points, on the engine from the previous
commit (ENG-616 PR 2).

The card screen gets Top up, for a signed-in holder of a card whose PIN
state it can read, and a line for each top-up that is paid for and not on
the card yet (or whose payment may still land), with Finish to resume it.
A quote that was never sent for payment is not shown: nothing was paid.

The screen: amount → (PIN check) → confirm → pay → wait for the mint →
load tap → done.
- Unit (D1): sats by default. A card holding value tops up only in that
  unit, so a card is never mixed; an empty card may choose USD when the
  remote flag `cashuCardUsdEnabled` is on. It ships off: flash-pos prices
  every card proof as sats today (ENG-619), so a USD card would be
  over-charged at a till.
- Refused before any amount: a blocked PIN (on v0.2.0 it spends for anyone;
  on 0.3 it never loads again, stranding what was paid), a PIN state or a
  unit this app cannot read, a card holding more than one unit.
- The amount says how many of the card's slots it takes, and will not go
  past the slots (empty plus spent), the mint's 1,000,000 limit, or the
  Cash wallet's balance.
- On a card with a PIN, the PIN is checked with a tap BEFORE anything is
  paid, then reused for the load tap. A wrong PIN found only at the load
  would spend tries on value already paid for.
- Paid from the Cash wallet through the send flow's idempotent
  lnInvoicePaymentSend (a stable key, never re-sent keyless on a retry;
  the server replaying the key for other parameters is "unknown", never a
  failure). The mint's invoice sits on Flash, so the payment is
  intraledger. The fee comes from lnUsdInvoiceFeeProbe and is shown only
  when the probe answers.
- A failed payment stays on confirm (nothing left the wallet); an unknown
  one says to check the history and retries through the engine, which asks
  the mint first. Leaving before paying drops the quote; leaving after a
  dispatch keeps it.
- A mint that has not seen the payment after ~15 s is left for later; the
  card screen finishes it. A mint answer that fails verification loads
  nothing and says to contact support. A card with no room says so and
  keeps the top-up.

Tests: the eligibility rules, every screen path, the hook's reading of each
payment answer, and the card screen's Top up and unfinished list. Mutation
checked: removing any of the money guarantees fails a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A payment read as refused no longer lets the top-up go, a paid quote is
minted before the mint stops issuing it, and spent slots are never cleared.

Payment answers (use-card-top-up.ts, engine.ts)
- The top-up has its own lnInvoicePaymentSend document that selects each
  error's code. A FAILURE reads as "nothing left the wallet" only for a
  refusal made before execution (INSUFFICIENT_BALANCE, TRANSACTION_RESTRICTED,
  TOO_MANY_REQUEST, INVALID_INPUT, INVOICE_DECODE_ERROR) or for IBEX's own
  corroborated FAILED status with no error. The busy lock on a same-key
  request (ROUTE_FINDING_ERROR, empty message) and IBEX's generic error are
  unknown now.
- A refusal of a RETRY is unknown too: the key and the retry flag stay.
- New sticky payment.everDispatched. cancelTopUp drops a record that was ever
  sent only once the mint still holds its quote UNPAID 10 minutes past its
  expiry. Leaving the screen after a refusal no longer deletes the lock key.
- A top-up is never paid without its key. wentKeyless is gone, along with
  the keyless fallback it was meant to guard.

Expiry (engine.ts, minter.ts, app.tsx)
- Nutshell refuses to mint a PAID quote after its expiry. advanceTopUps mints
  paid quotes without the card. It runs at launch, on foreground, on a nudge
  from the screen, and every 15 s while a payment may land, until the quote
  dies. It also runs when the card screen gets focus.
- A quote never sent with under 2 minutes left is quoted again before paying.
  A quote already sent is never paid that late.
- A PAID quote the mint no longer issues gets its own message. PENDING quote
  state now means wait, not restore. The fake mint refuses after expiry, as
  Nutshell does.

Card slots (engine.ts, cashu-card.ts, flashcard-v2-topup.tsx)
- Only empty slots count as room, and CLEAR_SPENT is never sent. A spent
  slot is owed until it settles (cashu-javacard spec/CARD-FILE.md). The
  clearSpent docstring now says so.
- A resumed load asks the mint (NUT-07) about each proof before the tap.
  The card never gets back a proof the mint has seen spent. A PENDING proof
  waits for a later load.
- Unfinished top-ups hold their slots and their unit, in prepareTopUp and on
  the screen.

Store and card screen
- advanceTopUps drops dead quotes, sent or not. The card screen can dismiss
  a dead sent quote, and the removal is conditional (store.removeIf).
- Prepare failures say nothing was paid.

Correction to 9a5df5c: a sat top-up is NOT intraledger. Forge's sat
backend is phoenixd, so the payment is Lightning out of IBEX, where PENDING
and route failures are normal. Only USD top-ups settle on Flash.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eeps its record

A refused first dispatch takes a fresh key; it no longer lets the record
go (everDispatched keeps it until the mint says the quote died unpaid).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-3 review fixes on the Cashu card top-up (ENG-616).

Quote age (engine.ts, types.ts)
- Every expiry decision compared the phone's clock with the mint's. On a
  phone about 70 minutes fast, a PENDING payment's record was dropped, lock
  key and all, and the payment then settled into a PAID quote nobody could
  mint. A slow clock paid late. A quote now saves quote.quotedAt (the
  phone's clock on arrival) and quote.lifeMs (its expiry less its bolt11
  timestamp), and is judged by its age on the phone's own clock, as the
  send flow's isInvoiceExpired does.
- quoteIsDead (drop, Dismiss, cancel) and quoteExpired (the mint no longer
  issues it) fire only when the age and the mint's expiry on the phone's
  clock agree. The pay window goes by the age alone: here the harmful
  answer is "there is time", so the absolute reading may neither hold it
  back (a slow phone would pay late) nor fire it alone (a fast phone could
  never pay). A clock set back since the quote arrived is not paid on.
- The pay window is checked again after a re-quote. A quote whose invoice
  states no issue time is refused before anything is saved.

A paid quote the mint no longer issues (engine.ts)
- Any quote state but UNPAID now saves a quoted record as paid before it is
  minted (mintTopUp, cancelTopUp), conditional on the same quote. The card
  screen shows it as paid with Finish, never as expired with Dismiss.
- A refusal the mint will repeat is saved on the record (mintRefused), and
  no card-free pass asks the mint about it again. Finish still asks.

Payments (use-card-top-up.ts, engine.ts)
- IBEX's FAILURE with no error is definitive: flash caches it under the key
  and replays it to every retry. A retry answered with it retires the key;
  the next Pay is a first dispatch under a fresh key. A retry refused before
  it ran stays unknown.
- The busy lock is UNEXPECTED_CLIENT_ERROR "... (code:
  ResourceAttemptsLockServiceError: Unknown error)", not ROUTE_FINDING_ERROR
  with an empty message. Spec and comment corrected.

Messages (flashcard-v2-topup.tsx, flashcard-v2.tsx)
- A resumed load whose NUT-07 check could not reach the mint fails as
  mint-unreachable, before any tap. It no longer says "No Cashu card found".
  No TopUpError reads as a missing card any more.
- A top-up gone from the store no longer says "Your top-up is saved".
- A refused Dismiss reads the top-ups again and says why the top-up stays.

CLEAR_SPENT (cashu-card.ts)
- clearSpent and INS.CLEAR_SPENT are removed with their tests; the sweep
  adds them behind its NUT-07 gate. loadTopUp names the spec lines it does
  not follow (NUT-XX.md:193, APDU.md:278 and :453 at v0.2.0) and the spec
  fix, cashucard/javacard#27.

The fake mint now quotes real signed bolt11 invoices. New i18n keys
topUpMintUnreachable, topUpGone and topUpDismissRefused, in all 23
translations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Size the pay window to the quote: a quarter of its life, between 10 s
  and 2 min. A forge USD quote lives 60 s (IBEX caps every non-sat Flash
  invoice at 60 s), so the fixed 2-min window re-quoted every USD Pay and
  then refused the new quote too. Nothing USD could be paid.
- A paid quote the mint refuses as expired (NUT code 20007, or Nutshell
  0.20.3's "quote expired" detail under code 11000) is final, whatever the
  phone's clock reads. Only a mint call that got no answer is judged by the
  quote's age and the phone's clock. A slow phone no longer POSTs a refused
  quote every 15 s, and Finish says to contact support.
- With cashuCardUsdEnabled off, a card set to USD, by its value or by an
  unfinished top-up, takes no new top-up (new copy in all locales). An
  unfinished USD top-up still resumes and finishes.
- Fake mint: a usd keyset with 60 s quotes, a unit check, and Nutshell's
  MintOperationError for an expired quote.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 15 s window a 60 s usd quote got rested on its payment settling inside
Flash. It doesn't: lnInvoicePaymentSend pays through IBEX, and the mint can
mint only after its own check of the invoice, Flash's lnInvoicePaymentStatus
asking IBEX. Flash's IBEX client sets no timeout on either call, so a slow
IBEX could leave a paid quote the mint refuses as expired.

- The least pay window is 40 s, up from 10 s: a 60 s usd quote is paid only
  in its first 20 s (Pay quotes again after that). Sat keeps its 2 min.
- The pay window counts from just before the quote was asked for
  (`quote.requestedAt`), so the time the quote took to arrive counts against
  paying it. The drop and expired verdicts keep `quotedAt`, where reading the
  age low is the safe side.
- The fake mint refuses as Nutshell main does, each refusal a
  MintOperationError with its code, so tests read them as the mint's answer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@islandbitcoin
islandbitcoin changed the base branch from jabariennis/eng-616-change-pin to main September 30, 2026 21:00
@islandbitcoin
islandbitcoin force-pushed the jabariennis/eng-616-top-up branch from 090f99e to 91845b8 Compare September 30, 2026 21:00
@islandbitcoin
islandbitcoin merged commit e10f82a into main Sep 30, 2026
11 checks passed
islandbitcoin pushed a commit that referenced this pull request Oct 9, 2026
Mirror the five new FlashcardV2 keys (slotsSpentNote, topUpSlotsReclaim,
topUpReclaimed, topUpSlotsSettling, topUpSettlingNote) and the updated
slotSummary into all 23 locale files, the same way #746/#747/#755 did,
so check:translation-drift passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6
islandbitcoin added a commit that referenced this pull request Oct 9, 2026
…#759)

* feat(cashu-card): CLEAR_SPENT, slot-shape check and spent-slot reads (ENG-631)

Add the CLEAR_SPENT (0x31) APDU and `isProofShaped`, the card file's slot
checks that tell a CLEAR_SPENT remnant from a proof. A card read now reads
every occupied slot (`readCardSlots`) and carries the spent slots on
`CashuCardInfo.spentSlots`, so the next top-up can ask the mint about them
before its load tap. The Flashcard context re-reads the slots after an op
that moved the balance or the spent count, so a clear shows at once.

`getUnspentByKeyset` still reads unspent slots only; nothing here sends
CLEAR_SPENT.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* feat(cashu-card-topup): reclaim mint-settled spent slots on the load tap (ENG-631)

`reclaimVerdicts` asks the mint (NUT-07) about the card's proof-shaped spent
slots before the tap; `reclaimPlan` says what a reclaim will do with them;
`reclaimSpentSlots` re-reads the spent slots in the session and sends
CLEAR_SPENT only when every one is a remnant or mint-SPENT, otherwise sends
nothing and counts what is still settling. `prepareTopUp` counts
`card.reclaimable` as room; `loadTopUp` itself still never clears, and its
inventory no longer takes a torn spent slot's nonce as the record's proof.
`TopUpError` can carry the reclaim's result with a refusal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* feat(flashcard-v2): free settled spent slots on the top-up's load tap (ENG-631)

The load tap now runs VERIFY_PIN, the reclaim, then the load in one session;
the mint is asked about the spent slots before the tap, and a mint that
cannot answer costs no tap. The amount step counts the slots the tap will
free as room (`reclaimable`), the done step says how many were freed, and a
no-room refusal says how many spent slots are still settling. The card
screen shows unspent, spent and free counts with a note on spent slots.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* fix(cashu-card-topup): hand the reclaim's card read to the load, and drop the retry note from the done step (ENG-631)

Review fixes on #759.

- `reclaimSpentSlots` hands on what it read (`inventory`: the slot
  statuses and each spent slot's proof) when it sent no CLEAR_SPENT, and
  `loadTopUp` takes that in place of a read of its own. A first load in
  the same tap now sends no GET_SLOT_STATUS; a resumed load reads only
  the unspent slots, taking the spent ones from the reclaim. After a
  clear the read is stale and the load reads the card afresh, which
  after a full clear means the unspent slots alone. On a resumed load
  of a card with k spent and u unspent slots that is u GET_PROOFs
  before the first LOAD_PROOF instead of 1 + k + u.
- The done step's settling note no longer reuses `topUpSlotsSettling`,
  whose "Try again later." belongs to the `slots` refusal: a load that
  went through has nothing to try again. New `topUpSettlingNote`.

Tests: engine tests count the tap's APDUs for a first and a resumed load
with and without a clear, and assert the inventory handed on (or not);
the hook test checks the hand-off; the screen test asserts the new note
and that it carries no retry imperative.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* chore(i18n): add FlashcardV2 reclaim copy to every locale

Mirror the five new FlashcardV2 keys (slotsSpentNote, topUpSlotsReclaim,
topUpReclaimed, topUpSlotsSettling, topUpSettlingNote) and the updated
slotSummary into all 23 locale files, the same way #746/#747/#755 did,
so check:translation-drift passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* fix(flashcard-v2): wait for the reclaim plan before showing the amount field, and rethrow the engine's own refusal (ENG-631)

Review fixes on #759:

- The amount field waited for the unfinished-top-ups read but not for the
  reclaim plan. On a card with no empty slot and every slot spent, the room
  was 0 until the mint answered, so the field refused every amount ("try a
  smaller amount") and then changed its mind a round-trip later. The screen
  now tracks the plan settling (`reclaimRead`), set at once when there is
  nothing to ask about and in a `finally` otherwise, and the field waits on
  both reads.

- `useCardTopUp.load` built a fresh TopUpError to attach the reclaim, so a
  refused load's stack pointed at the catch block rather than the engine's
  own check. `TopUpError.reclaim` is now writable and the original error is
  rethrown with it set.

Tests: two screen tests hold the plan (resolve / reject) and assert no field
mounts until it settles; a hook test asserts the rejected error is the very
one the engine threw.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

* fix(flashcard-v2): show a spinner while the amount field waits on the reclaim plan (ENG-631)

Review fix on #759:

- The amount field waits for the reclaim plan, and that plan is a mint
  round-trip over the phone's network with no timeout. On a card with
  spent slots the amount step showed the unit caption, "Paid from" and a
  disabled Continue around a blank gap for as long as the mint took to
  answer, or RN fetch took to fail. An ActivityIndicator now sits in the
  field's slot (`topup-amount-loading`) until both the unfinished-top-ups
  read and the plan have settled, matching the screen's own loading step.

- The held-plan, held-read and refused-mint screen tests assert the
  indicator is present before settle/refuse and gone after.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WxkKbrg2Xohf3mQj7BLrs6

---------

Co-authored-by: Dread <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant