isLoading: boolean and error: Error | null (see Introduction); the sections below list each hook’s specific returns.
Two denominations
Every wallet has adenomination that decides how to render its balance and which top-up shape it accepts:
'unit'— raw counts like “AI Credits” or API calls. Render5,000 credits; auto-topup usesmode: 'package'.- A fiat code (
'usd','eur', …) — a prepaid money balance withminorUnitScaledecimal places. Render$50.00; auto-topup usesmode: 'amount'.
denomination; never mix the two formatters. A wallet balance is the credit wallet balance — unrelated to metered entitlement remaining (use entitlements for that).
useCreditAccounts
Returns every credit account (wallet) the customer holds — one per credit currency — each already carrying itsbalance, currency metadata, active grants, and auto-topup config. No second round-trip is needed for the typical wallet UI.
Parameters
string
Optional. Defaults to the customer set on
<UnitPayProvider>. Pass an explicit id only to read a different customer’s wallets.accounts—CreditAccount[]— all wallets for the customer (one per currency), or[]while loading or when the customer has no wallet yet. Render as a list of wallet cards.
useCreditCurrencies
Returns the org-wide list of active credit currencies the merchant has configured. Use it to build a “Wallets you can fund” picker when the customer hasn’t engaged any wallet yet (i.e.useCreditAccounts returns []). Admin-managed, so this list is read-only and cached aggressively.
Parameters — takes no arguments; the list is org-scoped, resolved from the <UnitPayProvider> context.
Returns
currencies—CreditCurrency[]— every active credit currency configured on the org, or[]while loading.
The first
useAutoTopUp set() or first useTopUp topUp() call on an unengaged currency auto-creates the credit_account server-side.useTopUp
Refills the customer’s credit wallet by a free-form amount. The server dispatches on customer state — PLG with a payment method charges inline, SLG appends the top-up to the next invoice — and returns aSettleOutcome you wire to your UX with on* callbacks.
Parameters — useTopUp(options?) accepts an optional HandleSettlementOptions object of settlement callbacks (onChargedInline, onInvoiceAdded, onRequiresForm, onNoAction, …). Each server outcome maps to exactly one; unhandled ones are silent no-ops. The returned topUp(input) alias takes:
string
required
The wallet currency to refill. Auto-creates the
credit_account server-side if the customer hasn’t engaged this currency yet.number
required
Amount to add, in minor units of the currency’s denomination (
unit credits or fiat).string
Override the auto-generated
Idempotency-Key. Auto-generated by default.boolean
Force the inline
<PaymentForm> even when a payment method is on file.PLG customers with no payment method throw
TOPUP_REQUIRES_PM (402) — route the customer to payment-method setup first.topUp alias for mutateAsync:
topUp(input)—(input: UseTopUpInput) => Promise<SettleOutcome>— performs the top-up; theoptionscallbacks fire automatically on success.isPending/data— standard mutation state (isPendingwhile in flight,datais the lastSettleOutcome).
useBuyCreditPackage
Purchases a fixed-SKU credit package. LikeuseTopUp, the server dispatches on customer state — PLG with a payment method charges inline, SLG appends to the next invoice — and returns a SettleOutcome you wire to your UX with on* callbacks. A package is a pre-configured SKU (its credit amount, price, and target wallet are fixed merchant-side), so you only pass the package id.
Parameters — useBuyCreditPackage(options?) accepts an optional HandleSettlementOptions object of settlement callbacks (same set as useTopUp). The returned buyCreditPackage(input) alias takes:
string
required
The credit package SKU to purchase.
string
Override the auto-generated
Idempotency-Key. Auto-generated by default.boolean
Force the inline
<PaymentForm> even when a payment method is on file.PLG customers with no payment method throw — route the customer to payment-method setup first.
buyCreditPackage alias for mutateAsync:
buyCreditPackage(input)—(input: UseBuyCreditPackageInput) => Promise<SettleOutcome>— performs the purchase; theoptionscallbacks fire automatically on success.isPending/data— standard mutation state.
useAutoTopUp
Manages the auto-topup rule for one credit currency. Reads piggyback onuseCreditAccounts (no extra fetch — autoTopup and autoTopupRuntime are already inline on each wallet row); set() and disable() upsert the rule and re-fetch the wallet so the card reflects the new state immediately.
The wallet’s denomination decides the rule shape: 'unit' (SKU credits) → set({ mode: 'package', … }); a fiat code → set({ mode: 'amount', … }). The server validates mode against the target currency’s denomination. All monetary fields (threshold, topupAmount, monthlyChargeLimit) are minor units of that denomination.
Parameters
string
required
The wallet currency whose auto-topup rule to manage.
rule—AutoTopupConfig | null— current config (enabled,threshold,packageId,amount,monthlyChargeLimit), ornullwhen nocredit_accountexists for this currency yet.runtime—AutoTopupRuntime | null— derived counters (lastFiredAt,lastFailedAt,consecutiveFailures,totalFiresCount,isPending,monthToDateCharge), ornullwith no account.effectiveFundingMethod—'charge_automatically' | 'send_invoice' | null— how the next auto-fire will fund (PSP off-session charge vs. one-off invoice), derived from the customer’s collection method.currency—CreditAccountCurrency | null— the wallet’s currency metadata, ornullwhen the customer hasn’t touched this currency yet. Usecurrency.denominationto pick the form variant without a second hook call.denomination—'unit' | 'usd' | … | null— convenience accessor forcurrency?.denomination.set(input)—(input: SetAutoTopUpInput) => Promise<AutoTopUpRule>— upserts the rule (auto-creates the credit account if missing).inputis a discriminated union onmode(see below).disable()—() => Promise<void>— soft-disables the rule, keeping the rest of the config so a later re-enable pre-fills.isMutating—truewhile aset()ordisable()is in flight.
set(input) fields:
'package' | 'amount'
required
'package' for unit-denominated wallets (buy a fixed SKU); 'amount' for fiat wallets (refill a free-form $ amount).string
required
mode: 'package' only. The SKU to auto-purchase when the balance drops below threshold.number
required
mode: 'amount' only. Amount to add per fire, in minor units of the fiat denomination.number
required
Balance (minor units) at or below which the rule fires.
number
Optional cap (minor units) on total auto-topup spend per calendar month.
null to clear.boolean
Optional. Defaults to enabled on upsert; set
false to stage a disabled rule.useTopupHistory
Reads the customer’s top-up attempt log — manual, auto, and sweeper-replay attempts unified in one append-only feed. This table is the runtime source of truth behind the auto-topup counters (last-fired, consecutive failures, monthly cap usage). ParametersTopupHistoryFilters
Optional filter object. All fields are optional; omit it for the full history.
string
Scope to a single wallet currency.
'pending' | 'succeeded' | 'failed' | 'skipped'
Filter by attempt status.
'auto' | 'manual' | 'sweeper_replay'
Filter by what triggered the attempt.
number
Page size. The server caps at 100.
string
Cursor from a previous page’s
nextCursor.attempts—TopupAttempt[]— the matching attempts (newest first), or[]while loading. Each row carriesstatus,triggerSource,fundingMethod,amount/chargeAmount,balanceAtFire,thresholdAtFire, optionalinvoiceId/paymentId, anderrorCode/errorMessage/skipReasonon non-success.nextCursor—string | null— pass tofilters.cursorto fetch the next page, ornullwhen none remain.
useCreditLedger
Reads the customer’s credit ledger — the append-only record of grant, consumption, expiry, and adjustment rows. Backed by an infinite query: pages accumulate,fetchNextPage walks the server cursor for you, and changing a filter resets pages cleanly. The caller never threads cursor state.
Parameters
CreditLedgerFilters
Optional filter object. All fields are optional; omit it to read the full ledger.
string
Scope to one wallet / credit account.
string
Scope to one currency (e.g. AI Credits) when the customer has many wallets.
string
Filter by the entry
type — credit, debit, hold, release, expire, or adjustment (matched case-insensitively). This is the type column, not the more specific reason.string
Source feature filter — narrows to consumption rows debited by one feature.
string
ISO datetime — inclusive lower bound on
createdAt.string
ISO datetime — inclusive upper bound on
createdAt.number
Page size. The server caps at 100.
entries—CreditLedgerEntry[]— flattened entries across all loaded pages, or[]while loading. Each entry’stypeis'CREDIT'(balance up) or'DEBIT'(balance down) — plus'HOLD'/'RELEASE'/'EXPIRE'/'ADJUSTMENT'— and a more specificreason(e.g.'GRANT','USAGE_DEDUCTION','PACKAGE_PURCHASE','EXPIRATION'), withamountand thebalanceBefore/balanceAftersnapshot.fetchNextPage()— loads the next page and appends it toentries. No-op whenhasNextPageisfalse.hasNextPage—boolean—truewhen more pages remain on the server.isFetchingNextPage—boolean—truewhile a subsequent page fetch is in flight.
See also
Credits overview
How grants, priority, FIFO consumption, and denominations work under the hood.
Entitlements & gates
Metered
remaining and feature access — distinct from wallet balance.Usage & analytics
Credit burn-rate and runway derived from the ledger.
Checkout
Preview a top-up or package purchase before charging.