# DuckLedger: Full Context & Documentation > DuckLedger is a multi-tenant SaaS financial intelligence and unit economics platform. It reconciles revenue from payment gateways (Asaas, Stripe, Pagar.me, Paddle, Iugu, Mercado Pago, AbacatePay) with cloud infrastructure costs (AWS Cost Explorer, Google Cloud, Azure) and AI token consumption (OpenAI, Anthropic, Bedrock, OpenRouter) to deliver real net margins, contribution economics per customer, and cohort retention. --- ## 1. Product Overview & Architecture ### The Problem DuckLedger Solves Payment gateways show gross revenue collections. Cloud dashboards show aggregated infrastructure costs. Neither system connects the two. For SaaS founders, CTOs, and tech finance operators, this disconnect hides crucial realities: - A customer paying R$ 299/mo may consume R$ 380/mo in cloud database queries, bandwidth, and AI tokens (negative contribution margin). - Aggregated MRR growth can mask declining net cash margins due to unoptimized cloud infrastructure or escalating LLM token bills. - Startup cloud credits mask underlying unit economics deficits until the "credit cliff" arrives. DuckLedger solves this by unifying: 1. **Multi-Gateway Revenue & Subscriptions**: Normalized MRR/ARR waterfall (New, Expansion, Contraction, Churn) across 7 gateways in BRL and USD with official Brazilian Central Bank PTAX exchange rates. 2. **Cloud & Infrastructure Cost Attribution**: AWS Cost Explorer ingestion, Google Cloud, and Azure billing attributed to products, environments, and customer workspaces. 3. **AI & LLM Token Economics**: Metering of prompt, completion, thinking, and cached tokens from OpenAI, Anthropic, OpenRouter, and AWS Bedrock via the `@duckledger/usage` SDK. 4. **Cohort Economics by Net Margin**: Retention tracking not just by active seats, but by cumulative net cash profit generated by each cohort over time. 5. **Platform Billing**: Native multi-tenant billing engine with Pix and Credit Card, grace periods, lifecycle notifications, and usage quota enforcement. --- ## 2. FinOps & Cloud Economics Knowledge Base ### 2.1 Reducing Cloud Costs by up to 40% (AWS, GCP, Azure) - **NAT Gateway & Inter-AZ Traffic**: The #1 silent AWS cost trap. NAT Gateways charge ~$0.045/hour plus $0.045 per GB processed. Fix: Provision free Gateway VPC Endpoints for S3 and DynamoDB; keep high-chatter microservices within the same Availability Zone. - **Right-Sizing & ARM Migration**: Analyze P95/P99 CPU and RAM metrics. Migrate x86 workloads to ARM architectures (AWS Graviton `t4g`/`c7g`, GCP Tau T2A) for 20% lower cost and up to 40% higher efficiency. - **Zombie Storage**: Detect unattached EBS/Persistent Disk volumes and unmanaged snapshots without lifecycle expiration rules. - **Commitment Strategy**: Combine Compute Savings Plans (covering 50-60% of baseline consumption) with Spot instances for asynchronous queues and workers. ### 2.2 Cloud Startup Credits (AWS Activate, Google Cloud, Microsoft Founders Hub) - **Program Tiers**: - AWS Activate: $1k-$2k (Founders) up to $100k (Portfolio with accelerators/VCs). - Google for Startups: Up to $100k-$200k in Year 1, with Vertex AI and Workspace benefits. - Microsoft Founders Hub: Progressive tiering up to $150k with Azure OpenAI credits. - **Non-Covered Items**: Third-party Marketplace subscriptions (Datadog, MongoDB Atlas, Snowflake), domain registration fees, and commercial proprietary software licenses. - **The Credit Cliff (Ressaca dos Créditos)**: Startups that inflate infrastructure while on credits risk severe cash burn when credits expire. DuckLedger tracks real underlying infrastructure burn rate against paid gateway MRR from day one. ### 2.3 Cloud Infrastructure Comparison for SaaS - **Container Compute**: Google Cloud Run leads in developer experience and scale-to-zero; AWS ECS Fargate provides deep VPC enterprise controls; Azure Container Apps integrates smoothly with Microsoft ecosystems. - **Data Egress**: Cloud egress fees ($0.08-$0.12/GB) penalize high-bandwidth applications. Mitigation: Cloudflare CDN caching and zero-egress S3-compatible storage (Cloudflare R2). - **Bare Metal / Hybrid Alternatives**: Dedicated hardware (Hetzner, OVH) running Docker Compose or Coolify can reduce hardware costs by 70-80% for bootstrapped SaaS companies with stable workloads. ### 2.4 Token Economics & AI Cost Attribution - **Marginal Cost of AI**: Flat-rate subscriptions break when heavy users generate millions of tokens. - **Pricing Strategies**: Monthly soft caps with model fallbacks, pre-paid credit wallets, or pass-through pricing with margin markups. - **Prompt Caching**: Anthropic and OpenAI prompt caching reduces input token costs by 75-90% for fixed context windows and system prompts. - **Model Cascading**: Route simple classifications to ultra-fast models (Claude 3.5 Haiku, GPT-4o-mini, Gemini Flash) and reserve reasoning models (Claude 3.5 Sonnet, GPT-4o) for high-complexity prompts. --- ## 3. SDK-First Integrations For Node.js, Next.js server code and NestJS: - Use `@duckledger/api-client` for API operations. - Use `@duckledger/usage` for metering AI tokens, compute traces, and event attribution. Read the complete guides at: - `https://duckledger.com/sdk-integration.md` - `https://duckledger.com/sdk-upgrade.md` ### Usage Tracking Example (Node.js/TypeScript) ```typescript import { DuckLedgerUsage } from '@duckledger/usage'; const usage = new DuckLedgerUsage({ apiKey: process.env.DUCKLEDGER_USAGE_KEY!, }); await usage.withTrace( { kind: 'ai_generation', name: 'Document Analysis', subject: user.id, workspaceId: workspace.id, }, async (trace) => { trace.step('callLlm'); usage.track({ type: 'ai.tokens_spent', workspaceId: workspace.id, data: { provider: 'anthropic', model: 'claude-3-5-sonnet', prompt_tokens: 1450, completion_tokens: 380, }, }); }, ); ``` --- ## 4. Canonical Endpoints - Web application: `https://duckledger.com` - Blog & FinOps Guides: `https://duckledger.com/blog` - Developer documentation: `https://duckledger.com/developers` - Interactive API reference: `https://duckledger.com/developers/reference` - OpenAPI 3.1 contract: `https://duckledger.com/openapi.json` - Webhook guide: `https://duckledger.com/developers/guides/webhooks` - Production API: `https://api.duckledger.com/api/v1` - Sandbox API: `https://sandbox-api.duckledger.com/api/v1` - LLM index: `https://duckledger.com/llms.txt` - Webhook debugger: `https://duckledger.com/webhooks/logs` (authenticated) --- ## 5. API Parity Status The OpenAPI contract documents all 278 callable DuckLedger operations: 94 native controller routes and 184 compatibility-gateway routes. The developer endpoint matrix maps all 208 Asaas reference operations across 33 capability groups; aliases collapse into shared DuckLedger method/path pairs. Every published operation has `x-duckledger-status: available`. --- ## 6. Outbound Webhook Setup 1. Open Developer → Webhooks → Add endpoint. 2. Select Sandbox or Production and enter that environment's final public HTTPS URL. 3. Optionally scope it to one workspace and select event filters. 4. Store the returned `whsec_...` signing secret. It is shown only once. 5. Verify signatures over the exact raw request body before parsing JSON. 6. Store `event.id` as an idempotency key, enqueue work, and return 2xx quickly. 7. Send a `ping` with the Test action and inspect Developer → Webhook Logs. Registration is also available at `POST /api/v1/webhook-endpoints`: ```json { "url": "https://product.example/webhooks/duckledger", "environment": "PRODUCTION", "workspaceId": "97d7c188-e37a-4897-a719-5537cce78af8", "description": "Production receiver", "subscribedEvents": ["payment.received", "payment.refunded"] } ``` --- ## 7. Webhook Request Contract & Verification ```http POST /webhooks/duckledger HTTP/1.1 Content-Type: application/json User-Agent: DuckLedger-Webhooks/1.0 X-DuckLedger-Event: payment.received X-DuckLedger-Delivery: 12465f62-8adf-4c7a-8be9-e84152c029e5 X-DuckLedger-Environment: PRODUCTION X-DuckLedger-Signature: t=1753208591,v1=6f1c… ``` ```json { "id": "12465f62-8adf-4c7a-8be9-e84152c029e5", "type": "payment.received", "environment": "PRODUCTION", "createdAt": "2026-07-22T17:43:11.000Z", "data": { "paymentId": "f7d6a6bc-b9dd-4f59-862d-07a884c9aca3", "externalReference": "pay_order_1842", "customerId": "fb16c0a2-b8f1-4a5f-8ff6-49e58a660e1f", "workspaceId": "97d7c188-e37a-4897-a719-5537cce78af8", "status": "RECEIVED", "amount": "299.00", "netAmount": "290.80", "feeAmount": "8.20", "currency": "BRL", "paidAt": "2026-07-22T17:42:58.000Z", "billingType": "PIX" } } ``` ### Signature Verification Algorithm Header: `t=,v1=`. Signing material: `.`. ```typescript import { createHmac, timingSafeEqual } from 'node:crypto'; export function verifyDuckLedgerSignature( rawBody: string, signatureHeader: string | undefined, signingSecret: string, ): boolean { if (!signatureHeader) return false; const parts = Object.fromEntries( signatureHeader.split(',').map((segment) => { const [key, ...value] = segment.trim().split('='); return [key, value.join('=')]; }), ); const timestamp = Number(parts.t); if (!Number.isFinite(timestamp) || !parts.v1) return false; if (Math.abs(Date.now() / 1000 - timestamp) > 300) return false; const expected = createHmac('sha256', signingSecret) .update(`${timestamp}.${rawBody}`) .digest('hex'); const provided = Buffer.from(parts.v1, 'utf8'); const expectedBytes = Buffer.from(expected, 'utf8'); return provided.length === expectedBytes.length && timingSafeEqual(provided, expectedBytes); } ``` --- ## 8. Event Catalog - `payment.created`: a charge was created and is awaiting payment. - `payment.updated`: a charge changed. - `payment.authorized`: a card charge was authorized. - `payment.confirmed`: the provider confirmed payment but settlement is incomplete. - `payment.received`: funds were received; use this event to unlock paid access. - `payment.overdue`: the due date passed without payment. - `payment.refunded`: a payment was fully refunded. - `payment.partially_refunded`: part of a payment was refunded. - `payment.refund_in_progress`: the provider is processing a refund. - `payment.refund_denied`: the provider denied a refund. - `payment.chargeback_requested`: a cardholder requested a chargeback. - `payment.chargeback_dispute`: a chargeback entered dispute. - `payment.canceled`: a charge was canceled. - `payment.failed`: a charge failed. - `subscription.created`: a subscription was created. - `subscription.updated`: a subscription changed. - `subscription.inactivated`: a subscription became inactive. - `subscription.canceled`: a subscription was canceled. - `asaas.*`: all other Asaas event families and future provider events, forwarded losslessly. - `ping`: a synthetic event from the endpoint Test action. --- ## 9. HTTP API Base URLs: - Production: `https://api.duckledger.com/api/v1` with `dlk_live_...`. - Sandbox: `https://sandbox-api.duckledger.com/api/v1` with `dlk_test_...`. Machine authentication: ```http Authorization: Bearer dlk_test_. # production: dlk_live_. ``` ### Billing Resources: - `POST/GET /customers`: create and list product customers. - `POST/GET /plans`: create reusable billing plans. - `POST /payments`: create a PIX, boleto, or credit-card charge. - `GET /payments/:id/pix`: retrieve QR image and PIX copy-paste data. - `GET /payments/:id/boleto`: retrieve digitable line, barcode, and boleto URL. - `POST /payment-methods/tokenize`: exchange card data for an encrypted provider token. - `GET /payment-methods?customerId=`: list safe card display metadata. - `POST/GET /subscriptions`: create a subscription from a `planId` or explicit terms. - `POST /payments/:id/refund`: full or partial refund. - `POST /payments/:id/cancel`: cancel a charge. --- ## 10. Model Context Protocol (MCP) for AI Agents DuckLedger includes `@duckledger/mcp`, an official stdio MCP server for agentic IDEs (Cursor, Claude Desktop, Antigravity). Build: ```bash pnpm install pnpm --filter @duckledger/mcp build ``` MCP Client Configuration (`claude_desktop_config.json` or `.cursor/mcp.json`): ```json { "mcpServers": { "duckledger": { "command": "node", "args": ["/absolute/path/to/duckledger/apps/mcp/dist/index.js"] } } } ``` Resources: - `duckledger://docs/quickstart` - `duckledger://docs/webhooks` - `duckledger://docs/api` - `duckledger://docs/debugging` Tools: - `duckledger_list_webhook_events` - `duckledger_signature_example` - `duckledger_webhook_handler_example` - `duckledger_debug_webhook` - `duckledger_mcp_config`