Core HTTP 402 payment library for Nano cryptocurrency - framework agnostic
npm install nano402Framework-agnostic core library for HTTP 402 payments with Nano cryptocurrency.
``bash`
npm install nano402or
pnpm add nano402or
yarn add nano402
nano402 provides the core functionality for implementing HTTP 402 payment systems using Nano cryptocurrency. It's framework-agnostic and can be used with any Node.js backend framework.
- ✅ Deterministic Address Derivation - Generate unique payment addresses from a seed
- ✅ Invoice Management - Create, track, and manage payment invoices
- ✅ Payment Verification - Verify payments via Nano RPC (supports pending and confirmed blocks)
- ✅ Multiple Storage Backends - In-memory (dev) or SQLite (production) storage
- ✅ Webhook Support - Trigger webhooks on invoice events
- ✅ RPC Caching - Built-in caching for better performance
- ✅ TypeScript Support - Full TypeScript definitions included
`typescript
import { Nano402 } from "nano402";
// Initialize Nano402
const nano402 = new Nano402({
walletSeed: process.env.NANO_SEED!,
nanoRpcUrl: process.env.NANO_RPC_URL || "https://node.somenano.com/proxy",
});
// Create an invoice
const invoice = await nano402.createInvoice({
resource: "/api/protected",
amount_xno: "0.00001",
ttlSeconds: 3600,
});
// Verify payment
const isValid = await nano402.verifyPayment(invoice.id, txHash);
`
#### Nano402
Main class for invoice management and payment verification.
`typescript`
const nano402 = new Nano402({
walletSeed: string; // 64-character hex seed
nanoRpcUrl: string; // Nano RPC node URL
invoiceStore?: InvoiceStore; // Optional custom store
indexStore?: IndexStore; // Optional custom index store
// ... see full config in types
});
Methods:
- createInvoice(params: CreateInvoiceParams): Promise - Create a new invoiceverifyPayment(id: string, proofTxHash?: string): Promise
- - Verify paymentgetStatus(id: string): Promise
- - Get invoice statusmarkUsed(id: string): Promise
- - Mark invoice as usedgetInvoice(id: string): Promise
- - Get invoice by IDgetInvoiceByResource(resource: string): Promise
- - Get invoice by resourcegetInvoiceByClientIp(ip: string, resource?: string): Promise
- - Get invoice by IPgenerateNanoUri(invoice: Invoice): string
- - Generate Nano payment URIregisterWebhook(config: WebhookConfig): void
- - Register webhook
#### Invoice Stores
- MemoryInvoiceStore - In-memory storage (development)SqliteInvoiceStore
- - SQLite storage (production)
#### Index Stores
- FileIndexStore - File-based index storage (default)SqliteIndexStore
- - SQLite-based index storageMemoryIndexStore
- - In-memory index storage
- deriveNanoAccount(seed: string, index: number): string - Derive Nano account from seedxnoToRaw(amount: string): string
- - Convert XNO to raw unitsrawToXno(amount: string): string
- - Convert raw units to XNO
Shared verification helpers used by framework packages:
- calculateRetryAfter(expiresAt: string): number - Calculate Retry-After header value in secondsisSessionValid(invoice: Invoice, sessionDuration?: number): boolean
- - Check if session is still validisUsageExceeded(invoice: Invoice, maxUsage?: number): boolean
- - Check if invoice has exceeded max usagegetPaymentInfo(options: GuardOptions): PaymentInfo
- - Generate helpful payment informationgetClientIp(req: RequestLike): string
- - Extract client IP from request (framework-agnostic)
Framework-agnostic guard handler for implementing payment protection:
- handleGuardRequest(nano402: Nano402, request: GuardRequest, options: GuardOptions): Promise - Main guard handler that performs all verification logicgenerate402Response(invoice: Invoice, options: GuardOptions, nano402: Nano402): ResponseData
- - Generate standardized 402 response data
These utilities are used internally by @nano402/express and @nano402/nestjs packages, but can also be used directly when building custom framework integrations.
All TypeScript types are exported for use in your projects:
- Invoice, InvoiceStatus, Nano402Config, CreateInvoiceParamsInvoiceStore
- , IndexStore, PaymentVerificationOptionsInvoiceStatistics
- , WebhookConfig
- And more...
Custom error classes for better error handling:
- InvoiceNotFoundErrorInvoiceNotPaidError
- InvoiceExpiredError
- InvalidSeedError
- InvalidAmountError
- RpcError
- RpcTimeoutError
- ConcurrentModificationError
-
`typescript
import { Nano402 } from "nano402";
const nano402 = new Nano402({
walletSeed: process.env.NANO_SEED!,
nanoRpcUrl: process.env.NANO_RPC_URL!,
});
// Create invoice
const invoice = await nano402.createInvoice({
resource: "/api/premium-content",
amount_xno: "0.01",
ttlSeconds: 3600,
});
// Check status
const status = await nano402.getStatus(invoice.id);
console.log(status); // "pending" | "paid" | "used" | "expired" | "cancelled" | "refunded"
// Verify payment
const isValid = await nano402.verifyPayment(invoice.id, txHash);
if (isValid) {
await nano402.markUsed(invoice.id);
}
`
`typescript
import { Nano402, SqliteInvoiceStore } from "nano402";
const invoiceStore = new SqliteInvoiceStore({
dbPath: "./data/invoices.db",
});
const nano402 = new Nano402({
walletSeed: process.env.NANO_SEED!,
nanoRpcUrl: process.env.NANO_RPC_URL!,
invoiceStore,
});
`
Note: Install better-sqlite3 for SQLite support:
`bash`
npm install better-sqlite3
`typescript`
nano402.registerWebhook({
url: "https://api.example.com/webhooks/nano402",
secret: process.env.WEBHOOK_SECRET!,
events: [
"invoice.created",
"invoice.paid",
"invoice.expired",
"invoice.cancelled",
"invoice.refunded",
],
});
For easier integration with popular frameworks, check out:
- @nano402/express - Express.js middleware
- @nano402/nestjs - NestJS guard
- Node.js >= 18.0.0
- Nano wallet seed (64-character hexadecimal string)
- Nano RPC node (public or self-hosted)
For complete documentation, examples, and guides, visit the main repository.
MIT
- GitHub: https://github.com/nano402/nano402-js
- Issues: https://github.com/nano402/nano402-js/issues
If you find this project useful, consider supporting its development:
Nano Address: nano_366td9nfbxns1tkq3u1ryoaazdzjc5ah3duipw5s7dah4nqna41a6hef3i7x`