### Development Setup and Checks Source: https://github.com/horn111/resvary/blob/main/README.md Run these commands in order to install dependencies, typecheck, test, and build the project. The test command uses npm workspaces and the dot reporter. ```bash npm install npm run typecheck npm run test --workspaces --if-present -- --reporter=dot npm run build ``` -------------------------------- ### Install dependencies and build the SDK Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Install all workspace dependencies, build the SDK package, and start the demo app. ```bash # Install all dependencies (workspaces) npm install ``` ```bash # Build the SDK npm run build --workspace=packages/sdk ``` ```bash # Start the demo app npm run dev --workspace=apps/demo ``` -------------------------------- ### Install Dependencies and Run Demo Source: https://github.com/horn111/resvary/blob/main/README.md Install dependencies and start the demo. Requires Node.js 24 because the persistent demo uses the built-in node:sqlite module. ```bash npm install npm run dev ``` -------------------------------- ### Install and migrate with npm and npx Source: https://github.com/horn111/resvary/blob/main/packages/postgres/README.md Install the SDK and Postgres packages, then run the migration CLI with a DATABASE_URL environment variable. Migrations must be applied before starting application, worker, or console processes. ```bash npm install @resvary/sdk @resvary/postgres DATABASE_URL=postgres://... npx resvary-postgres migrate ``` -------------------------------- ### Setup: Install dependencies and run demo server Source: https://github.com/horn111/resvary/blob/main/docs/demo-script.md Run the persistent demo with Node.js 24. Sets required environment variables and starts the demo workspace on port 3004. Every mutating demo request fails closed without the server-configured token. ```bash npm install $env:RESVARY_DEMO_ADMIN_TOKEN = 'replace-with-a-long-random-token' $env:RESVARY_WEBHOOK_SECRET = 'replace-with-a-different-long-random-token' npm run dev --workspace=@resvary/demo -- --port 3004 ``` -------------------------------- ### Install Postgres and worker packages Source: https://github.com/horn111/resvary/blob/main/README.md Install Postgres persistence and worker packages, then run migrations. ```bash npm install @resvary/postgres @resvary/worker DATABASE_URL=postgres://... npx resvary-postgres migrate ``` -------------------------------- ### Build core and run durable-operation-recovery example Source: https://github.com/horn111/resvary/blob/main/docs/migration-1.3.md Run the reproducible process-crash example after building the packages. It uses synthetic provider usage and a temporary SQLite database; assertions verify one provider call, one receipt, and the expected balance. ```bash npm run build:core node examples/durable-operation-recovery.mjs ``` -------------------------------- ### Install dependencies and run core tests Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Run from the repository root to install dependencies and execute core and agent-demo tests. ```sh npm ci --ignore-scripts npm run build:core npm test --workspace @resvary/circle npm test --workspace @resvary/agent-demo npm run build --workspace @resvary/agent-demo ``` -------------------------------- ### Install Resvary SDK and SQLite store Source: https://github.com/horn111/resvary/blob/main/README.md Install the core SDK and SQLite store packages via npm. ```bash npm install @resvary/sdk @resvary/sqlite ``` -------------------------------- ### Install @resvary/circle Source: https://github.com/horn111/resvary/blob/main/packages/circle/README.md Install the SDK and Circle adapter packages via npm. ```bash npm install @resvary/sdk @resvary/circle ``` -------------------------------- ### Scaffold a new Resvary application Source: https://github.com/horn111/resvary/blob/main/docs/getting-started.md Scaffold a new project with create-resvary version 1.3.1. Choose 'AI prepaid credits' and either Next.js or Express; the legacy x402 paid API starter is an alternate template. ```bash npx create-resvary@1.3.1 my-ai-product ``` -------------------------------- ### Start Operator Console with PostgreSQL and Docker Compose Source: https://github.com/horn111/resvary/blob/main/README.md Sets required environment variables and starts the console stack. Replace the password and admin secret with strong values; the admin secret must be at least 32 random characters. Run this as an explicit deployment step before using the console. ```bash 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 ``` -------------------------------- ### Run buyer example with Circle Gateway Source: https://github.com/horn111/resvary/blob/main/docs/circle-gateway-funding.md Runs the official Circle buyer client example against a top-up endpoint. Targets Mainnet by default; set RESVARY_GATEWAY_NETWORK=testnet for Testnet. RESVARY_GATEWAY_DEPOSIT moves USDC into Gateway, so use it only after confirming the selected network and amount. ```bash RESVARY_GATEWAY_BUYER_PRIVATE_KEY=0x... \ npx tsx examples/gateway-buyer.ts https://your-app.example/api/top-up ``` -------------------------------- ### Copy demo environment file Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Copy the example environment file for the demo app to .env.local. ```bash cp apps/demo/.env.example apps/demo/.env.local ``` -------------------------------- ### Install Circle Integration Package Source: https://github.com/horn111/resvary/blob/main/README.md Install the @resvary/circle package to accept direct Arc Mainnet or Testnet transfers and Circle Gateway Nanopayments. ```bash npm install @resvary/circle ``` -------------------------------- ### Resvary Receipts Quick Start: create invoice, record payment, sign webhook Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use this TypeScript example to set up a ReceiptLedger, create an invoice, record a payment, and sign the resulting webhook event. Requires an ARC_WEBHOOK_SECRET environment variable. The invoice memo is 'resvary:invoice:v1:inv_pro_plan_123', the receipt status is 'paid', and the signature header is 't=...,v1=...'. ```typescript import { ReceiptLedger, signWebhookEvent } from '@resvary/sdk/receipts'; const ledger = new ReceiptLedger(); const invoice = ledger.createInvoice({ id: 'inv_pro_plan_123', amount: '19.00', currency: 'USDC', payTo: '0x1111111111111111111111111111111111111111', customerId: 'team_123', description: 'Pro plan subscription', }); console.log(invoice.memo); // resvary:invoice:v1:inv_pro_plan_123 const receipt = ledger.recordPayment(invoice.id, { from: '0x2222222222222222222222222222222222222222', to: invoice.payTo, amount: '19.00', memo: invoice.memo, txHash: '0xabc' as `0x${string}`, }); const paidEvent = ledger.listWebhookEvents().at(-1)!; const signature = signWebhookEvent(paidEvent, process.env.ARC_WEBHOOK_SECRET!); console.log(receipt.status); // paid console.log(signature.header); // t=...,v1=... ``` -------------------------------- ### Install Circle Gateway Nanopayment SDK packages Source: https://github.com/horn111/resvary/blob/main/docs/circle-gateway-funding.md Install the required packages for Circle Gateway Nanopayment funding: @resvary/sdk, @resvary/circle, and @circle-fin/x402-batching. ```bash npm install @resvary/sdk @resvary/circle @circle-fin/x402-batching ``` -------------------------------- ### Upgrade packages to 0.4.0-alpha.0 Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.4.md Run these npm install commands to upgrade the SDK and SQLite packages together. The second command installs the Circle package. ```bash npm install @resvary/sdk@0.4.0-alpha.0 @resvary/sqlite@0.4.0-alpha.0 ``` ```bash npm install @resvary/circle@0.4.0-alpha.0 ``` -------------------------------- ### Run core and workspace tests from repository root Source: https://github.com/horn111/resvary/blob/main/apps/agent-demo/README.md Install dependencies and run the core build and test suites for the Circle and agent-demo workspaces. Requires Node.js 24 and a disposable PostgreSQL database whose name ends in `_test`. ```sh npm ci --ignore-scripts npm run build:core npm test --workspace @resvary/circle npm test --workspace @resvary/agent-demo ``` -------------------------------- ### Install and run the worker Source: https://github.com/horn111/resvary/blob/main/packages/worker/README.md Install the package and run the worker with required environment variables. Defaults: batch 25, lease 30 seconds, webhook timeout 10 seconds, maximum 8 attempts, exponential backoff with jitter. HTTP 2xx succeeds; network failures, timeout, 408, 429, and 5xx retry; other 4xx move to dead letter. ```bash npm install @resvary/worker DATABASE_URL=postgres://... \ RESVARY_WEBHOOK_URL=https://example.com/webhooks/resvary \ RESVARY_WEBHOOK_SECRET=replace-me \ npx resvary-worker run ``` -------------------------------- ### Persistent receipt ledger with SQLite store Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use the optional @resvary/sqlite package for local SQLite persistence. This example creates a SQLite receipt store at '.resvary/receipts.sqlite' and passes it to PersistentReceiptLedger. ```typescript import { PersistentReceiptLedger } from '@resvary/sdk/receipts'; import { createSqliteReceiptStore } from '@resvary/sqlite'; const store = createSqliteReceiptStore({ path: '.resvary/receipts.sqlite', }); const ledger = new PersistentReceiptLedger({ store }); ``` -------------------------------- ### Run agent-demo integration and e2e tests with TEST_DATABASE_URL Source: https://github.com/horn111/resvary/blob/main/apps/agent-demo/README.md Sets the PostgreSQL connection string, runs the agent-demo tests and build, then runs the e2e workflow tests with `AGENT_DEMO_TEST_EXECUTION_MODE=workflow`. The browser harness starts fixture services on `127.0.0.1:3100` and makes no external AI or payment request. ```powershell $env:TEST_DATABASE_URL='postgresql://postgres:PASSWORD@127.0.0.1:5432/resvary_agent_test' npm test --workspace @resvary/agent-demo npm run build --workspace @resvary/agent-demo $env:AGENT_DEMO_TEST_EXECUTION_MODE='workflow' npm run test:e2e --workspace @resvary/agent-demo Remove-Item Env:\AGENT_DEMO_TEST_EXECUTION_MODE ``` -------------------------------- ### Persistent receipt ledger and webhook inbox with in-memory store Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use PersistentReceiptLedger and PersistentWebhookInbox when receipts or delivery attempts must survive process restart. This example creates an in-memory store and passes it to both persistent components. ```typescript import { InMemoryReceiptStore, PersistentReceiptLedger, PersistentWebhookInbox, } from '@resvary/sdk/receipts'; const store = new InMemoryReceiptStore(); const ledger = new PersistentReceiptLedger({ store }); const inbox = new PersistentWebhookInbox({ store }); ``` -------------------------------- ### Run demo workspace Source: https://github.com/horn111/resvary/blob/main/apps/demo/README.md Starts the demo workspace with npm. Requires Node.js 24+ and the RESVARY_DEMO_ADMIN_TOKEN environment variable. ```bash npm run dev --workspace=apps/demo ``` -------------------------------- ### verifyMemoPaymentProof Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Verifies that a transaction hash matches a generated memo payment request and returns the proof details. ```APIDOC ## verifyMemoPaymentProof ### Description Verifies that a transaction hash matches a generated memo payment request and returns the proof details. ### Parameters - **txHash** (`0x${string}`) - Required - The transaction hash to verify. - **paymentRequest** (object) - Required - The payment request object. ### Returns - **blockNumber** (number) - The block number of the transaction. - **memoIndex** (number) - The memo index. - **explorerUrl** (string) - The explorer URL for the proof. ### Example ```typescript const proof = await verifyMemoPaymentProof({ txHash: '0x...' as `0x${string}`, paymentRequest, }); console.log(proof.blockNumber); console.log(proof.memoIndex); console.log(proof.explorerUrl); ``` ``` -------------------------------- ### Conventional commit message examples Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Follow Conventional Commits for commit messages. Examples cover feature, fix, docs, and test scopes. ```text feat(sdk): add per-second billing plan support fix(middleware): handle malformed x402 payment headers docs: update architecture diagram test(buyer): add unit tests for payment retry logic ``` -------------------------------- ### findMemoPaymentProof Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Polls Arc Testnet Memo logs for a matching payment request and returns a proof if found. ```APIDOC ## findMemoPaymentProof ### Description Polls Arc Testnet Memo logs for a matching payment request and returns a proof if found. ### Parameters - **paymentRequest** (object) - Required - The payment request object. ### Returns - **status** (string) - The status of the watch result ('found' or other). - **proof** (object) - The proof object, containing `explorerUrl`. ### Example ```typescript const watchResult = await findMemoPaymentProof({ paymentRequest, }); if (watchResult.status === 'found') { console.log(watchResult.proof.explorerUrl); } ``` ``` -------------------------------- ### Receive and replay webhook events with WebhookInbox Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use WebhookInbox to receive, verify, store, and replay Resvary Receipts webhook deliveries locally. The inbox is in-memory, so production apps should persist delivery attempts in their own database. The example logs the delivery status as 'verified' and the replay attempt as 2. ```typescript import { WebhookInbox, serializeWebhookPayload, signWebhookEvent } from '@resvary/sdk/receipts'; const inbox = new WebhookInbox(); const event = ledger.listWebhookEvents().at(-1)!; const signature = signWebhookEvent(event, process.env.ARC_WEBHOOK_SECRET!); const delivery = inbox.receive({ payload: serializeWebhookPayload(event), header: signature.header, secret: process.env.ARC_WEBHOOK_SECRET!, target: 'https://seller.app/webhooks/arc', }); const replay = inbox.replay({ event, secret: process.env.ARC_WEBHOOK_SECRET!, replayOf: delivery.id, }); console.log(delivery.status); // verified console.log(replay.attempt); // 2 ``` -------------------------------- ### Install Resvary SDK and SQLite 0.7 packages Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.7.md Upgrade the SDK and SQLite packages to version 0.7.0. Opening a v4 credit database with @resvary/sqlite 0.7 applies schema v5 automatically in one BEGIN IMMEDIATE transaction. ```bash npm install @resvary/sdk@0.7.0 @resvary/sqlite@0.7.0 ``` -------------------------------- ### createMemoPaymentRequest Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Creates a memo payment request from an invoice, providing the memo contract, target ERC-20 interface, memo ID, and transaction data. ```APIDOC ## createMemoPaymentRequest ### Description Creates a memo payment request from an invoice, providing the memo contract, target ERC-20 interface, memo ID, and transaction data. ### Parameters - **invoice** (object) - Required - The invoice object. ### Returns - **memoContract** (string) - The memo contract address. - **target** (string) - The Arc Testnet USDC ERC-20 interface address. - **memoId** (string) - Indexed memo ID for querying logs. - **txData** (string) - Data for Memo.memo(...). ### Example ```typescript const paymentRequest = createMemoPaymentRequest(invoice); console.log(paymentRequest.memoContract); console.log(paymentRequest.target); console.log(paymentRequest.memoId); console.log(paymentRequest.txData); ``` ``` -------------------------------- ### Run migration and import commands Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.5.md Run the cutover commands in order: apply the target schema, dry-run the SQLite import, commit the import, and verify it. Requires Node.js 24 for the SQLite import. Stop all 0.4 processes that can write to the SQLite file before starting. ```bash resvary-postgres migrate resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite --dry-run resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite resvary-postgres verify-import --sqlite .resvary/resvary.sqlite ``` -------------------------------- ### Install and migrate PostgreSQL packages for 0.7 Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.7.md Upgrade the SDK, PostgreSQL, and worker packages to version 0.7.0, then run the explicit migration steps. The final status must report schema version 3. PostgreSQL 16, 17, and 18 are supported. ```bash npm install @resvary/sdk@0.7.0 @resvary/postgres@0.7.0 @resvary/worker@0.7.0 ``` ```bash resvary-postgres status ``` ```bash resvary-postgres migrate ``` ```bash resvary-postgres status ``` -------------------------------- ### ReceiptWatcher Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Watches Arc Testnet Memo events for real transactions, verifies the paired ERC-20 USDC Transfer, writes an onchainProof onto the receipt, and emits signed-webhook-ready ledger events. ```APIDOC ## ReceiptWatcher ### Description Watches Arc Testnet Memo events for real transactions, verifies the paired ERC-20 USDC Transfer, writes an onchainProof onto the receipt, and emits signed-webhook-ready ledger events. ### Constructor `new ReceiptWatcher({ ledger, onReceipt })` ### Parameters - **ledger** (ReceiptLedger) - Required - The ledger instance to use. - **onReceipt** (function) - Required - Callback invoked when a receipt is received, receives the receipt object. ### Methods - **watchInvoice(invoice)** - Starts watching for the given invoice. - **start()** - Starts the watcher polling loop. ### Example ```typescript const watcher = new ReceiptWatcher({ ledger, onReceipt(receipt) { console.log('paid', receipt.txHash); }, }); watcher.watchInvoice(invoice); watcher.start(); ``` ``` -------------------------------- ### Find and verify memo payment proof with findMemoPaymentProof and verifyMemoPaymentProof Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use findMemoPaymentProof() to poll Arc Testnet Memo logs for a matching payment request. Use verifyMemoPaymentProof() when you already have a transaction hash and want to prove it matches a generated memo payment request. The proof path is read-only; it does not send a transaction, store a private key, or replace a production indexer. ```typescript import { createMemoPaymentRequest, findMemoPaymentProof, verifyMemoPaymentProof, } from '@resvary/sdk/receipts'; const paymentRequest = createMemoPaymentRequest(invoice); const watchResult = await findMemoPaymentProof({ paymentRequest, }); if (watchResult.status === 'found') { console.log(watchResult.proof.explorerUrl); } const proof = await verifyMemoPaymentProof({ txHash: '0x...' as `0x${string}`, paymentRequest, }); console.log(proof.blockNumber); console.log(proof.memoIndex); console.log(proof.explorerUrl); ``` -------------------------------- ### PostgreSQL migration commands Source: https://github.com/horn111/resvary/blob/main/docs/migration-1.0.md Explicit migration for PostgreSQL. The console never runs it and refuses to start against any version other than v4. The final status must report schema version 4. Apply the migration before deploying 1.0 application, worker, or console processes. ```bash pg_dump --format=custom --file=resvary-before-1.0.dump "$DATABASE_URL" DATABASE_URL="$DATABASE_URL" npx resvary-postgres status DATABASE_URL="$DATABASE_URL" npx resvary-postgres migrate DATABASE_URL="$DATABASE_URL" npx resvary-postgres status ``` -------------------------------- ### Run ArcFundingWorker for durable processing Source: https://github.com/horn111/resvary/blob/main/docs/arc-credit-funding.md Creates and starts an ArcFundingWorker on Arc Mainnet with configurable confirmations, block ranges, and cursor overlap. The worker restores pending invoices, persists cursors, and reconciles receipts after crashes. ```typescript import { ARC_MAINNET } from '@resvary/sdk'; import { ArcFundingWorker } from '@resvary/sdk/funding'; const worker = new ArcFundingWorker({ ledger, receiptStore, payTo, network: 'arc', networkConfig: ARC_MAINNET, confirmations: 2, maxBlockRange: 2_000, maxBlocksPerPoll: 10_000, cursorOverlap: 2, }); worker.start(); ``` -------------------------------- ### Register meter and create price version with graduated and package components Source: https://github.com/horn111/resvary/blob/main/docs/usage-rating.md Registers a meter with multiple dimensions and creates a price version combining a linear rate, a graduated tier component, and a package component. The graduated tiers use cumulative upTo boundaries, and the package charges per started block. ```typescript const meter = await credits.registerMeter({ key: 'multimodal', dimensions: ['input_tokens', 'output_tokens', 'images'], idempotencyKey: 'multimodal-meter-v1', }); ``` ```typescript const price = await credits.createPriceVersion({ meterKey: meter.key, rates: [{ dimension: 'output_tokens', unitSize: '1000', amount: '0.008' }], components: [ { model: 'graduated', dimension: 'input_tokens', tiers: [ { upTo: '1000000', unitSize: '1000', amount: '0.002' }, { upTo: '5000000', unitSize: '1000', amount: '0.0015' }, { unitSize: '1000', amount: '0.001' }, ], }, { model: 'package', dimension: 'images', packageSize: '10', amount: '0.5', }, ], idempotencyKey: 'multimodal-price-v1', }); ``` -------------------------------- ### Watch Arc Testnet receipts with ReceiptWatcher Source: https://github.com/horn111/resvary/blob/main/docs/receipts.md Use this watcher to receive receipts from real Arc Testnet transactions instead of manually calling recordPayment(). It polls Arc Testnet Memo events, fetches transaction receipts, verifies the paired ERC-20 USDC Transfer, writes an onchainProof onto the receipt, and emits signed-webhook-ready ledger events. It intentionally watches the ERC-20 USDC interface at 0x3600000000000000000000000000000000000000 and ignores the native USDC system event emitter at 0xfffffffffffffffffffffffffffffffffffffffe to avoid double-counting. ```typescript import { ReceiptWatcher, ReceiptLedger, createMemoPaymentRequest } from '@resvary/sdk/receipts'; const ledger = new ReceiptLedger(); const invoice = ledger.createInvoice({ id: 'inv_pro_plan_123', amount: '19.00', payTo: '0x1111111111111111111111111111111111111111', }); const paymentRequest = createMemoPaymentRequest(invoice); console.log(paymentRequest.memoContract); console.log(paymentRequest.target); // Arc Testnet USDC ERC-20 interface console.log(paymentRequest.memoId); // Indexed memo id for querying logs console.log(paymentRequest.txData); // Data for Memo.memo(...) const watcher = new ReceiptWatcher({ ledger, onReceipt(receipt) { console.log('paid', receipt.txHash); }, }); watcher.watchInvoice(invoice); watcher.start(); ``` -------------------------------- ### Create monthly allowance policy and apply allowance Source: https://github.com/horn111/resvary/blob/main/docs/grant-policies.md Creates an immutable monthly allowance policy and applies it to a customer for the current period. Periods are derived from the ledger's injected UTC clock; one application exists per customer, policy version, and period. At period start, only the difference between the policy target and unspent amount is granted. ```typescript const policy = await credits.createGrantPolicy({ type: 'allowance', key: 'pro-monthly-credits', cadence: 'month', amount: '25', idempotencyKey: 'policy:pro-monthly-credits:v1', }); const result = await credits.applyAllowance({ policyId: policy.id, customerId: 'customer_123', idempotencyKey: 'allowance:customer_123:2026-08', }); ``` -------------------------------- ### Run database migrations Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Run migrations with production configuration and AGENT_DEMO_ACCEPTING=false. Set AGENT_DEMO_INITIAL_SPEND_UNITS=19390 before the first migration of a fresh database. ```sh npm run migrate --workspace @resvary/agent-demo ``` -------------------------------- ### Opt-in to live browser suite with environment variables Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Requires explicit opt-in because a full run creates two paid jobs. Sets the live demo URL and runs the 'live funding' test. Keep Playwright traces private as they may contain session cookies and submitted content. ```powershell $env:RUN_LIVE_AGENT_DEMO='true' $env:LIVE_AGENT_DEMO_URL='https://agent.resvary.xyz' npm run test:e2e --workspace @resvary/agent-demo -- --config playwright.production.config.ts --grep 'live funding' ``` -------------------------------- ### Set up CreditLedger with SQLite store Source: https://github.com/horn111/resvary/blob/main/README.md Create a CreditLedger instance with a SQLite store for credit management. ```typescript 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', }), }); ``` -------------------------------- ### Clone and set up your fork Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Clone your fork, add the upstream remote, and create a feature branch. Replace YOUR_USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR_USERNAME/resvary.git cd resvary ``` ```bash git remote add upstream https://github.com/horn111/resvary.git ``` ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Apply PostgreSQL migrations Source: https://github.com/horn111/resvary/blob/main/apps/demo/README.md Applies PostgreSQL migrations for multi-instance or serverless deployments. Requires DATABASE_URL to be set. ```bash DATABASE_URL=postgres://... npx resvary-postgres migrate ``` -------------------------------- ### Run all tests Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Run the full test suite. ```bash npm run test ``` -------------------------------- ### Scaffold a Resvary app with npm create resvary@1.3.1 Source: https://github.com/horn111/resvary/blob/main/packages/create-resvary/README.md Run this command to scaffold a Resvary application with prepaid credits and usage billing for AI products. Requires Node.js 24 or newer for the prepaid credits starter. ```bash npm create resvary@1.3.1 my-ai-app ``` -------------------------------- ### Public environment variables for Vercel agent demo Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Configure public controls for the agent demo on Vercel. Set AGENT_DEMO_EXECUTION_MODE=workflow and AGENT_DEMO_TEST_MODE=false; the sync script refuses production test mode and non-Workflow execution mode. ```text AGENT_DEMO_ORIGIN=https://agent.resvary.xyz AGENT_DEMO_EXECUTION_MODE=workflow AGENT_DEMO_TEST_MODE=false AGENT_DEMO_ARC_NETWORK=mainnet AGENT_DEMO_ACCEPTING=false AGENT_DEMO_INITIAL_SPEND_UNITS=19390 AGENT_DEMO_AGENT_PROVIDER=nous AGENT_DEMO_AGENT_MODEL=qwen/qwen3.8-flash AGENT_DEMO_ANALYSIS_PROVIDER=nous AGENT_DEMO_ANALYSIS_MODEL=openai/gpt-4.1-mini ``` -------------------------------- ### Backup PostgreSQL database with pg_dump and pg_restore Source: https://github.com/horn111/resvary/blob/main/docs/operator-console-runbook.md Creates a custom-format dump and restores it into a disposable test database to verify the backup before upgrade. Use for PostgreSQL deployments. ```bash pg_dump --format=custom --file=resvary-before-upgrade.dump "$DATABASE_URL" createdb resvary_restore_test pg_restore --clean --if-exists --dbname=resvary_restore_test resvary-before-upgrade.dump ``` -------------------------------- ### Create Postgres credit store with createPostgresCreditStore Source: https://github.com/horn111/resvary/blob/main/packages/postgres/README.md Creates a credit store using a connection string from the DATABASE_URL environment variable. The store owns and closes its pool when created from a connection string; call close() during shutdown. ```ts import { createPostgresCreditStore } from '@resvary/postgres'; const store = createPostgresCreditStore({ connectionString: process.env.DATABASE_URL! }); // Use store with CreditLedger, then close the owned pool during shutdown. await store.close(); ``` -------------------------------- ### Create a price version for token rates Source: https://github.com/horn111/resvary/blob/main/README.md Create a price version with rates for input and output tokens. ```typescript 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', }); ``` -------------------------------- ### Deploy to Vercel with region fra1 Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Deploy the app to production with the region explicitly set to fra1 and the scope horn111s-projects. ```sh vercel deploy --prod --yes --regions fra1 --scope horn111s-projects ``` -------------------------------- ### Apply schema changes with resvary-postgres status and migrate Source: https://github.com/horn111/resvary/blob/main/docs/production-persistence.md Run these commands as a separate deployment step to apply schema changes. Store constructors fail against missing tables; they never migrate automatically. ```bash resvary-postgres status resvary-postgres migrate ``` -------------------------------- ### Run tests for a specific package Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Run tests for the SDK package using the workspace flag. ```bash npm run test --workspace=packages/sdk ``` -------------------------------- ### Create Gateway Credit Gate Source: https://github.com/horn111/resvary/blob/main/packages/circle/README.md Creates a credit gate that returns a Gateway funding challenge when credits are insufficient. Rounds shortfall up to a cent. Requires prior caller authentication and mainnet funding requires expectedPayer. Deduplicate jobs and persist the challenge. ```ts import { createGatewayCreditGate } from '@resvary/circle'; const gate = createGatewayCreditGate({ ledger, funding }); const outcome = await gate({ customerId: authenticatedCustomerId, expectedPayer: authenticatedPayer, priceId, estimatedUsage: { input_tokens: '2000', output_tokens: '1024' }, idempotencyKey: `reservation:${jobId}`, fundingIdempotencyKey: `funding:${jobId}`, }); ``` -------------------------------- ### Set Demo Environment Variables Source: https://github.com/horn111/resvary/blob/main/README.md Set a local admin token and webhook secret. Mutating demo actions fail closed when the token is missing. Receipt signing and webhook ingestion stay disabled until RESVARY_WEBHOOK_SECRET is configured. ```dotenv RESVARY_DEMO_ADMIN_TOKEN=replace-with-a-long-random-token RESVARY_WEBHOOK_SECRET=replace-with-a-different-long-random-token ``` -------------------------------- ### Reserve and Commit Usage with TypeScript SDK Source: https://github.com/horn111/resvary/blob/main/docs/prepaid-credits.md Core flow for reserving credits and committing actual usage. Requires a reservation ID and usage event ID; uses idempotency keys to ensure safe retries. ```typescript const reservation = await credits.reserveCredits({ customerId: 'customer_123', priceId: price.id, estimatedUsage: { input_tokens: '2000', output_tokens: '1000' }, idempotencyKey: 'request_abc', }); const completion = await callModel(); const result = await credits.commitUsage({ reservationId: reservation.id, usageEventId: completion.id, actualUsage: { input_tokens: String(completion.usage.inputTokens), output_tokens: String(completion.usage.outputTokens), }, idempotencyKey: 'request_abc:commit', }); ``` -------------------------------- ### Run proof exporter for completed job Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Use after the job reaches 'completed'. Rejects fixture runs and outputs an allowlisted record without sensitive data. Keep the first output outside the Git worktree until an operator checks the transaction. ```sh npm run proof --workspace @resvary/agent-demo -- JOB_UUID ``` -------------------------------- ### Run PostgreSQL migration status and migrate commands Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.8.md Run these commands before application rollout to check and apply any pending PostgreSQL schema migrations. When upgrading from 0.7, the migrate command should report no pending schema version. ```bash npx resvary-postgres status npx resvary-postgres migrate ``` -------------------------------- ### Public wallet addresses for Vercel agent demo Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Set the three public wallet addresses from operator-verified records. The SCA and backing EOA serve different protocol roles; do not copy one address into both fields. The configuration rejects an identical payer and seller. ```text AGENT_DEMO_WALLET= AGENT_DEMO_PAYER= AGENT_DEMO_SELLER= ``` -------------------------------- ### createNextGatewayTopUpHandler Source: https://github.com/horn111/resvary/blob/main/docs/circle-gateway-funding.md Creates a framework-neutral HTTP handler for Next.js that processes Gateway top-up requests. The first request returns HTTP 402 with Payment-Required, and the paid retry carries Payment-Signature. ```APIDOC ## createNextGatewayTopUpHandler ### Description Creates a framework-neutral HTTP handler for Next.js that processes Gateway top-up requests. The first request returns HTTP 402 with Payment-Required, and the paid retry carries Payment-Signature. ### Method POST ### Endpoint / (Next.js route handler) ### Parameters #### Request Body - **customerId** (string) - Required - The customer identifier. - **amount** (string) - Required - The amount to fund. - **expectedPayer** (string) - Required - The expected payer's wallet address. - **idempotencyKey** (string) - Required - A unique key for idempotency. ### Request Example ```typescript export const POST = createNextGatewayTopUpHandler({ funding, resolveRequest: async (request) => { const session = await requireSession(request); return { customerId: session.customerId, amount: '5', expectedPayer: session.walletAddress, idempotencyKey: `topup:${session.customerId}:${crypto.randomUUID()}`, }; }, }); ``` ### Response #### Success Response (200) - **paymentRequired** (object) - The x402 v2 response for the Circle batching client. #### Response Example ```typescript request.paymentRequired ``` ### Error Handling - **402** - Returns HTTP 402 with `Payment-Required` header on the first request. - **Payment-Signature** - The paid retry carries `Payment-Signature` header. ``` -------------------------------- ### Import ArcFundingWorker Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.4.md Workers are available from the funding module. ```typescript import { ArcFundingWorker } from '@resvary/sdk/funding'; ``` -------------------------------- ### Run PostgreSQL regression tests with TEST_DATABASE_URL Source: https://github.com/horn111/resvary/blob/main/docs/migration-1.3.md Set TEST_DATABASE_URL to a dedicated, disposable database whose name ends in `_test`, then run these commands. The PostgreSQL suite creates and removes its own schemas; Agent Demo tests truncate job tables, so never use application data. Without TEST_DATABASE_URL, database integration tests are skipped. ```bash npm run build:core npm run test --workspace=@resvary/postgres npm run test --workspace=@resvary/agent-demo ``` -------------------------------- ### Import SQLite database to PostgreSQL with dry run and verification Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.7.md Run a dry run before cutover, then perform the import and verify. The importer accepts SQLite schema v5 and requires PostgreSQL schema v3. ```bash resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite --dry-run ``` ```bash resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite ``` ```bash resvary-postgres verify-import --sqlite .resvary/resvary.sqlite ``` -------------------------------- ### Demo flow overview Source: https://github.com/horn111/resvary/blob/main/apps/demo/README.md Text block showing the demo's end-to-end flow: $5 grant, reserve, simulated AI usage, commit, release, and usage receipt. ```text $5 grant → reserve → simulated AI usage → commit → release → usage receipt ``` -------------------------------- ### Run Postgres migration Source: https://github.com/horn111/resvary/blob/main/docs/persistence.md Applies the PostgreSQL schema migration using the DATABASE_URL environment variable. Required before deploying workers that use DurableMeteredOperations. ```bash DATABASE_URL=postgres://postgres:postgres@localhost:5432/resvary \ npx resvary-postgres migrate ``` -------------------------------- ### Postgres CLI commands Source: https://github.com/horn111/resvary/blob/main/packages/postgres/README.md CLI commands for status, migration, SQLite import (with dry-run), and verification. SQLite import requires Node.js 24 and an offline Resvary 0.8 SQLite schema v5 database; stop all writers before importing. ```text resvary-postgres status resvary-postgres migrate resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite --dry-run resvary-postgres import-sqlite --sqlite .resvary/resvary.sqlite resvary-postgres verify-import --sqlite .resvary/resvary.sqlite ``` -------------------------------- ### Create Postgres credit store Source: https://github.com/horn111/resvary/blob/main/docs/persistence.md Initializes a Postgres-backed credit store with a connection string and schema. Passing a connection string makes the store own the pool; call await store.close() during graceful shutdown. Store construction never applies migrations. ```typescript import { createPostgresCreditStore } from '@resvary/postgres'; const store = createPostgresCreditStore({ connectionString: process.env.DATABASE_URL, schema: 'public', }); ``` -------------------------------- ### Run tests in watch mode Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Run tests in watch mode for the SDK package. ```bash npm run test:watch --workspace=packages/sdk ``` -------------------------------- ### Run a metered operation with reservation Source: https://github.com/horn111/resvary/blob/main/README.md Execute a provider call with estimated usage and commit actual usage. ```typescript 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); ``` -------------------------------- ### Configure BuyerClient with paymentPolicy Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.6.md Use this snippet to construct a BuyerClient with a payment policy that fails closed on 402 responses. The policy requires exact recipients and origins, and the client validates network, amount, expiry, recipient, and request origin before signing. It reserves the total budget before asynchronous approval, so concurrent requests cannot exceed the client-instance limit. ```ts import { BuyerClient } from '@resvary/sdk'; const buyer = new BuyerClient({ privateKey: process.env.BUYER_PRIVATE_KEY, paymentPolicy: { allowedPayTo: ['0x0123456789abcdef0123456789abcdef01234567'], allowedOrigins: ['https://api.example.com'], maxAmount: '1.00', maxTotalAmount: '25.00', }, }); ``` -------------------------------- ### Run compiled browser test in Workflow mode Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Set the environment variable to 'workflow' to run the e2e test in Workflow mode, then remove the variable after the test. ```powershell $env:AGENT_DEMO_TEST_EXECUTION_MODE='workflow' npm run test:e2e --workspace @resvary/agent-demo Remove-Item Env:\AGENT_DEMO_TEST_EXECUTION_MODE ``` -------------------------------- ### Create GatewayNanopaymentFunding Request Source: https://github.com/horn111/resvary/blob/main/README.md Create a funding request using GatewayNanopaymentFunding with the Arc Gateway Mainnet. Requires a ledger, seller address, and network. The request includes customerId, amount, and idempotencyKey. ```typescript 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', }); ``` -------------------------------- ### Refresh Claude Design Import Source: https://github.com/horn111/resvary/blob/main/scripts/README.md Run the import script with the source HTML and target generated file, then verify with design:check and build the demo app. The importer fails if expected source strings are missing, so review changes before committing. ```powershell node scripts/import-claude-design.mjs "C:\path\to\Resvary Site.html" apps/demo/src/app/claude-design.generated.ts npm run design:check npm --prefix apps/demo run build ``` -------------------------------- ### Create promotional grant and claim promotion Source: https://github.com/horn111/resvary/blob/main/docs/grant-policies.md Creates a one-time promotion policy with a 14-day expiry and claims it for a customer. The application must check eligibility, segments, and coupon validity before calling claimPromotion. Resvary guarantees one claim per customer and policy version, even with different idempotency keys. ```typescript const promotion = await credits.createGrantPolicy({ type: 'promotion', key: 'launch-credit', amount: '5', expiresInMs: 14 * 24 * 60 * 60 * 1000, idempotencyKey: 'policy:launch-credit:v1', }); await credits.claimPromotion({ policyId: promotion.id, customerId: 'customer_123', idempotencyKey: 'promotion:launch-credit:customer_123', }); ``` -------------------------------- ### git diff command for Agent Stack implementation Source: https://github.com/horn111/resvary/blob/main/docs/ethonline-continuity.md Use this command after the implementation lands in one Git history to review the complete diff for lockfile, build-context, and Vercel configuration changes. ```sh git diff 53f59dacc86f5300a68e29ceff7b7751af06c096 -- apps/agent-demo packages/circle docs/agent-demo-architecture.md docs/agent-demo-vercel-runbook.md docs/ethonline-continuity.md ``` -------------------------------- ### Secret variable names for Vercel agent demo Source: https://github.com/horn111/resvary/blob/main/docs/agent-demo-vercel-runbook.md Store these values as Vercel Sensitive variables without printing them. Keep local source files .env.agent-demo.local and .env.circle-session.local ignored by Git. ```text DATABASE_URL AGENT_DEMO_SECRET CRON_SECRET NOUS_API_KEY CIRCLE_AGENT_SESSION_BUNDLE CIRCLE_SESSION_ENCRYPTION_KEY ``` -------------------------------- ### Create SQLite credit store Source: https://github.com/horn111/resvary/blob/main/docs/persistence.md Initializes a SQLite-backed CreditLedger with a project ID. The database file and directory are owner-only on POSIX (0700 and 0600). Call store.close() during graceful shutdown. ```typescript import { CreditLedger } from '@resvary/sdk/credits'; import { createSqliteCreditStore } from '@resvary/sqlite'; const store = createSqliteCreditStore({ path: '.resvary/resvary.sqlite' }); const credits = new CreditLedger({ projectId: 'my_ai_product', store }); ``` -------------------------------- ### createExpressGatewayTopUpHandler Source: https://github.com/horn111/resvary/blob/main/docs/circle-gateway-funding.md Wraps the same Request/Response handler for Express-compatible routes. ```APIDOC ## createExpressGatewayTopUpHandler ### Description Wraps the same Request/Response handler for Express-compatible routes. ### Method POST ### Endpoint / (Express route) ### Parameters #### Request Body - **customerId** (string) - Required - The customer identifier. - **amount** (string) - Required - The amount to fund. - **expectedPayer** (string) - Required - The expected payer's wallet address. - **idempotencyKey** (string) - Required - A unique key for idempotency. ### Request Example ```typescript const handler = createExpressGatewayTopUpHandler({ funding, resolveRequest: async (request) => { const session = await requireSession(request); return { customerId: session.customerId, amount: '5', expectedPayer: session.walletAddress, idempotencyKey: `topup:${session.customerId}:${crypto.randomUUID()}`, }; }, }); ``` ### Response #### Success Response (200) - **paymentRequired** (object) - The x402 v2 response for the Circle batching client. #### Response Example ```typescript request.paymentRequired ``` ### Error Handling - **402** - Returns HTTP 402 with `Payment-Required` header on the first request. - **Payment-Signature** - The paid retry carries `Payment-Signature` header. ``` -------------------------------- ### Run lint, typecheck, and tests Source: https://github.com/horn111/resvary/blob/main/CONTRIBUTING.md Ensure all checks pass before submitting a pull request. ```bash npm run lint && npm run typecheck && npm run test ``` -------------------------------- ### Import ArcCreditFunding Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.4.md Existing imports for ArcCreditFunding remain valid in 0.4. ```typescript import { ArcCreditFunding } from '@resvary/sdk/funding/arc'; ``` -------------------------------- ### Register a meter for token usage Source: https://github.com/horn111/resvary/blob/main/README.md Register a meter with dimensions for input and output tokens. ```typescript const meter = await credits.registerMeter({ key: 'llm_tokens', dimensions: ['input_tokens', 'output_tokens'], idempotencyKey: 'meter-v1', }); ``` -------------------------------- ### Grant credits to a customer Source: https://github.com/horn111/resvary/blob/main/README.md Grant a credit amount to a customer with an idempotency key. ```typescript await credits.grantCredits({ customerId: 'customer_123', amount: '5', idempotencyKey: 'signup-credit:customer_123', }); ``` -------------------------------- ### Instantiate ArcCreditFunding with rpcUrl Source: https://github.com/horn111/resvary/blob/main/docs/migration-0.6.md Use this snippet to create an ArcCreditFunding instance that verifies direct Arc funding through Arc Testnet RPC. Supply rpcUrl when the default endpoint is unsuitable; publicClient remains available for an injected compatible client. The expected recipient, asset, network, amount, and expiry come from the persisted funding intent, and caller-supplied receipt fields are not trusted as proof. ```ts import { ArcCreditFunding } from '@resvary/sdk'; const funding = new ArcCreditFunding({ ledger, payTo: process.env.RESVARY_ARC_FUNDING_RECIPIENT, rpcUrl: process.env.RESVARY_ARC_RPC_URL, }); ``` -------------------------------- ### Package pricing calculation formulas Source: https://github.com/horn111/resvary/blob/main/docs/usage-rating.md Formulas for package pricing: packageCount is the ceiling of quantity divided by packageSize, and charge is packageCount times packageAmountUnits. Zero quantity produces zero packages and zero charge. ```text packageCount = ceil(quantity / packageSize) charge = packageCount × packageAmountUnits ```