# AI Agent Deployment Guide A comprehensive guide for deploying and operating a Beignet Lightning node for AI agent workflows. ## Prerequisites - **Node.js** 22.23.4+, 24.22.1+ or 26.12.1+ (the releases with the October 21, 2026 security fixes) - **npm** 9+ - Bitcoin on-chain funds for channel opening - Electrum server access (mainnet default: `bitkit.to:9999`) ## Import Paths | Path | Contents | |------|----------| | `beignet` | On-chain wallet only (`Wallet`, `generateMnemonic`) | | `beignet/cli` | `BeignetNode`, `startDaemon`, `isRetryableError`, errors (recommended for agents) | | `beignet/lightning` | Low-level protocol modules (`LightningNode`, `Channel`, etc.) | ## Quick Start Get from zero to payment-ready in under 30 lines of TypeScript: ```typescript import { BeignetNode } from 'beignet/cli'; const peer = { pubkey: '03abc...', host: 'node.example.com', port: 9735 }; const bolt11Invoice = 'lnbc...'; // 1. Create a node (generates a mnemonic if none is provided: back up // node.getMnemonic() before funding it) const node = await BeignetNode.create({ network: 'mainnet', alias: 'my-agent', autoReconnect: true, }); // 2. Get on-chain address and fund it const address = await node.getNewAddress(); console.log('Fund this address:', address); // 3. Wait for on-chain funds, then connect + open a channel in one call const channel = await node.connectAndOpenChannel(peer.pubkey, peer.host, peer.port, 1_000_000); // 4. Wait for the channel to become active. The default timeout is 60s; the // funding transaction needs confirmations first, so allow for blocks. await node.waitForChannelReady(channel.channelId, 2 * 60 * 60_000); // 5. Pay an invoice const result = await node.payInvoiceSafe(bolt11Invoice); console.log('Payment:', result.status); // 'COMPLETED' or 'FAILED' ``` ## HTTP Daemon For framework integrations (LangChain, CrewAI, etc.), use the HTTP daemon: ```typescript import { startDaemon } from 'beignet/cli'; const { server, node } = await startDaemon({ network: 'mainnet', daemonPort: 2112, apiToken: process.env.BEIGNET_API_TOKEN, cors: true, rateLimit: { maxRequests: 100, windowMs: 60_000 }, // Optional: protect against runaway loops }); ``` All endpoints use JSON: send every body as `Content-Type: application/json` (with authentication off the daemon refuses anything else with `415 UNSUPPORTED_MEDIA_TYPE`). `$TOKEN` is the `apiToken` that `beignet init` prints and saves to `~/.beignet/config.json` (or whatever `apiToken`/`apiKeys` you configured). Example: ```bash # Pay an invoice curl -X POST http://localhost:2112/invoice/pay-safe \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"bolt11": "lnbc..."}' # Check payment status curl http://localhost:2112/payment?paymentHash=abc123 \ -H "Authorization: Bearer $TOKEN" ``` ## Channel Strategy ### When to open channels Use the **Liquidity Advisor** to make informed decisions: ```typescript const snapshot = node.getLiquiditySnapshot(); for (const rec of snapshot.recommendations) { console.log(`[${rec.priority}] ${rec.type}: ${rec.reason}`); } ``` ### Which node to connect to Use **Channel Suggestions** for graph-aware recommendations: ```typescript const suggestions = node.getChannelSuggestions(3); for (const s of suggestions) { console.log(`${s.alias || s.nodeId} (score: ${s.score}): ${s.reason}`); } ``` ### Timing channel opens Use the **Fee Advisor** to avoid overpaying on-chain fees: ```typescript const fees = node.getFeeSnapshot(); if (fees?.recommendation === 'OPEN_NOW') { console.log('Good time to open a channel'); } else if (fees?.recommendation === 'WAIT') { console.log('Fees are high, consider waiting'); } ``` ## Liquidity Management ### Check capacity before paying ```typescript const check = node.canSend(50000); // 50k sats if (!check.canSend) { console.log('Insufficient capacity. Available:', check.availableSats, 'sats'); } ``` ### Monitor liquidity health ```typescript const snapshot = node.getLiquiditySnapshot(); console.log('Outbound:', snapshot.outboundLiquidityPct + '%'); console.log('Inbound:', snapshot.inboundLiquidityPct + '%'); ``` ## Monitoring ### Health checks ```typescript const health = node.getHealth(); // health.status: 'ready' | 'syncing' | 'degraded' ``` ### Prometheus metrics Export metrics for monitoring dashboards and alerting: ```typescript const metrics = node.getMetrics(); // Returns Prometheus text exposition format (text/plain) ``` Via HTTP (auth-exempt): ```bash curl http://localhost:2112/metrics # HELP beignet_channels_total Number of channels by state # TYPE beignet_channels_total gauge beignet_channels_total{state="NORMAL"} 2 beignet_balance_sats{type="lightning"} 50000 beignet_peers_connected 3 beignet_uptime_seconds 3600 ... ``` Via CLI: ```bash beignet metrics ``` Key metrics: `beignet_channels_total`, `beignet_payments_total`, `beignet_balance_sats`, `beignet_electrum_connected`, `beignet_peers_connected`, `beignet_uptime_seconds`, `beignet_block_height`, `beignet_payment_success_rate`, `beignet_fees_paid_sats`, `beignet_graph_nodes`, `beignet_graph_channels`. ### Event-driven monitoring ```typescript // Via EventEmitter node.on('payment:received', (info) => { console.log('Received', info.amountSats, 'sats'); }); // Via SSE (HTTP daemon) // GET /events (Server-Sent Events) // Via Webhooks (HTTP daemon) — persistent across restarts // POST /webhooks/register { "url": "https://...", "events": ["payment:received"] } ``` ### Action log Query what happened while you were away: ```typescript const logs = node.getActionLog({ category: 'payment', since: Date.now() - 3600000 }); for (const log of logs) { console.log(`[${log.action}] ${JSON.stringify(log.data)}`); } ``` ## Pre-Flight Payment Validation Before sending any payment, validate it first. `validatePayment()` checks everything in one call — invoice validity, expiry, amount limits, spending limits, channel capacity, and route availability: ```typescript const validation = node.validatePayment(bolt11); if (validation.status === 'FAIL') { console.log('Do not send:', validation.summary); // Individual check details: for (const check of validation.checks) { if (check.status === 'FAIL') console.log(` [FAIL] ${check.name}: ${check.message}`); } return; } if (validation.status === 'WARN') { console.log('Proceed with caution:', validation.summary); } // All clear — send it const result = await node.payInvoiceSafe(bolt11); ``` Via HTTP: ```bash curl -X POST http://localhost:2112/invoice/validate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"bolt11": "lnbc..."}' # Returns: { ok: true, result: { status: "OK"|"WARN"|"FAIL", summary: "...", checks: [...] } } ``` **Checks performed:** `INVOICE_DECODE`, `AMOUNT`, `EXPIRY`, `MAX_PAYMENT`, `DAILY_LIMIT`, `CAPACITY`, `ROUTE`, `SERVICE_STATE`, `CHANNELS`. ## Safety Rails Protect your agent from accidental overspend: ```typescript const node = await BeignetNode.create({ network: 'mainnet', maxPaymentSats: 100_000, // Reject any single payment over 100k sats dailySpendLimitSats: 500_000, // Cap total daily spend at 500k sats }); // This will throw SPENDING_LIMIT_EXCEEDED if the invoice is over 100k sats: await node.payInvoice(bigInvoice); // Or use validatePayment() to check before sending: const check = node.validatePayment(bigInvoice); // check.status === 'FAIL', check.summary includes "exceeds per-payment limit" ``` Both limits count the routing fee, not just the invoice amount. Every pay path sends under a fee cap: `maxFeeSats` / `maxFeeMsat` when you pass one, otherwise 1% of the amount with a 50 sat floor. `maxPaymentSats` and the daily limit are judged on the amount plus that cap when the payment is admitted, and the day is charged the amount plus the fee actually paid when it settles. A payment that fits the limit on its amount alone but not with its cap is refused, and the error says whether to lower `maxFeeSats` or the amount; `validatePayment(bolt11, amountSats, maxFeeSats)` previews the same judgement. `sendToRoute` is judged on what its first hop carries. External on-chain sends are held to both limits as well: `sendOnchain`, an address-targeted `spliceOut` and `sendDirectFunding` on the amount plus the fee, `sendMaxOnchain` on the whole sweep. A circular rebalance counts only its routing fee, and only against the daily limit. ## Error Handling ### Decision tree ``` Payment failed? ├── Is error retryable? (check isRetryableError(error)) │ ├── Yes → Retry with backoff │ └── No → Report permanent failure ├── Is it a routing error? (error.code === 'NO_ROUTE') │ └── Check liquidity, try different amount, or open new channel ├── Is it a timeout? (error.code === 'PAYMENT_TIMEOUT') │ └── Check channel health, try again later └── Is it a capacity issue? (canSend returns false) └── Open a new channel or wait for inbound payment ``` ### Safe payment pattern ```typescript // payInvoiceSafe() NEVER throws — it always returns a PaymentInfo object. // On failure, result.status === 'FAILED' and result.failureDescription contains // a machine-parseable error code like [INSUFFICIENT_BALANCE], [INVOICE_EXPIRED], etc. const result = await node.payInvoiceSafe(bolt11); if (result.status === 'COMPLETED') { // Cryptographically verify the proof // Get a standalone proof bundle for record-keeping const proof = node.getPaymentProof(result.paymentHash); // { paymentHash, preimage, amountSats, completedAt, invoice?, hopCount?, feeSats? } // Verify the proof cryptographically (SHA256(preimage) === paymentHash) const verification = node.verifyPaymentProof(result.paymentHash); console.log('Valid proof:', verification.valid); } else { // result.status === 'FAILED' console.log('Failure:', result.failureDescription); // Parse the error code from failureDescription for programmatic handling: // e.g. "[INSUFFICIENT_BALANCE] Not enough outbound capacity" } ``` ### Payment queuing For batch payments with concurrency control. The queue is **persistent**: queued payments survive daemon restarts and crashes, and dispatch once a channel can carry them after the next start. A payment that was mid-dispatch at the restart is checked against the node's own record for its invoice before anything sends it again: one that was paid is recorded `completed`, one whose HTLCs are still out stays `dispatching` until they resolve, and only one that paid nothing is queued again. A dispatch whose HTLC is still out when the queue's own payment timeout fires (60 s by default) is not recorded `failed` either: it stays `dispatching` and is recorded from the node's outcome, `completed` when the payment settles and `failed` once every HTLC resolved with nothing paid (issue #976). A `failed` entry is a verdict; a `dispatching` one is still being paid, so do not enqueue its invoice again. `listQueue()` holds every queued and dispatching entry but only the 1000 most recently finished ones. Look an entry up by id to follow it: `getQueuedPayment(id)` reads the database for one that is no longer listed, and `listQueueHistory({ limit, before })` pages through every finished entry, newest first. ```typescript const queue = node.enqueuePayment(bolt11, 1); // priority 1 (highest) console.log('Queued:', queue.id); // Monitor progress const entry = node.getQueuedPayment(queue.id); const items = node.listQueue(); ``` ## Keysend (Spontaneous Payments) Send payments without an invoice using keysend (bLIP-0003). Critical for AI agents making spontaneous payments: ```typescript // Safe pattern — never throws const result = await node.sendKeysendSafe( '03...destination_pubkey', // recipient node pubkey 1000, // amount in sats 60_000, // timeout in ms (default: 60s) 50, // max fee in sats (optional) { purpose: 'tip' }, // metadata (optional) ); if (result.status === 'COMPLETED') { console.log('Keysend sent! Preimage:', result.preimage); } else { console.log('Failed:', result.failureDescription); } // Throwing pattern — for try/catch workflows const payment = await node.sendKeysend('03...pubkey', 1000); ``` Via HTTP: ```bash # Safe (returns FAILED status, never errors) curl -X POST http://localhost:2112/keysend/safe \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"pubkey": "03...", "amountSats": 1000}' # Throwing (returns error on failure) curl -X POST http://localhost:2112/keysend \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"pubkey": "03...", "amountSats": 1000, "maxFeeSats": 50}' ``` ## Channel Health Monitor individual channel health for proactive liquidity management: ```typescript const health = node.getChannelHealth(channelId); // IChannelHealth { // channelId, state, localBalancePct, remoteBalancePct, // htlcCount, maxHtlcs, capacitySats, warnings // } // Warnings indicate actionable issues: // - LOW_OUTBOUND_LIQUIDITY: local balance < 10% — can't send // - LOW_INBOUND_LIQUIDITY: remote balance < 10% — can't receive // - HTLC_SLOTS_NEARLY_FULL: active HTLCs > 80% of max // - AWAITING_REESTABLISH: channel pending reconnection for (const warning of health.warnings) { console.log('Warning:', warning); } ``` Via HTTP: ```bash curl "http://localhost:2112/channel/health?channelId=abc123..." \ -H "Authorization: Bearer $TOKEN" ``` ## Payment Lifecycle ### Timeout behavior At its timeout `payInvoice()` fails the payment only when no HTLC is out for it. With one still in flight the record stays `PENDING` until that HTLC resolves (it can still settle after the timeout fires), no further route is tried after the timeout, and the record is failed when the HTLC fails or its on-chain timeout resolves; the `PAYMENT_TIMEOUT` message says so, and `payInvoiceSafe()` then returns that `PENDING` record (issue #976). Check `getPayment(hash)` before retrying: a `PENDING` payment is still being paid, and the engine refuses a second payment to it in any case. ### Duplicate payment protection Retrying the same invoice while the payment is still `PENDING`, while any HTLC it sent is still out (a payment that timed out at the wall clock is not over until its HTLC resolves), or after it completed will throw `DUPLICATE_PAYMENT`. This holds for `payInvoice()`, `payInvoiceSafe()`, `sendPaymentAsync()` (`POST /invoice/pay-async` answers 409 `DUPLICATE_PAYMENT`, not a retryable 502), BOLT 12 payments and `sendToRoute()` alike, on a node that still has its payment records (a completed record is refused from memory, and from the database once pruned from memory after 24 hours); a seed-only restore has no records to refuse from. `payInvoiceSafe()` and `payInvoiceWithRetry()` return the existing record instead of throwing. A failed attempt can be sent again once the failed HTLC's removal is irrevocable (the peer's `revoke_and_ack` for the commitment without it); until then it still counts as in flight, and the engine's own retry of a temporary failure waits for the same moment (issue #989). The correct pattern: check the payment status first, use `waitForPayment()` if still pending. ### Method comparison | Method | Blocks? | Throws on failure? | Best for | |--------|---------|-------------------|----------| | `payInvoice()` | Yes | Yes | Simple scripts | | `payInvoiceSafe()` | Yes | No (returns `FAILED`, or the `PENDING` record after a timeout with an HTLC still out) | Agent loops | | `sendPaymentAsync()` | No | Only at submission (drain, limits, decode, no route) | Fire-and-forget | | `payInvoiceWithRetry()` | Yes | No | Production agents | ### Recommended safe pattern ```typescript import { BeignetNode, isRetryableError } from 'beignet/cli'; async function safePay(node: BeignetNode, bolt11: string): Promise { // 1. Check if we already attempted this payment const decoded = node.decodeInvoice(bolt11); const existing = node.getPayment(decoded.paymentHash); if (existing?.status === 'COMPLETED') return; // Already paid if (existing?.status === 'PENDING') { // Wait for in-flight payment instead of creating a duplicate await node.waitForPayment(decoded.paymentHash); return; } // 2. Use payInvoiceWithRetry for automatic backoff const result = await node.payInvoiceWithRetry(bolt11, { maxRetries: 3, backoffMs: 2000, maxFeeSats: 100, }); console.log('Status:', result.status, 'Attempts:', result.attempts); } ``` ## Payment Retry with Backoff Instead of implementing your own retry loop, use the built-in retry method: ```typescript // Retries up to 3 times with exponential backoff (2s, 4s, 8s). // Automatically stops retrying if drain mode is enabled (SERVICE_DRAINING). const result = await node.payInvoiceWithRetry(bolt11); console.log('Attempts:', result.attempts, 'Status:', result.status); // Custom retry options const result = await node.payInvoiceWithRetry(bolt11, { maxRetries: 5, backoffMs: 1000, // 1s base delay maxFeeSats: 100, // cap routing fees cltvLimit: 144, // optional: no HTLC may expire more than 144 blocks // above the current tip; CLTV_EXCEEDS_MAX if no route fits }); // Monitor retries via events node.on('payment:retry', (data) => { console.log(`Retry ${data.attempt}/${data.maxRetries} in ${data.nextRetryMs}ms: ${data.error}`); }); ``` Via HTTP: ```bash curl -X POST http://localhost:2112/invoice/pay-retry \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"bolt11": "lnbc...", "maxRetries": 3, "backoffMs": 2000}' ``` Via CLI: ```bash beignet invoice pay-retry lnbc... --max-retries 5 --backoff-ms 1000 --max-fee 100 ``` ## Peer Connection Timeout By default, `connectPeer()` times out after 15 seconds to prevent hangs on unreachable hosts: ```typescript const node = await BeignetNode.create({ network: 'mainnet', connectTimeoutMs: 10_000, // 10 second timeout (default: 15s) }); // Throws CONNECT_TIMEOUT if the peer is unreachable within the timeout await node.connectPeer(pubkey, host, port); ``` Via environment variable: ```bash export BEIGNET_CONNECT_TIMEOUT_MS=10000 ``` ## Filtering Payments by Metadata Agents can store request IDs in payment metadata and query by them later: ```typescript // Attach metadata when paying await node.payInvoice(bolt11, { metadata: { requestId: 'order-12345', agent: 'purchasing-bot' } }); // Later, filter payments by metadata const payments = node.listPayments({ metadataKey: 'requestId', metadataValue: 'order-12345' }); // Returns only payments where metadata.requestId === 'order-12345' // Filter by key existence (any value) const allTagged = node.listPayments({ metadataKey: 'agent' }); ``` Via HTTP: ```bash curl "http://localhost:2112/payments?metadataKey=requestId&metadataValue=order-12345" \ -H "Authorization: Bearer $TOKEN" ``` ## Electrum Failover For production reliability, configure multiple Electrum servers: ```typescript const node = await BeignetNode.create({ network: 'mainnet', electrumServers: [ { host: 'bitkit.to', port: 9999, tls: true }, { host: 'electrum.blockstream.info', port: 50002, tls: true }, ], }); // Failover is automatic — when the current server fails, beignet reconnects to the next one node.on('electrum:failover', (data) => { console.log(`Switched from ${data.from.host}:${data.from.port} to ${data.to.host}:${data.to.port}`); }); ``` The readiness checker will warn if only one server is configured: ```typescript const report = node.getMainnetReadiness(); // Check: ELECTRUM_REDUNDANCY — WARN if < 2 servers ``` ## Automated Backups Enable automated periodic backups for unattended operation: ```typescript const node = await BeignetNode.create({ network: 'mainnet', backupPath: '/var/backups/beignet/node.db', backupIntervalMs: 6 * 60 * 60 * 1000, // every 6 hours (default) }); // Monitor backup status node.on('backup:completed', ({ path, timestamp }) => { console.log('Backup saved to', path); }); node.on('backup:failed', ({ path, error }) => { console.error('Backup failed:', error); }); // Trigger on-demand backup await node.triggerBackup(); ``` Via CLI: ```bash # Start with automated backups beignet start --backup-path /var/backups/beignet/node.db --backup-interval 21600000 # Manual backup beignet backup /tmp/snapshot.db ``` ## Auto-Open Minimum Channels Ensure your node always has sufficient channels. The method automatically connects to peers using gossip graph addresses before opening: ```typescript // Auto-connect + open channels up to a minimum count const channels = await node.ensureMinimumChannels(3, 500_000); // Returns existing ready channels + newly opened channels console.log('Channels:', channels.length); // Or connect + open a specific channel in one call: const ch = await node.connectAndOpenChannel(pubkey, host, port, 500_000); ``` Via HTTP: ```bash curl -X POST http://localhost:2112/channels/ensure-minimum \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"count": 3, "satsPerChannel": 500000}' ``` ## Backup & Recovery ```typescript // Manual backup await node.backup('/path/to/backup.db'); // Automated backups (configured at node creation) const node = await BeignetNode.create({ network: 'mainnet', backupPath: '/var/backups/beignet/node.db', backupIntervalMs: 6 * 60 * 60 * 1000, }); // Recovery: create node with same mnemonic const recovered = await BeignetNode.create({ mnemonic: savedMnemonic, network: 'mainnet', }); // Channels and payment history are restored from SQLite ``` ## Spending Limits Enforce a daily budget to prevent runaway spending by AI agents: ```typescript const node = await BeignetNode.create({ network: 'mainnet', dailySpendLimitSats: 100_000, // 100k sats/day budget }); // Check current spend info const info = node.getDailySpendInfo(); console.log('Limit:', info.limitSats, 'Spent:', info.spentSats, 'Pending:', info.pendingSats, 'Remaining:', info.remainingSats); // Resets at midnight UTC (info.resetsAt) // payInvoice and sendKeysend will throw SPENDING_LIMIT_EXCEEDED if the limit is hit. // Spend is recorded when a payment settles, once, even when the settle lands after // payInvoice's timeout or after a restart; failed payments do not count against the limit. // The ledger is persisted: a restart within the UTC day resumes the day's total. // Concurrent payments are guarded by a pending counter to prevent overshoot. ``` Via environment variable: ```bash export BEIGNET_DAILY_SPEND_LIMIT_SATS=100000 ``` Via CLI: ```bash beignet start --daily-spend-limit 100000 ``` Via HTTP: ```bash curl http://localhost:2112/spend-limit -H "Authorization: Bearer $TOKEN" # { "ok": true, "result": { "limitSats": 100000, "spentSats": 42000, "remainingSats": 58000, "pendingSats": 0, "resetsAt": 1709078400000 } } ``` ## Paying for APIs with L402 L402 (formerly LSAT) is the Lightning-native way to buy HTTP API access: no signup, no API key, no account. The server answers an unauthenticated request with `402 Payment Required` plus a macaroon and an invoice; the client pays and retries with the macaroon and the preimage. ```typescript const result = await node.l402Fetch( 'https://api.example/v1/data', { method: 'GET' }, { maxPriceSats: 50 } // hard cap on what ONE challenge may cost ); console.log(result.status, result.body); console.log('paid:', result.paid, 'cost:', result.amountPaidSats, 'sats'); ``` What the client guarantees before any payment leaves: - The invoice's payment hash matches the hash the macaroon commits to. A server cannot bill for one hash and hand you a token bound to another. - The price is known and under `maxPriceSats`. An amountless invoice is refused outright, since its cost cannot be capped, and a sub-satoshi price rounds up rather than down. - The routing fee is capped too. `maxFeeSats` defaults to 5% of the price with a 5 sat floor rather than to no cap: the invoice comes from a remote header, and its routing hints set the fee, so an uncapped fee is an uncapped payment no matter how small the price is. - A macaroon that cannot be parsed is refused, so an unverifiable commitment is never paid. `allowUnverifiedMacaroon: true` overrides this and should stay off. A macaroon that cannot be sent back in a header (one carrying whitespace, which base64 decoding would happily ignore) is refused before paying, not after. - The challenge came from the origin you asked for. A redirect to another origin is not paid unless you pass `allowCrossOriginChallenge: true`, and even then only for a GET or HEAD request. - Both halves of the challenge come from the SAME entry in the `WWW-Authenticate` header, so a reflected or multi-scheme header cannot pair a macaroon with someone else's invoice. - At most one payment happens per call. A server that keeps returning 402 gets paid once and the 402 is handed back to you. `maxPriceSats` is per request; your `dailySpendLimitSats` and `maxPaymentSats` still apply underneath it. An unattended agent wants both: one bounds a single purchase, the other bounds the wallet. The wallet limits count the invoice amount plus the routing-fee cap, so the L402 fee cap above is also what the wallet limits are judged against for that purchase. Over HTTP, `POST /l402/fetch` honours `X-Idempotency-Key`, so a retried fetch replays the first result instead of buying a second challenge. Paid credentials are reused for the rest of the process lifetime, scoped per origin, so a paid API is paid for once rather than per request: ```typescript node.listL402Credentials(); // what has been paid for node.forgetL402Credential(scope); // drop one, so the next call pays again ``` Via HTTP: ```bash curl -X POST http://localhost:2112/l402/fetch -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"url":"https://api.example/v1/data","maxPriceSats":50}' ``` Via CLI: ```bash beignet l402 fetch https://api.example/v1/data --max-price 50 beignet l402 credentials ``` Serving L402-gated endpoints from your own node is not supported yet; this is the client half. ## Idempotency Keys Prevent duplicate payments from agent retry loops by adding the `X-Idempotency-Key` header to payment requests: ```bash # First request — payment is executed, response is cached for 24 hours curl -X POST http://localhost:2112/invoice/pay-safe \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: order-12345" \ -d '{"bolt11": "lnbc..."}' # Retry with same key + same body — returns cached response (no duplicate payment) curl -X POST http://localhost:2112/invoice/pay-safe \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "X-Idempotency-Key: order-12345" \ -d '{"bolt11": "lnbc..."}' # Same key with DIFFERENT body — returns 409 IDEMPOTENCY_CONFLICT ``` Supported endpoints: `/invoice/pay`, `/invoice/pay-safe`, `/invoice/pay-async`, `/invoice/pay-retry`, `/keysend`, `/keysend/safe`, `/l402/fetch`, `/rebalance`, `/advisor/execute-rebalances`, `/direct-funding/send`, `/send`, `/send-max`, `/offer/pay`, `/channel/asset-splice`, `/channel/splice-out`, `/channel/open`, `/channel/open-v2`, `/channel/open-zeroconf`, `/channel/connect-and-open`. Any other `POST` that carries the header is refused with `400 INVALID_PARAMS` and does not run, so a key is never silently dropped. Drop the header for those routes. A BOLT 12 offer payment needs the key more than a BOLT 11 one: every `POST /offer/pay` asks the payee for a fresh invoice with a fresh payment hash, so nothing but the key can tell a retry from a new payment. That holds after a `504 PAYMENT_TIMEOUT` too, whose error carries the `paymentHash`: a keyed retry answers `200` with the payment once it completed and `409 DUPLICATE_PAYMENT` while an HTLC for it can still settle, and asks for a new invoice only once nothing sent for the first can (issue #1094). A keyed `POST /keysend` that timed out is answered the same way, since a rerun would pick a fresh preimage (issue #1133). Query `GET /payment?paymentHash=...` rather than retrying in a loop. The same applies to the on-chain sends: a retried `POST /send` that carries the key of a send already broadcast returns that broadcast's txid instead of spending again. The cache is in memory, so it is empty after a daemon restart. Concurrent requests are covered too: a keyed request that arrives while the first one with that key is still running waits for it and receives the same response (or the same error), and one with a different body gets the 409 at once, so the handler never runs twice for one key. ## Graceful Shutdown (Drain Mode) Stop accepting new payments, wait for in-flight ones to settle, then shutdown: ```bash # Drain mode: rejects new payments (SERVICE_DRAINING), waits up to 60s for pending payments curl -X POST http://localhost:2112/stop \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"drain": true, "drainTimeoutMs": 60000}' ``` Programmatic: ```typescript node.setDraining(true); // New payInvoice/sendKeysend calls will throw SERVICE_DRAINING // Wait for in-flight payments... while (node.hasPendingPayments()) { await new Promise(r => setTimeout(r, 2000)); } await node.gracefulShutdown(); ``` ## Security - **API Token**: `beignet init` mints one and saves it to the config; always keep `apiToken` (or `apiKeys`) set in production. Without one the daemon warns at start and falls back to browser guards (JSON-only bodies, no foreign `Origin`, loopback `Host` only), which keep a web page out but not another local process. - **Mnemonic**: Store securely, never log - **Network**: Bind daemon to `127.0.0.1` (default) - **TLS**: For production, enable HTTPS with `--tls-cert` and `--tls-key` (or `BEIGNET_TLS_CERT`/`BEIGNET_TLS_KEY` env vars) - **CORS**: Only enable if needed, specify exact origin - **Spending Limits**: Set `dailySpendLimitSats` to cap daily agent spending - **Idempotency Keys**: Use `X-Idempotency-Key` header on payment requests to prevent duplicates - **Webhook Secrets**: Use HMAC-SHA256 verification (the webhook rows hold only a hash; the secret itself is kept in the encrypted wallet data so deliveries stay signed across restarts) - **Rate Limiting**: Enable `rateLimit` option to protect against runaway agent loops (429 `RATE_LIMITED` response). Every route counts, the unauthenticated health and spec endpoints included; `/metrics` is auth-gated (it reports balances) unless `metricsPublic` is set. Buckets are keyed on the connecting address, so behind a reverse proxy all clients share one bucket unless you list the proxy's IP in `rateLimit.trustedProxies`, which keys on the client address the proxy reports via `X-Forwarded-For`. Never front the daemon with a proxy you do not control when the limiter matters: the header is only trusted from listed addresses. ## Mainnet Checklist Use the built-in readiness checker: ```typescript const report = node.getMainnetReadiness(); console.log('Score:', report.score + '/100'); console.log('Ready:', report.ready); for (const check of report.checks) { const icon = check.status === 'PASS' ? 'OK' : check.status === 'WARN' ? '!!' : 'XX'; console.log(`[${icon}] ${check.name}: ${check.message}`); } ``` ## Upgrade Path Beignet follows semver. When upgrading: 1. **Backup** the database before upgrading 2. **Read** the changelog for breaking changes 3. **Test** on testnet/regtest first 4. **Monitor** the action log after upgrading ## Payment Intelligence Estimate payment success before sending: ```typescript const estimate = node.estimatePayment(bolt11); if (estimate) { console.log('Success probability:', estimate.successProbabilityPct + '%'); console.log('Estimated fee:', estimate.estimatedFeeSats, 'sats'); console.log('Route quality:', estimate.routeQuality); if (estimate.warning) console.log('Warning:', estimate.warning); } ``` ## Time-Windowed Statistics Get stats for a specific time window: ```typescript // Last hour stats const hourStats = node.getStats(3600000); console.log('Payments sent (last hour):', hourStats.totalPaymentsSent); console.log('Avg payment time:', hourStats.avgPaymentTimeSec, 'sec'); console.log('Avg fee %:', hourStats.avgFeePct); ```