Skip to content

feat(cards): card programs on the reservation core (tracking) - #51

Closed
Slokh wants to merge 253 commits into
mainfrom
cards
Closed

Slokh wants to merge 253 commits into
mainfrom
cards

Conversation

@Slokh

@Slokh Slokh commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Draft. Carries card programs built on the TIP-1153 reservation core to main. Not for merge yet.

Programs in src/spend/programs (interfaces in src/interfaces/spend/programs), split by role:

  • CardAuth (immutable; settings run in a once-per-chain CardAuthAdmin): cards, limits, mandates, operator roles with caps, a 2-day settings delay, purchases recorded in one word each, funding orders versioned so an open purchase always walks the order it was authorized under, capture totals bounded by authorization plus tolerance, network stand-ins booked with bookStandIn (counted against limits, never refused by them), and a settlement ledger with cut-off checkpoints.
  • Sources (ISource): CashSource (including converted legs priced in a band around the rate locked at authorization), SavingsSource (bounded by the float while redemptions defer) and CreditSource (APR within the borrower's accepted maximum, statements with retried collection, liquidation and charge-off with surplus to the borrower).
  • IssuerTreasury: payouts with advances as a receivable, collateral the sponsor accepts, an exposure guard counting unsettled and absorbed amounts plus a per-token stress share of open converted holds, and a guard hand-off after a long sponsor silence.
  • IssuerDesk (disputes, receivables), MerchantReserves, Rewards, AccountKeys, AccountLifecycle, Conversion.

Amounts the network already paid are always booked; shortfalls the cardholder can't pay are absorbed by the issuer and counted as exposure; the core holds no debt. Tests in test/spend/programs include stress suites, a differential replay against the node, and gas snapshots.

Slokh added 30 commits November 16, 2026 20:22
Card programs are holder contracts on the reservation core. CardProgram keeps cards, limits, merchant mandates and each owner's funding order, places one to three holds per purchase in one call, runs the capture waterfall and reverse refunds, and logs every purchase step with a settled-through cursor. SavingsFacility is the payee of savings legs and redeems captured shares to the settlement account. CreditLine draws are holds on the lender's balance, with optional pledge-secured credit.
…in CardProgram

Owners grant a program terms (a lifetime limit, per-purchase, daily and
monthly limits at a UTC offset) that bound all their cards; windows are
calendar days and months. Holds count from authorization, captures past
the hold and charges when they land, and releases and refunds give their
amount back. Adds partial approvals, adjust (raise or lower a purchase's
cash hold), charge (a late presentment as one core charge, with debt
within the owner's cap), issuer operators, card caps and issuer freezes.
Spend accounting and the adjust and refund paths move into the linked
CardLimits and CardAdjust libraries to keep CardProgram under the code
size limit.
A late charge takes what the owner has available plus the debt cap headroom it
set for the program; the issuer absorbs the rest instead of reverting, and
PurchaseCharged reports it. The ledger also keeps the net at the settled cursor.
A stand-in reserves what the owner had, which may be less than the offline
approval. Adjusting it down keeps what is reserved up to the new amount and
gives the rest back; it never goes up.
An issuer's services over its CardProgram: splits paid to named parties from the settlement account at each capture, rewards paid out of a funder's split, refunds that take both back in proportion through core charges, and corrections linked to the program step they fix. Each step emits a self-describing event.
CardRegistry keeps what an issuer records about its program's cards beyond what
authorization reads: a network token reference hash, program type and holder.
It is a companion contract, so CardProgram's runtime code does not grow.
CardProgram.setExpiry moves a card's expiry, such as a virtual card's.
Money paid through ReceiveSweep lands as a normal credit, so the core repays the
owner's capped debt first, and what is left goes into the owner's chosen savings
vault in its name.
Disputes open on captured, unrefunded purchases, move forward with evidence and provisional credit from the settlement account, and resolve: a merchant win takes the credit back from what the cardholder has and leaves the rest as capped debt; a cardholder win counts as a refund, splits included.
…ograms

AccountKeys records the keys that sign an account's card actions and the guardians that can replace them; CardProgram checks it for cardholder card actions. IdentityRules records jurisdictions, attesters' keys, attestations and each program's identity policy; CardProgram checks it at authorization. A stand-in on a frozen card now declines.
The lender accrues interest on what a line owes and closes statements; a statement falling due is collected from the borrower's autopay sources (cash, then free Earn shares), and repayments pay statements oldest first.
…-over to card programs

AccountLifecycle tracks an owner's standing across programs (active, dormant, closed, estate) and pays out what an account can release: debt first, then the payee. Programs read it at authorization and report activity to it. CoverageRegistry records which balances a deposit insurance scheme covers and splits an account's positions into insured and uninsured value. An open purchase now follows its card's replacements, and carryUsage brings an owner's usage, card windows and mandate spend counted on another instance of the program into this one.
…rt open dispute exposure

IssuerDesk now recovers a lost dispute's provisional credit from the owner's free settlement token, then its savings positions in funding order, before leaving fee-free capped debt, and logs each source as DisputeRecovered. A refund or correction past what a purchase still nets settles provisional credit instead of paying it twice (DisputeSettled). The desk reports what open disputes risk and the debt lost disputes left, and a cardholder win frees the mandate usage provisional credit already covered through CardProgram.creditBack.
…token changes

Owners set a hold rounding increment per program; holds and increases round up to it and captures stay exact. A settlement token change is refused while anything is still sized in the old token, purchases keep the token they were authorized in, and limits keep their value across the change.
…from converted cash

A late charge on a program settling in another stablecoin is owed in that token, like capture debt. repayConverted converts the owner's cash through the program's venue to repay it, and forwards what the program was repaid to the settlement account.
Slokh added 11 commits November 20, 2026 23:57
CardAuth lets only the current exposure guard replace or clear it. IssuerTreasury.handOffGuard(next) passes that on: the sponsor at any time, the issuer before a sponsor is named or once no collateral is live and nothing is seized or exposed (stressedExposure() == 0).

Also regenerates the auth gas snapshots for the merged CardAuth and CashSource changes.
IssuerTreasury weighs each converted token's open holds by a stress figure the issuer sets per token (setFxStress: raising applies at once, lowering waits the settings delay; default 1000 bps). CashSource keeps an exact open total per converted token (openConvertedOf, convertedTokens; at most 8 tokens, one slot per token). stressedExposure reads the program's cash-source list (CardAuth.cashSources, filled on approval), replacing addFxSource/removeFxSource.
The weekly-keeper stress case always renewed locks since renewal widened to RENEW_WINDOW, so it never let a lock lapse. A keeper now runs on its own schedule and relocks what is due: weekly and every 14 days keep every lock with zero loss, every 20 days (past RENEW_WINDOW) lets locks lapse and relocks them, and every 40 days (past the term) loses only what defaulted borrowers withdrew.
PaymentCallShape.t.sol pins what a node-side registry of payment calls
reads from CardAuth:

- Immutable ranges: CardAuths with different issuers, settlement
  accounts and admins differ only inside the artifact's
  immutableReferences (ADMIN 2x32 bytes, SETTLEMENT_ACCOUNT 2x20) and
  hash alike once those are zeroed, to the artifact's own runtime code.
- Linked libraries: CardAuth and CardAuthAdmin link the same CardLegs
  and CardLimits, outside the zeroed ranges, so the masked hash names
  them.
- No SELFDESTRUCT or CALLCODE in CardAuth, CardAuthAdmin or the
  libraries, and no DELEGATECALL in the libraries.
- authorize, capture, charge, release, adjust and refund keep their
  selectors and static-only calldata (4 + 32 * n bytes).
- Gas, over the reservation-core model: the four-leg shape (converted
  EURX cash, USD cash, savings, credit line) under per-call caps, a
  one-leg purchase under the proposed lane caps (authorize 1.5M,
  capture 500k), and the model at or above node 0703315's one-leg
  figures.

Reads out/CardAuth.sol and out/CardAuthAdmin.sol, added to
fs_permissions.
CardAuth's deployed code, metadata tail included, does not start with 0xEF, holds no SELFDESTRUCT in its instruction stream outside push data, and every immutable range lies inside one push's data.
…in holds

The reservation core no longer keeps protocol debt or places stand-in holds:
holds need full availability, captures past the hold and charges pay only from
the owner's free balance, refunds are paid wholly by the caller, and payee terms
shrink to a capture tolerance (setCaptureTolerance).

- IReservationCore and MockReservationCore follow the new interface, error order,
  events and balance moves.
- CashSource takes free cash past a hold and nothing more; the issuer absorbs
  the rest, which stays in the settlement net. The debtor list, its prune and
  the settlement-token guard are gone.
- CardAuth, CardLegs and ISource drop the STAND_IN flag, stand-in holds,
  CAPTURE_BEYOND and owed(); the purchase word keeps open and charged flags.
  A network stand-in is booked after the fact with charge.
- IssuerTreasury records payOut advances as its own receivable (advanceOf),
  repaid through repayAdvance and carried across a settlement token change.
- IssuerDesk takes a merchant win back from free cash and savings and records
  the rest as a receivable; collectReceivable takes only free funds.
- AccountLifecycle, Rewards and ReceiveSweep no longer read or repay debt.
- Tests, the stress suite and the differential harness follow; the trace
  replay is skipped until the traces are regenerated on the new node.
Record five seeds of 300 operations each against a dev node built from the
reservation core without protocol debt or stand-in holds (tempo 2ec88c1e), with
the state vector StateReader now reads, and replay them against
MockReservationCore again. 1,500 operations match with no node invariant
failures and no change to the mock; together they meet every coverage minimum
the replay lists.
@Slokh Slokh changed the title feat(cards): cards branch (tracking) feat(cards): card programs on the reservation core (tracking) Nov 22, 2026
Slokh added 17 commits November 22, 2026 16:47
Move the card programs into the single Foundry project's spend domain:
sources to src/spend/programs/, interfaces to src/interfaces/spend/programs/,
tests (harness, stress, differential traces, venues) to test/spend/programs/,
and the gas snapshots to snapshots/. Imports of Earn use relative paths, the
root foundry.toml gains the program tests' read permissions, the lint scope
covers src/spend/programs, and spend.yml checks the program gas snapshots.
main compiles with solar f1b75c6 (previously e7a91fc) and its Earn vault
and engines are cheaper. With the previous solar the program bytecode
is unchanged apart from metadata and library placeholders, CompanionGas
matches its old snapshot, and AuthGas differs only on the savings paths.
Add CardAuth.bookStandIn(card, ref, amount, merchant), which books a purchase
the network approved without asking once it clears. It runs charge's path,
under a new reference or late on a purchase whose hold ended, and counts
toward the card's and owner's limits and the merchant's mandate without
being refused by them, as tips past the hold already count. The operator
key's cap, a revoked merchant, the exposure guard and, under a new
reference, a card that cannot start a purchase still refuse it.

charge keeps its selector and behaviour: a force post under a new reference
is still refused past the limits. bookStandIn takes the same four static
arguments (selector 0x57676f56), so a payment-call template lists it with
charge's gas cap; PaymentCallShape pins it.
…etwork paid

Funding versions:
- setFunding writes a new 32-bit version each time and never rewrites one,
  so every purchase keeps the order it was placed under. An ended purchase
  records its whole version where its amount was (it then equals what it
  captured); an open one keeps the version's low 8 bits.
- CardAuth counts each owner's open purchases and the version the oldest
  may date from (fundingState), and setFunding refuses a version 256 past it
  (FundingInUse) until those purchases end. fundingVersion(address) becomes
  fundingState(address) returning (version, openFrom, open); fundingOf and
  FundingSet take a uint32 version.

Network-paid amounts:
- bookStandIn, a late charge on an ended purchase and every capture are
  booked whatever the exposure guard, the card's or account's state, the
  identity rules or the grant say: the network already paid, so refusing
  only kept the debt out of the net. Only the operator's cap (and a card
  never issued) refuses them. The owner's free cash still pays what it can.
- A booking at a merchant the owner revoked is absorbed by the issuer in
  full and not counted toward the owner's limits. Late bookings read the
  merchant a mandate recorded for the purchase and ignore the caller's.
- A force post (charge under a new reference) is still admitted like an
  authorization and refused by the limits, a revoked merchant and the guard.

Credit backs:
- What the issuer absorbed is recorded per purchase beside what credit backs
  added back to settlement, and negative settles stay within what was
  actually refunded.

Tests: FundingVersions and NetworkPaidBooking cover the above; StandInBooking,
AbsorbedExposure and CardAuthBounds now expect the bookings to land;
CardAuth and AuthGas count the funding-state slot; PaymentCallShape measures a
steady one-leg authorize with the treasury guard armed at 16 pledges and 8
cash sources (1,345,541 of the 1,500,000 lane cap). The weekend stress books
stand-ins with bookStandIn and asserts none is refused.

PaymentCallShape's opcode scan now reads the trailing metadata length instead
of assuming solc's: solar writes a 75-byte map, so the scan read its hash as
instructions and failed whenever the hash held a CALLCODE byte.
CashSource records the place of a converted leg's token in its lock word, so releasing a leg whose hold the core already ended takes its open value off that token's total rather than the token the program's position names. Live legs are held, captured and released in their hold's token, and a lock kept for a late charge records its token, so a late charge in another token prices at the venue instead of against the old lock. No new storage per hold.
IssuerDesk tries the vault redeem like the core charge before it: when the vault cannot redeem at once, the shares go back to the cardholder and their value stays owed as a receivable, so the dispute still closes.
…ilence

IssuerTreasury records when the sponsor last acknowledged, checkpointed, seized or released (packed into the collateral slot). Once the sponsor has not acted for SPONSOR_SILENCE (180 days), no collateral is live and nothing is seized, the issuer may hand the guard on although the program is still exposed, and then acknowledges the settlement itself. An active sponsor keeps the guard by acting at least that often.
setFunding refused once 255 versions passed the version a run of overlapping purchases began at, even when every open purchase was recent. Open purchases are now counted in two counters by the parity of their version's window of 128, and setFunding refuses only to start a window while a purchase from the window two back is open. Open purchases stay within 255 versions of the latest, so their low 8 bits still name them exactly.
…ff the guard

A sponsor that seized any amount and then stopped acting kept the exposure guard and the issuer's committed funds for good. Once the sponsor has been silent for SPONSOR_SILENCE and no collateral is live, the issuer may hand off even with something seized; the seizure counts as applied (SeizedApplied) and seized returns to zero. A sponsor that keeps acting keeps every right over its seizures.
@Slokh Slokh closed this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant