Skip to content
Resvary. 0.3 alpha
Menu
Run the live demo

Prepaid credits and usage billing for AI products

Open source · 0.3 alpha

Reserve a maximum cost before an AI job runs. Charge the actual usage when it finishes. Release the rest and give users an auditable receipt.

Apache-2.0 TypeScript · Embedded SDK SQLite alpha backend
01 / Problem

AI usage has a timing problem

You must decide whether a customer can start an AI request before the final cost exists. Tokens, seconds, images, and tool calls arrive after the provider finishes.

Resvary checks available credits and creates a reservation before provider work begins. It commits the final charge after execution and releases the unused amount.

  • 01Concurrent jobs can spend the same apparent balance.
  • 02A retried request can create a duplicate charge.
  • 03Failed jobs can leave credits locked without an explicit release.
  • 04Mutable prices make old charges hard to explain.
  • 05A balance snapshot cannot show why the number changed.
02 / Credit lifecycle

One lifecycle from authorization to receipt

Fund → Reserve → Execute → Commit → Release → Receipt
STEP 01

Fund the account

Grant product credits from your application or confirm an external funding payment.

STEP 02

Reserve the maximum cost

Rate the estimated usage against an immutable price version and hold that amount before expensive work begins.

STEP 03

Run the AI operation

Call a model, agent, generation pipeline, tool, or batch worker with your existing provider stack.

STEP 04

Commit actual usage

Rate the provider's final usage, charge it once, and release the unused part of the reservation in the same transaction.

STEP 05

Record the result

Store an immutable ledger entry, usage receipt, idempotency result, and outbox event for reconciliation.

03 / Why Resvary

The credit boundary around each AI call

Authorize spend before execution

Resvary checks available credits and creates an atomic reservation before your application starts provider work. Overlapping requests cannot reserve the same credits twice when the store supplies the required transaction isolation.

Charge once across retries

Every mutating command requires an idempotency key. Replaying the same key and payload returns the original result. Reusing the key with different input raises a conflict.

Explain each balance change

Immutable ledger entries and per-charge usage receipts record the price version, line items, amount charged, amount released, and balance after the operation.

Keep payment rails separate from usage

The credit lifecycle does not depend on checkout, wallets, or an AI provider. Your application can fund the same ledger through manual grants, Arc USDC payments, or another adapter without changing usage accounting.

Usage receipt

Each commit records its own explanation

The usage receipt records the price version, line items, final charge, released credits, and resulting balance. Your team can trace each balance change without reconstructing it from logs.

Resvary ledger 0.3 alpha
Reserving credits
Resvary · usage receipt 0.3 alpha
RECEIPTrcp_8f42c1
ACCOUNTacct_studio_04
METERtokens.chat
PRICE VERSIONpv_7
INPUT · 18,400 tok0.055200
OUTPUT · 2,440 tok0.073200
RESERVED$0.400000
CHARGED$0.128400
RELEASED$0.271600
BALANCE AFTER$4.871600
IDEMPOTENCY req_5c9d0e7a3b COMMITTED 2026-08-14 09:41:02Z LEDGER le_1183 · le_1184
04 / Included in alpha

Credit primitives that survive retries

  • +Closed-loop USD product credit accounts
  • +Six-decimal integer credit arithmetic
  • +Multi-dimensional usage meters
  • +Immutable price versions
  • +Estimated-usage reservations
  • +Actual-usage commit and release
  • +Expiring open reservations
  • +Persistent idempotency records
  • +Append-only ledger entries
  • +Per-charge usage receipts
  • +Manual grants and explicit adjustments
  • +Transactional outbox events
  • +Signed credit webhook payloads
  • +In-memory and SQLite stores
  • +Arc Testnet USDC funding adapter
  • +Next.js and Express starter generation
  • +Stablecoin receipt and x402 compatibility modules
05 / Usage pricing

Price the usage your provider returns

A meter can rate one or more integer dimensions. Each immutable price version keeps old receipts tied to the rates used at the time of the charge.

The alpha supports linear multi-dimensional rates. Tiering, packages, subscriptions, monthly minimums, and allowances are outside the current scope.

LLM chat
input tokens · output tokens
Image generation
images · compute seconds
AI agents
tool calls · steps · runtime
Speech and video
seconds · minutes processed
Batch jobs
items · pages · completed jobs
Developer APIs
requests · domain-specific units
06 / TypeScript SDK

Wrap each provider call in a metered lifecycle

runMetered reserves estimated usage, runs your provider callback, commits the final charge, and returns the released amount with a receipt.

metered-request.ts
import { CreditLedger } from '@resvary/sdk/credits';
import { createSqliteCreditStore } from '@resvary/sqlite';

const credits = new CreditLedger({
  projectId: 'my_ai_product',
  store: createSqliteCreditStore({
    path: '.resvary/resvary.sqlite',
  }),
});

const result = await credits.runMetered(
  {
    customerId: 'customer_123',
    priceId: 'price_llm_v1',
    estimatedUsage: {
      input_tokens: '2000',
      output_tokens: '1000',
    },
    idempotencyKey: 'request_abc',
  },
  async () => {
    const completion = await callModel();

    return {
      value: completion,
      usageEventId: completion.id,
      actualUsage: {
        input_tokens: String(completion.usage.inputTokens),
        output_tokens: String(completion.usage.outputTokens),
      },
    };
  },
);

console.log(result.receipt.amount);
console.log(result.receipt.releasedAmount);

If the provider throws, runMetered releases the full reservation. If provider execution succeeds but the commit fails, the reservation stays open so your application can retry the same commit without giving away completed usage.

The packages currently live in the Resvary monorepo. Use the setup guide until public package releases are available.

07 / Demo

Run the credit lifecycle in one demo

The deterministic demo needs no AI key. Grant credits, run a request, replay it without a second charge, or trigger a provider failure and inspect the stored result.

Run the interactive demo
Demo actions
  • Grant $5 in development credits
  • Run a simulated AI operation
  • Replay the same request
  • Simulate provider failure
  • Simulate an Arc Testnet funding confirmation
Data exposed
  • Posted, reserved, and available balances
  • Reservation status
  • Actual charge and released amount
  • Price line items
  • Immutable ledger history
  • Usage receipts
  • Transactional outbox events
  • Signed event headers
08 / Use cases

Add prepaid credits to variable-cost AI workloads

AI SaaS

Sell prepaid product credits while keeping subscriptions, checkout, and invoices in your existing billing stack.

AI APIs

Authorize requests before execution and reconcile each customer charge to provider usage.

Agent platforms

Reserve a budget for an agent run, then charge for its final steps, tools, tokens, or runtime.

Generation products

Rate images, audio, video, or batch jobs with units that match your provider costs.

Paid developer tools

Give teams auditable credit balances and retry-safe usage charges without building a ledger from scratch.

09 / Transactions

Balance changes stay inside one transaction

Each balance-changing command validates idempotency, checks the account and lifecycle state, writes ledger entries, updates the account snapshot, stores the domain record and outbox event, and saves the command result before commit.

The SQLite store uses BEGIN IMMEDIATE to serialize competing writers. It stores balances, reservations, receipts, idempotency results, and outbox events across restarts.

SQLite supports local, single-node, and design-partner deployments in the current alpha. Multi-process production deployments should use a custom CreditStore with equivalent transaction isolation or wait for the planned Postgres adapter.

Balance definitions
Posted Granted credits minus committed charges
Reserved Credits held by open reservations
Available Posted minus reserved
Arc USDC funding

Arc USDC is Resvary's reference and first-class external funding path. The adapter creates an invoice, validates its payment receipt, and grants credits once for each network + transaction hash pair. Usage accounting remains payment-rail agnostic.

Arc invoice → memo proof → payment receipt → funding confirmation → credit grant
A payment receipt proves which external transfer funded an account. A usage receipt explains why product credits were charged.

The current Arc integration is Testnet-first development infrastructure.

10 / Credit model

A credit balance needs a transaction lifecycle

Capability Balance column Resvary 0.3 alpha
Available balance snapshotYesYes
Atomic pre-request reservationCustom workIncluded
Actual-usage commit and releaseCustom workIncluded
Retry-safe mutating commandsCustom workIncluded
Immutable price historyCustom workIncluded
Per-charge usage receiptsCustom workIncluded
Append-only ledger entriesCustom workIncluded
Transactional outbox eventsCustom workIncluded
Funding rail independenceDepends on implementationIn the domain model
11 / Alpha boundary

Know the alpha boundary before you integrate

Resvary 0.3 includes the embedded credit domain, SQLite persistence, starter integration, and Arc Testnet funding. Hosted billing, Postgres, and multi-node deployment remain planned work.

Supported boundary
  • Credits belong to one merchant project
  • Credits cannot move between users
  • Users cannot redeem or cash out credits
  • Resvary does not custody customer funds
  • Usage receipts are operational records, not tax invoices
Not in the current alpha
  • Hosted dashboard or managed API
  • Postgres adapter
  • Multi-node deployment support
  • Subscription management · checkout UI
  • Tax calculation or tax invoices
  • Transferable balances · cash redemption
  • Marketplace wallets
  • Enterprise SLA or compliance certification
Planned direction
  • Postgres persistence
  • Self-hosted HTTP service
  • Hosted operations and delivery tooling
  • Access control and operator workflows
  • Analytics and reconciliation views

Roadmap items, not available features.

12 / Open source

Keep the credit ledger inside your application

Run the Apache-2.0 TypeScript code inside your application. Inspect the balance rules, run the tests, use the store interface, and keep product usage in your infrastructure.

Repository components
@resvary/sdk/credits Accounts, grants, reservations, usage receipts, ledger, idempotency, outbox
@resvary/sdk/pricing Meters, immutable price versions, integer usage rating
@resvary/sdk/funding/arc Arc payment receipt to credit grant adapter
@resvary/sqlite Persistent credit and payment receipt stores
@resvary/sdk/receipts Stablecoin invoices, proofs, payment receipts, signed webhooks
@resvary/sdk/middleware Compatible legacy x402 middleware for Express and Next.js
create-resvary Starter generator for prepaid AI credit applications
13 / Access

Run the open-source alpha or request an integration review

Run Resvary in your application today. Design-partner reviews are available for a small number of AI teams. A managed service remains a roadmap item with no launch date or price.

Open-source alpha Apache-2.0 Source available now
  • Full credit ledger and pricing engine
  • SQLite store, embedded or as a service
  • Arc funding adapter and signed webhooks
  • No usage caps, no telemetry, no vendor account
  • Community support through GitHub issues
Open the repository
Design partner Alpha review Limited slots during 0.3 alpha
  • Everything in self-hosted
  • Direct channel to the maintainers
  • Integration review of your metering model
  • Influence over the Postgres adapter and API surface
  • Migration help when the schema changes
Request an alpha review
Managed service Planned Roadmap, no launch date
  • Hosted ledger with managed backups
  • Operator console and audit exports
  • Reconciliation and analytics views
  • Uptime commitments and support terms
  • Same SDK, no application rewrite
Not available yet
What you operate in the current alpha
ConcernYou run itManaged service, when available
Data location Usage and balances never leave your infrastructure Ledger stored on Resvary infrastructure
Store SQLite today; a Postgres adapter is planned Managed Postgres with backups
Upgrades You pin versions and apply schema migrations Rolling upgrades with versioned API guarantees
Availability Your deployment, your monitoring and on-call Support terms and uptime commitments
Payments Your processor and Arc keys, your merchant terms Unchanged — Resvary never holds customer funds
Cost Your compute and storage only To be announced

Managed cloud is a roadmap item. No hosted plan, contract, or price exists today.

14 / FAQ

Questions engineers ask first

Is Resvary a payment processor?

No. Resvary manages closed-loop product credits and usage authorization. Keep checkout, subscriptions, tax, and fiat payment processing in the systems you already use.

Does Resvary replace Stripe Billing, Lago, or Orb?

Resvary handles the real-time credit boundary around an AI operation. A broader billing platform can continue to handle checkout, subscriptions, invoicing, or finance workflows.

Why reserve credits before the AI request?

The final provider cost arrives after execution. A reservation prevents concurrent requests from spending the same available balance while keeping the final charge tied to actual usage.

What happens when the provider fails?

runMetered releases the full reservation when the provider callback throws. The account keeps its posted credits.

What happens if commit fails after the AI request succeeds?

The reservation stays open. Retry the commit with the same idempotency key to record the completed usage without charging twice.

Can an actual charge exceed its reservation?

No. Your application must create another reservation before continuing work that needs a higher limit.

Can I use my existing AI provider?

Yes. The core ledger does not depend on a model vendor. Your application passes estimated and actual usage into the SDK.

Do I need crypto or Arc to use Resvary?

No. Manual grants can fund an account without a blockchain. Arc USDC is the reference external funding path and does not change the usage ledger.

Is SQLite production-ready?

The current SQLite adapter targets local, single-node, and design-partner deployments. Multi-process production deployments need a store with equivalent transaction isolation. A Postgres adapter is planned.

Are credits transferable or redeemable?

No. Resvary models non-transferable, non-redeemable product credits that customers use inside one merchant project.

Is a usage receipt a tax invoice?

No. A usage receipt explains an operational credit charge. Each merchant remains responsible for its customer terms, refund policy, privacy notice, invoices, and tax treatment.

Is Resvary free to use?

The current code is available under the Apache-2.0 license. No hosted paid plan exists yet.

How do I try the alpha?

Run the deterministic demo without an AI key, or open the repository and follow the getting-started guide.

Add a retry-safe credit ledger to your next AI request

Run the lifecycle in the demo, then evaluate the open-source SDK inside your application.