Skip to content
horn111Public

About

Open-source prepaid credits and usage billing for AI products. Reserve spend, charge actual usage, and issue auditable receipts.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Latest commit

 

History

194 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Resvary logo

Resvary

Open-source prepaid credits and usage billing for AI products.

ETHOnline 2026 Continuity participant

Resvary gives AI applications a durable balance ledger and a safe request lifecycle:

grant or top up credits
→ reserve the maximum cost
→ execute the AI job
→ charge actual usage
→ release the remainder
→ issue an auditable usage receipt

Resvary keeps credit accounting separate from settlement. Arc is the reference network for external USDC funding: direct Arc transfers and Circle Gateway Nanopayments fund the same ledger. The Operator Console explains balances and supports guarded recovery without manual SQL. Version 1.3 adds durable-operation recovery with saved usage evidence, transition history, and replayable commands.

The agent demo runs on Arc Mainnet. Each IP receives three lifetime sponsored runs; later runs require a signed-in wallet and prepaid credits funded through a verified Arc USDC transfer. Read the Mainnet payment and usage evidence for a maintainer's completed run and the limits of that verification.

Why Resvary

AI costs are known only after a model or tool finishes. A single balance -= cost update is not enough when requests retry, overlap, fail, or report usage late.

Resvary provides:

  • USD-denominated credits with six-decimal integer arithmetic;
  • multi-dimensional prices for tokens, seconds, images, jobs, or tool calls;
  • mixed linear, graduated, and package pricing with integer-only rating;
  • atomic reserve → commit/release operations;
  • idempotency for grants, reservations, charges, and funding confirmations;
  • UTC allowance policies and one-time expiring promotional grants;
  • deterministic credit-lot priority and per-charge allocations;
  • immutable ledger entries and per-charge usage receipts;
  • transactional outbox events using the existing x-resvary-signature format;
  • in-memory, SQLite, and Postgres stores;
  • a lease-based outbox worker with retry and dead-letter recovery;
  • a self-hosted, single-project Operator Console with an audit explorer and guarded recovery actions;
  • direct Arc Mainnet and Testnet USDC top-ups with durable watcher recovery;
  • Circle Gateway Nanopayment top-ups through the official batching facilitator;
  • an interactive Next.js demo and Express/Next.js starter generator.

Quickstart

npm install @resvary/sdk @resvary/sqlite
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 meter = await credits.registerMeter({
  key: 'llm_tokens',
  dimensions: ['input_tokens', 'output_tokens'],
  idempotencyKey: 'meter-v1',
});

const price = await credits.createPriceVersion({
  meterKey: meter.key,
  rates: [
    { dimension: 'input_tokens', unitSize: '1000', amount: '0.002' },
    { dimension: 'output_tokens', unitSize: '1000', amount: '0.008' },
  ],
  idempotencyKey: 'price-v1',
});

await credits.grantCredits({
  customerId: 'customer_123',
  amount: '5',
  idempotencyKey: 'signup-credit:customer_123',
});

const result = await credits.runMetered(
  {
    customerId: 'customer_123',
    priceId: price.id,
    estimatedUsage: { input_tokens: '2000', output_tokens: '1000' },
    idempotencyKey: 'request_abc',
  },
  async () => {
    const completion = await callYourModel();
    return {
      value: completion,
      actualUsage: {
        input_tokens: String(completion.usage.inputTokens),
        output_tokens: String(completion.usage.outputTokens),
      },
      usageEventId: completion.id,
    };
  },
);

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

runMetered stores an execution claim before it calls the provider. Concurrent matching calls on one CreditLedger instance wait for the first execution; calls through another instance receive MeteredExecutionAlreadyClaimedError instead of calling the provider again. Pass the same key to the provider when it supports idempotent requests.

runMetered checks the reservation's status and expiry in the same transaction that records its execution claim. An expired reservation releases its remaining hold without starting the provider callback. This check does not extend the reservation TTL or keep it open while the provider runs.

If the callback throws, runMetered releases the reservation and keeps the claim. Start a new operation only after confirming the provider did not complete the first one, or when a duplicate result is acceptable. Save a successful provider result and its usage inside the callback, before returning to the credit commit. After a commit failure, retry commitUsage with the saved usage event and commit key only while the reservation remains open and unexpired. A committed event replays its receipt. If the reservation expired or was released, reconcile the saved result and charge explicitly; do not call the provider again or assume that the old hold can still be charged.

For a multi-process deployment, install Postgres persistence and apply migrations before the application starts:

npm install @resvary/postgres @resvary/worker
DATABASE_URL=postgres://... npx resvary-postgres migrate

See the production persistence guide before moving an existing SQLite database.

Operator Console

The production path uses PostgreSQL and runs its migration as an explicit deployment step:

export POSTGRES_PASSWORD='replace-with-a-database-password'
export RESVARY_PROJECT_ID='my_ai_product'
export RESVARY_CONSOLE_ADMIN_SECRET='replace-with-at-least-32-random-characters'
docker compose -f docker-compose.console.yml up -d

The console shows balances, customer timelines, usage evidence, overdue reservations, outbox failures, funding reconciliation, and the append-only operator action log. Operators can reconcile saved operation results, record evidence for unknown outcomes, grant credits, make reasoned adjustments, sweep overdue reservations, and requeue dead letters. Recovery commands bind to reviewed evidence and stable action IDs. One instance serves one project.

Resvary Operator Console showing balances, ledger events, and a usage-receipt evidence chain with synthetic demo data

Operator Console with synthetic demo data.

See the Operator Console guide, operation recovery guide, and 1.3 migration guide.

ETHOnline 2026 agent demo

The Agent Demo supports sponsored and visitor-funded document analysis. Three lifetime runs per IP use the sponsored Circle Agent Wallet and Gateway path. Later runs require wallet sign-in and a direct Arc Mainnet USDC credit deposit. Resvary reserves up to 0.347392 credits, charges measured agent and analysis usage, releases the unused amount, and returns a receipt. Paid runs cannot spend the sponsor wallet.

The archived proof covers the former Circle Testnet path. The separate Mainnet evidence covers an existing direct wallet deposit and paid run, verified against Arc RPC and the production ledger. It does not establish Mainnet Gateway replay behavior or external customer adoption. The production operations guide describes deployment gates, monitoring, and retention checks.

Arc settlement for external USDC funding

Arc provides Resvary's reference settlement path for external USDC funding. Install the Circle integration package to accept direct Arc Mainnet or Testnet transfers and Circle Gateway Nanopayments:

npm install @resvary/circle
import { ARC_GATEWAY_MAINNET, GatewayNanopaymentFunding } from '@resvary/circle';

const funding = new GatewayNanopaymentFunding({
  ledger: credits,
  sellerAddress: '0x1111111111111111111111111111111111111111',
  network: ARC_GATEWAY_MAINNET,
});

const request = await funding.createFundingRequest({
  customerId: 'customer_123',
  amount: '5',
  idempotencyKey: 'topup_123',
});

Both paths create closed-loop credits after Resvary verifies external payment evidence. The Gateway path calls the official Circle facilitator to verify and settle the authorization. The direct path verifies the Arc transaction and Memo-wrapped USDC transfer. See the direct Arc and Gateway guides for the complete server flows.

Demo

Requires Node.js 24 because the persistent demo uses the built-in node:sqlite module.

npm install
npm run dev

Set a local admin token, start the demo, and enter the same token in the UI. Mutating demo actions fail closed when the token is missing.

RESVARY_DEMO_ADMIN_TOKEN=replace-with-a-long-random-token
RESVARY_WEBHOOK_SECRET=replace-with-a-different-long-random-token

Open http://localhost:3000. The flow is deterministic and never sends a request to an external AI provider.

The old payment operations APIs remain under /api/receipts, /api/receipts/proof, and /api/webhook-inbox. Receipt signing and webhook ingestion stay disabled until RESVARY_WEBHOOK_SECRET is configured.

Modules

Import Responsibility
@resvary/sdk/credits Accounts, grants, reservations, usage receipts, ledger, idempotency, outbox
@resvary/sdk/admin Framework-neutral admin queries and guarded operator command service
@resvary/sdk/pricing Immutable linear, graduated, and package usage rating
@resvary/sdk/funding/arc Direct Arc invoice/payment receipt to credit grant adapter
@resvary/sdk/funding Durable Arc funding worker
@resvary/circle Circle Gateway Nanopayments and HTTP handlers
@resvary/sqlite Persistent credit and payment receipt stores
@resvary/postgres Multi-process stores, schema migrations, health and SQLite import
@resvary/worker Lease-based signed webhook delivery, retry, dead letter and worker CLI
@resvary/sdk/receipts Stablecoin invoices, proofs, payment receipts, signed webhooks
@resvary/sdk/middleware Compatible legacy x402 Express and Next.js paywalls

UsageMeter and createBillingPlan remain available for compatibility but are deprecated. New integrations should use the credit ledger and versioned pricing.

Guarantees and limits

  • Money is never calculated with JavaScript floating point in the new engine.
  • A project/customer account cannot have a negative available balance.
  • SQLite mutations use BEGIN IMMEDIATE and store the balance change, receipt, idempotency result, and outbox event together.
  • Credits are closed-loop product credits. Resvary does not support user-to-user transfer, cash-out, redemption, custody, tax invoices, subscriptions, or marketplace balances.
  • SQLite remains a local and single-node backend. Postgres 16–18 is the recommended backend for multi-process deployments.
  • Outbox delivery is at least once. Webhook consumers must deduplicate by x-resvary-event-id.
  • Postgres migrations are explicit deployment steps and never run when a store is constructed.
  • Expired promotional credits are excluded transactionally. Reserved promotional units may still commit after expiry; released expired units burn instead of returning to available.
  • Direct Arc and Gateway adapters support Mainnet and Testnet. Mainnet use moves real USDC and requires application-level limits, authentication, monitoring, and legal/compliance review.
  • Resvary stores authorization hashes and normalized evidence, never buyer private keys or full Gateway signatures.

Documentation

Development

npm install
npm run typecheck
npm run test --workspaces --if-present -- --reporter=dot
npm run build

The project is Apache-2.0 licensed. See SECURITY.md before reporting a vulnerability.


Website · Documentation · X / @resvaryAI · Product Hunt · ETHOnline showcase

About

Open-source prepaid credits and usage billing for AI products. Reserve spend, charge actual usage, and issue auditable receipts.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages