dero-pay
API Reference

API Reference

Complete reference for all dero-pay package exports.

Every subpath below is published dual-format: an ESM build resolved by import and a CommonJS build resolved by require, each with its own type declarations. The ./package.json export is also exposed so tools can resolve the manifest directly. This means a CommonJS backend can require("dero-pay/server") while an ESM app imports the same package.

Core (dero-pay)

Types, pricing utilities, and payment ID generation.

import {
  // Pricing
  deroToAtomic,              // Convert DERO string to atomic BigInt
  atomicToDero,              // Convert atomic BigInt to DERO string
  formatDero,                // Format atomic units as "X.XXXX DERO"
  isValidAmount,             // Validate amount is positive and valid
 
  // Payment IDs
  generatePaymentId,         // Generate random uint64 payment ID
  paymentIdToHex,            // Convert payment ID to hex string
  hexToPaymentId,            // Convert hex string to payment ID
  isValidPaymentId,          // Validate payment ID format
 
  // Constants
  ATOMIC_UNITS_PER_DERO,     // 100_000n (10^5)
  DERO_DECIMALS,             // 5
 
  // x402 receipt headers
  formatX402AuthorizationHeader,  // Build `X402 proof="<token>"`
  parseX402AuthorizationHeader,   // Extract a proof token from an Authorization header
 
  // Types
  type Invoice,
  type InvoiceStatus,        // "created" | "pending" | "confirming" | "completed" | "expired" | "partial"
  type Payment,
  type PaymentStatus,
  type WalletStatus,
  type CreateInvoiceParams,
  type CreateInvoiceEscrowParams,
  type InvoiceEscrow,
  type EscrowInvoiceStatus,
  type DeroPayConfig,
  type DeroChainId,
  type WebhookEvent,
  type WebhookEventType,
  type DeroPayError,
  type DeroPayErrorCode,
} from "dero-pay";

RPC (dero-pay/rpc)

import {
  WalletRpcClient,   // DERO wallet JSON-RPC client
  DaemonRpcClient,   // DERO daemon JSON-RPC client
 
  type WalletRpcConfig,
  type DaemonRpcConfig,
  type GetTransfersParams,
  type GetTransfersResult,
  type TransferEntry,
  type TransferParams,
  type MakeIntegratedAddressParams,
  type GetInfoResult,
  type GetScParams,
  type GetScResult,
  type InvokeScParams,
  type InstallScParams,
} from "dero-pay/rpc";

Server (dero-pay/server)

import {
  // Core
  InvoiceEngine,
  PaymentMonitor,
  WebhookDispatcher,
 
  // Storage
  MemoryInvoiceStore,        // In-memory (dev)
  SqliteInvoiceStore,        // SQLite (production, requires better-sqlite3)
 
  // Webhook helpers
  createWebhookEvent,
  signWebhookPayload,
  verifyWebhookSignature,
 
  // Re-exported from other modules
  WalletRpcClient,
  DaemonRpcClient,
  EscrowContract,
  EscrowManager,
 
  // Types
  type InvoiceStore,         // Interface for custom storage backends
  type InvoiceFilter,
  type InvoiceStats,
  type InvoiceEngineEvents,
  type PaymentMonitorEvents,
  type SqliteStoreConfig,
  type WebhookConfig,
  type WebhookDelivery,
  type EscrowRecord,
  type EscrowStatus,
  type EscrowManagerConfig,
} from "dero-pay/server";

Client (dero-pay/client)

import {
  XSWDPayClient,       // Browser-side XSWD client for payments
  PaymentSession,      // Payment session manager
 
  type XSWDPayAppData,
  type XSWDPayEvents,
  type PaymentSessionEvents,
} from "dero-pay/client";

React (dero-pay/react)

import {
  DeroPayProvider,       // Context provider
  PayWithDero,           // "Pay with DERO" button (XSWD)
  InvoiceView,           // Full payment interface (QR, address, timer)
  PaymentStatus,         // Compact status indicator
  EscrowInvoiceView,     // Escrow-specific payment view
  useDeroPayContext,     // Hook for custom payment UIs
 
  type DeroPayProviderProps,
  type DeroPayContextValue,
  type PayWithDeroProps,
  type InvoiceViewProps,
  type PaymentStatusProps,
  type EscrowInvoiceViewProps,
} from "dero-pay/react";

Next.js (dero-pay/next)

import {
  createPaymentHandlers,    // Factory for API route handlers
  createDeroPayMiddleware,  // API key middleware
  generateApiKey,           // Generate a random API key
  createX402RouteGuard,     // App Router x402 payment guard (see /dero-pay/x402)
 
  type PaymentHandlersConfig,
  type DeroPayMiddlewareConfig,
  type X402PaymentPolicy,
  type X402PolicyResolver,   // (request) => policy, for metered pricing
  type X402RouteGuardConfig,
  type X402ChallengeResponse,
} from "dero-pay/next";

createPaymentHandlers Return Value

const {
  createInvoiceHandler,      // POST — create invoice
  statusHandler,             // GET  — invoice status by ID
  listInvoicesHandler,       // GET  — list invoices with filters
  statsHandler,              // GET  — invoice statistics
  webhookHandler,            // POST — incoming webhook receiver
  healthHandler,             // GET  — engine health check
  escrowActionHandler,       // POST — escrow lifecycle actions
  listEscrowsHandler,        // GET  — list escrow records
  claimEscrowInvoiceHandler, // POST — claim a pre-minted escrow invoice
  issueReceiptHandler,       // POST — issue an x402 receipt after payment
  verifyReceiptHandler,      // POST — verify an x402 receipt token
  getEngine,                 // () => Promise<InvoiceEngine>
} = createPaymentHandlers(config);

x402 (dero-pay/x402)

Framework-agnostic HTTP 402 primitives — use these when you are not on Next.js (the dero-pay/next createX402RouteGuard is the App Router wrapper over the same rail).

import {
  withX402,               // Wrap any handler with a 402 challenge → verify flow
  build402Response,       // Construct the 402 body (accepts[] payment requirements)
  parsePaymentHeader,     // Parse an inbound X-Payment / Authorization header
  FacilitatorHttpClient,  // Optional verify/settle client for a facilitator
 
  type PaymentPayload,
  type PaymentRequirements,
  type WithX402Options,
} from "dero-pay/x402";

Focused subpaths are published for tree-shaking and cross-runtime use:

Import PathContents
dero-pay/x402/typesZod schemas + inferred types (PaymentPayload, PaymentRequirements)
dero-pay/x402/serverbuild402Response, parsePaymentHeader, facilitator client
dero-pay/x402/clientselectAcceptsEntry, buildPaymentHeader, payDeroRail (async convenience payer)
dero-pay/x402/nextwithX402 App Router wrapper

See the x402 Payment Guard page for the full guard flow.

Agent (dero-pay/agent)

The autonomous agent-side payer — settles x402 challenges under a spend policy with no facilitator.

import {
  // Auto-payer
  createPayingFetch,          // fetch() that transparently settles 402 challenges
  X402PaymentRejectedError,
  X402UnpayableError,
  X402SettlementTimeoutError,
 
  // Spend policy + attenuable credentials
  SpendPolicy,                // origin allowlist, per-request + rolling-window caps
  SpendPolicyError,
  mintSpendCredential,        // macaroon-style capability
  attenuate,                  // narrow a credential (holder can only tighten)
  verifyCredentialSignature,
  CredentialPolicy,
 
  // Wallet payers
  createWalletRpcPayer,       // loopback-only wallet RPC payer
  createXswdPayer,            // browser XSWD payer
 
  // MCP paid tools
  createPaidToolGuard,        // server: gate an MCP tool behind payment
  createPayingToolCaller,     // client: auto-pay an MCP tool call
 
  type PayingFetchConfig,
  type SpendPolicyConfig,
  type SpendCredential,
  type PaymentEvidence,
} from "dero-pay/agent";

See Autonomous Agent Payer for the full flow and safety properties.

Escrow (dero-pay/escrow)

import {
  EscrowContract,         // Smart contract RPC wrapper
  EscrowManager,          // Lifecycle manager
 
  // Status utilities
  EscrowStatusCode,       // { AWAITING_DEPOSIT: 0, FUNDED: 1, ... }
  statusCodeToString,     // Convert code to human-readable string
 
  // PREMINT keeper + inventory (see /escrow/keeper)
  EscrowKeeper,                 // Background pre-mint pool loop
  MemoryEscrowInventoryStore,   // In-memory pool store (single process)
  SqliteEscrowInventoryStore,   // Durable pool store (wraps a better-sqlite3 Database)
 
  type EscrowStatus,
  type EscrowStatusCodeValue,
  type EscrowOnChainState,
  type EscrowRecord,
  type EscrowResolution,
  type EscrowManagerEvents,
  type EscrowManagerConfig,
  type CreateEscrowParams,
  type EscrowKeeperOptions,
  type EscrowKeeperEvents,
  type EscrowInventoryStore,
  type EscrowInventoryState,
} from "dero-pay/escrow";

See PREMINT Keeper for the pre-mint inventory flow.

Router (dero-pay/router)

import {
  RouterContract,   // Payment router contract RPC wrapper
  RouterManager,    // Deploy + payment lifecycle manager
 
  type RouterOnChainState,
  type DeployRouterParams,
  type RouterRecord,
  type RouterStatus,
  type RouterManagerEvents,
  type RouterManagerConfig,
} from "dero-pay/router";

See the Payment Router SDK for full usage.

Gateway (dero-pay/gateway)

HTTP client for external platforms (Medusa, WooCommerce, etc.) to create invoices and check status against a running gateway server.

import {
  GatewayClient,        // HTTP client for a DeroPay gateway
  GatewayClientError,
 
  type GatewayClientConfig,
  type GatewayInvoice,
  type GatewayPayment,
  type GatewayEscrow,
  type GatewayInfo,
  type GatewayError,
  type CreateInvoiceInput,
} from "dero-pay/gateway";

See the Gateway Server guide for the server side.

Bridge (dero-pay/bridge)

An outbound-only host daemon that pushes durable, at-least-once payment webhooks to a merchant — InvoiceEngine + a durable outbox + a delivery worker, with zero inbound listeners. Also ships a deropay-bridge CLI binary.

import {
  PayoutBridge,             // The outbound webhook daemon
  loadConfig,               // Load + validate bridge config
  isAcceptableWebhookUrl,   // Guard against non-loopback/unsafe URLs
  writeHeartbeat,
  readHeartbeat,
  evaluateHealth,
 
  // Durability primitives (reusable when embedding the bridge)
  WebhookOutbox,
  WebhookDeliveryWorker,
  OutboxWebhookSink,
 
  type BridgeConfig,
  type OutboxRecord,
  type OutboxStatus,
  type DeadLetter,
} from "dero-pay/bridge";

See the Escrow documentation for full escrow API details.

Configuration Reference

FieldTypeDefaultDescription
walletRpcUrlstringlocalhost:10103Wallet RPC endpoint
daemonRpcUrlstringlocalhost:10102Daemon RPC endpoint
rpcAuth{ username, password }RPC authentication
chainIdDeroChainId"dero-mainnet"Network identifier
defaultTtlSecondsnumber900Invoice expiration (15 min)
defaultRequiredConfirmationsnumber3Confirmation depth
pollIntervalMsnumber5000Monitor poll interval
webhookUrlstringWebhook destination
webhookSecretstringHMAC signing secret
webhookMaxRetriesnumber3Max delivery attempts
storeInvoiceStoreMemoryInvoiceStoreStorage backend
enableEscrowbooleanfalseEnable escrow subsystem
escrowFeeBasisPointsnumber0Escrow platform fee in basis points (0 = no fee, 250 = 2.5%)
escrowBlockExpirationnumber60Escrow block expiry