# Agent-Native Setup Source: https://docs.delegare.dev/agent-native How to get Delegare running by talking to your AI assistant, or if you ARE the agent. Delegare is built for an agentic world. This page provides ready-to-use prompts for humans and a direct task list for AI agents to automate the integration process. ## Why `@delegare/x402` instead of official x402? The official `x402` packages are **crypto-only** and don't include discovery support. If an enterprise AI agent without a crypto wallet hits your endpoint, it fails — and your service won't appear in agent directories. `@delegare/x402` adds three things on top: 1. **Dual-Rail Fallbacks** — on-chain USDC + Fiat Credit Bundles (Stripe) in a single middleware 2. **Multi-protocol discovery** — every 402 response simultaneously emits `PAYMENT-REQUIRED` (x402 v2) and `WWW-Authenticate: Payment` (MPP / RFC 7235), making your endpoint automatically listed on [Delegare Market](https://market.delegare.dev) (which aggregates both), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com) 3. **Delegare AP2 mandates** — scoped agent spending via `X-DELEGARE-MANDATE` for human-authorized agent budgets *** ## For Humans: The "Setup Command" Copy and paste this prompt into your AI coding assistant (Cursor, Windsurf, or GitHub Copilot) to get Delegare integrated into your backend instantly. "I want to monetize my Express API using the Delegare dual-rail x402 protocol. Please perform the following steps: 1. Install `@delegare/x402` using pnpm. 2. Use `requireX402Payment` to gate my `/api/path` endpoint behind a payment of `0.05` USD. 3. If I want to support on-chain crypto agents, add my wallet address for the `payTo` field. 4. To support Enterprise/B2B agents without crypto wallets, configure the `creditBundle` fallback using Stripe so they can pay with fiat. 5. Add `declareDiscoveryExtension` with both `inputSchema` and `output.schema` to make my endpoint searchable on Delegare Market (market.delegare.dev), agentic.market, and MPPScan. Set COINBASE\_API\_KEY and COINBASE\_API\_SECRET env vars for authenticated CDP settlement." *** ## For AI Agents: Integration Checklist If you are an AI Agent reading this documentation, follow these specific tasks to complete the integration for your user. ### 1. Install Dependencies Add the dual-rail x402 middleware to the project. ```bash theme={null} pnpm add @delegare/x402 ``` ### 2. Implement the Payment Gate Mount the middleware on the targeted routes. Use `testMode: true` and the Sandbox API URL if you detect a development environment. Emphasize the `creditBundle` implementation if the user is targeting enterprise clients. ```typescript theme={null} import { requireX402Payment } from '@delegare/x402'; // Task: Apply this to routes specified by the user requireX402Payment({ price: '0.05', // 1. The Crypto Rail (Optional but recommended) payTo: '0x...', // 2. The Fiat Rail (Crucial for B2B/Enterprise Agents) creditBundle: { tiers: [ { name: 'Starter', usdCents: 1000, requests: 500 } ], purchaseUrl: 'https://api.yourdomain.com/billing', validateAndDeduct: async (token: string) => { // Task: Implement JWT validation and DB credit deduction here return { valid: true, creditsRemaining: 499, tenantId: 'org-123' }; } }, testMode: process.env.NODE_ENV !== 'production', apiUrl: process.env.NODE_ENV !== 'production' ? 'https://api.sandbox.delegare.dev/v1' : 'https://api.delegare.dev/v1' }) ``` ### 3. Setup Discovery (CDP Bazaar + MPPScan) Wrap the route with `declareDiscoveryExtension` to enable semantic search on [Delegare Market](https://market.delegare.dev), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com). The metadata is embedded in both `PAYMENT-REQUIRED` (x402 v2) and `WWW-Authenticate` (MPP/RFC 7235) on every 402 response — Delegare Market aggregates both upstream sources automatically. ```typescript theme={null} import { declareDiscoveryExtension } from '@delegare/x402'; // Task: Generate schemas based on the route's actual input/output shape declareDiscoveryExtension({ description: "Description of your service", inputSchema: { type: "object", properties: { /* Auto-generate from route parameters */ }, required: [ /* list required fields */ ] }, bodyType: "json", output: { example: { /* Auto-generate from route output */ }, // output.schema is required for CDP Bazaar to accept the catalog entry schema: { type: "object", properties: { /* Auto-generate from route output shape */ } } } }) ``` Also ensure these env vars are set for authenticated CDP settlement (required for Bazaar indexing): ```env theme={null} COINBASE_API_KEY=your-cdp-key-id COINBASE_API_SECRET=your-base64-ed25519-secret ``` *** ## Quick Reference for Agents * **Main Export:** `requireX402Payment` + `declareDiscoveryExtension` * **Differentiator:** Dual-rail (Crypto + Fiat) + multi-protocol discovery. Official x402 is crypto-only with no discovery. * **Protocols emitted:** x402 v2 (`PAYMENT-REQUIRED`), MPP/RFC 7235 (`WWW-Authenticate`), x402 v1 (JSON body) * **Settlement rails:** CDP Facilitator (x402 v2), Delegare Facilitator (x402 v1 + AP2), Stripe (credit bundles) * **Discovery:** Auto-indexed on [market.delegare.dev](https://market.delegare.dev), agentic.market, and MPPScan — Delegare Market aggregates both x402 and MPP sources # Get Delegate Balance Source: https://docs.delegare.dev/api-reference/mandates/balance GET /v1/mandates/{intentMandate}/balance Retrieve the current spending balance of an active delegate. Retrieve the spending limits and the currently available balance for a specific delegate token. ### Headers Your merchant identifier. Your merchant API key. ### Path Parameters The `intentMandate` used to authorize charges. ### Response The status of the delegate (`active`, `revoked`, `expired`). The total authorized monthly spend limit. The total amount spent by this delegate so far in the current month. The remaining available balance for the current month. The maximum permitted amount for a single transaction. ```bash Request theme={null} curl -X GET https://api.sandbox.delegare.dev/v1/mandates/dtok_abc123xyz789/balance \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "status": "active", "maxMonthlySpendCents": 5000, "currentMonthlySpendCents": 1500, "remainingMonthlySpendCents": 3500, "maxPerTxCents": 1000 } ``` # Create Setup Session Source: https://docs.delegare.dev/api-reference/mandates/create-session POST /v1/mandates Create a session to authorize a new Intent Mandate. When a user wants to enable payments for an AI agent, your backend creates a setup session. This endpoint returns a `setupUrl` where the user will securely connect their payment method and confirm spending limits. ### Headers Your merchant identifier. Your merchant API key. ### Body The maximum amount the agent can spend in a single transaction, in cents (USD). The maximum amount the agent can spend per calendar month, in cents (USD). The preferred settlement rail. Options are `"stripe"`, `"base"`, or `"both"`. ### Response The unique token for this setup session. The URL to redirect the user to complete the setup process. ```bash Request theme={null} curl -X POST https://api.sandbox.delegare.dev/v1/mandates \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" \ -H "Content-Type: application/json" \ -d '{ "maxPerTxCents": 1000, "maxMonthlySpendCents": 5000, "requestedRail": "both" }' ``` ```json Response theme={null} { "sessionToken": "sess_123456789", "setupUrl": "https://app.delegare.dev/setup/sess_123456789" } ``` # Get Session Source: https://docs.delegare.dev/api-reference/mandates/get-session GET /v1/mandates/session/{sessionToken} Retrieve the status of a setup session. Once a user completes the setup process on the `setupUrl`, you can retrieve the status of the session to get the resulting `intentMandate`. Alternatively, you can listen for the `delegate.created` webhook. ### Headers Your merchant identifier. Your merchant API key. ### Path Parameters The token generated during `Create Setup Session`. ### Response The status of the session (`pending`, `completed`, `failed`). The token your agent uses to authorize charges (only present if `status` is `completed`). ```bash Request theme={null} curl -X GET https://api.sandbox.delegare.dev/v1/mandates/session/sess_123456789 \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "status": "completed", "intentMandate": "dtok_abc123xyz789" } ``` # Revoke Delegate Source: https://docs.delegare.dev/api-reference/mandates/revoke POST /v1/mandates/{intentMandate}/revoke Revoke an active Intent Mandate, instantly preventing further charges. Revoking a delegate immediately invalidates its token. Any future charge attempts using this token will fail with a `403 Forbidden` response. ### Headers Your merchant identifier. Your merchant API key. ### Path Parameters The `intentMandate` to revoke. ### Response Will be `true` if the delegate was successfully revoked. The new status of the delegate, which will be `"revoked"`. ```bash Request theme={null} curl -X POST https://api.sandbox.delegare.dev/v1/mandates/dtok_abc123xyz789/revoke \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "success": true, "status": "revoked" } ``` # Get Merchant Stats Source: https://docs.delegare.dev/api-reference/merchants/stats GET /v1/merchants/stats Retrieve aggregated statistics for your merchant account. Get high-level statistics about your merchant account, including total processed volume and active Intent Mandates. ### Headers Your merchant identifier. Your merchant API key. ### Response The total volume processed by your merchant account in cents (USD). The current number of active Intent Mandates connected to your merchant account. The total number of successful transactions. ```bash Request theme={null} curl -X GET https://api.sandbox.delegare.dev/v1/merchants/stats \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "totalVolumeCents": 150450, "activeDelegates": 42, "transactionCount": 128 } ``` # List Transactions Source: https://docs.delegare.dev/api-reference/merchants/transactions GET /v1/merchants/transactions Retrieve a list of transactions across your merchant account. Retrieve a paginated list of all successful and failed transactions processed across all delegates connected to your merchant account. ### Headers Your merchant identifier. Your merchant API key. ### Query Parameters A limit on the number of objects to be returned, between 1 and 100. A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. ### Response Whether there are more transactions available in the list. An array of transaction objects. Unique identifier for the transaction. The ID of the Intent Mandate used for the transaction. The transaction amount in cents (USD). The status of the transaction (`succeeded`, `failed`, `pending`). The rail used for settlement (`stripe` or `base`). ISO 8601 timestamp of when the transaction occurred. ```bash Request theme={null} curl -X GET "https://api.sandbox.delegare.dev/v1/merchants/transactions?limit=10" \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "hasMore": false, "data": [ { "id": "txn_123456789", "delegateId": "del_987654321", "amountCents": 500, "status": "succeeded", "rail": "base", "createdAt": "2024-03-27T10:00:00Z" }, { "id": "txn_223456789", "delegateId": "del_187654321", "amountCents": 1200, "status": "succeeded", "rail": "stripe", "createdAt": "2024-03-26T14:30:00Z" } ] } ``` # Charge a Delegate Source: https://docs.delegare.dev/api-reference/payments/charge POST /v1/payments/charge Executes a payment using a Intent Mandate token. ### Headers | Name | Type | Required | Description | | :----------------------- | :------- | :------- | :------------------------------- | | `X-Delegare-Merchant-Id` | `string` | Yes | Your unique merchant identifier. | | `X-Delegare-Api-Key` | `string` | Yes | Your secret API key. | ### Body Parameters | Name | Type | Required | Description | | :--------------- | :------- | :------- | :----------------------------------------------- | | `intentMandate` | `string` | Yes | The user-authorized delegate token (`dtok_...`). | | `amountCents` | `number` | Yes | Amount in cents (positive integer). | | `currency` | `string` | Yes | `usd`, `usdc`, or `usdt`. | | `description` | `string` | Yes | Max 500 characters. Shown on user statement. | | `idempotencyKey` | `string` | Yes | Unique key to prevent duplicate charges. | | `metadata` | `object` | No | Key-value pairs for your own tracking. | ### Response Unique identifier for this transaction. `completed`, `pending`, or `failed`. The final charged amount. `fiat` (Stripe) or `crypto` (Base). On-chain transaction hash (if crypto was used). Stripe internal ID (if fiat was used). ### Errors | Status | Code | Description | | :----- | :------------------------ | :--------------------------------------------------- | | 400 | `validation_error` | Missing or malformed parameters. | | 402 | `per_tx` | Amount exceeds the delegate's per-transaction limit. | | 402 | `monthly` | Charge would exceed the delegate's monthly limit. | | 402 | `merchant_limit_exceeded` | Amount exceeds merchant-specific limits. | | 403 | `merchant_inactive` | Your merchant account is not active. | | 429 | `rate_limit_exceeded` | Too many requests. | # Get Receipt Source: https://docs.delegare.dev/api-reference/payments/get-receipt GET /v1/payments/{transactionId}/receipt Retrieve a receipt for a processed payment transaction. Retrieve details of a specific payment, including its status, the rail used, and timestamps. ### Headers Your merchant identifier. Your merchant API key. ### Path Parameters The unique ID of the transaction to retrieve. ### Response The unique identifier for the transaction. The status of the transaction (`succeeded`, `failed`, `pending`). The transaction amount in cents (USD). The currency code, e.g., `"usd"`. The rail used for settlement (`stripe` or `base`). A hosted URL to view the transaction receipt, if applicable. ```bash Request theme={null} curl -X GET https://api.sandbox.delegare.dev/v1/payments/txn_123456789/receipt \ -H "X-Delegare-Merchant-Id: your_merchant_id" \ -H "X-Delegare-Api-Key: your_api_key" ``` ```json Response theme={null} { "id": "txn_123456789", "status": "succeeded", "amountCents": 500, "currency": "usd", "rail": "stripe", "receiptUrl": "https://receipts.delegare.dev/txn_123456789" } ``` # Onchain Webhooks Source: https://docs.delegare.dev/api-reference/webhooks/onchain Handle incoming webhooks for crypto settlement on Base. If you support dual-rail settlement or exclusively accept crypto payments on the Base L2 network, Delegare listens to the blockchain for successful transactions and forwards the events to your webhook endpoint. ### Available Events * `payment.succeeded`: Fired when a charge successfully settles on the Base L2 rail. * `payment.failed`: Fired when an onchain transaction fails (e.g., reverted transaction, out of gas). * `delegate.created`: Fired when a user successfully connects a wallet and completes the setup session. * `delegate.revoked`: Fired when a user revokes their onchain delegate token via the Delegare dashboard or a smart contract call. ### Webhook Format Similar to fiat webhooks, onchain webhooks include a JSON payload and an `X-Delegare-Signature` header. ```json Example Payload theme={null} { "id": "evt_02H...", "type": "payment.succeeded", "data": { "transactionId": "txn_987654321", "amountCents": 500, "rail": "base", "status": "succeeded", "txHash": "0x123abc456def789..." }, "created_at": "2024-03-27T10:05:00Z" } ``` ### Differences from Stripe Onchain webhooks may contain additional metadata, such as the `txHash`, allowing you to provide a link to a block explorer like BaseScan for your users. # Stripe Webhooks Source: https://docs.delegare.dev/api-reference/webhooks/stripe Handle incoming webhooks for fiat settlement. When a transaction is settled on the fiat rail via Stripe, Delegare can forward normalized webhooks to your server. ### Available Events * `payment.succeeded`: Fired when a charge successfully settles on the Stripe rail. * `payment.failed`: Fired when a Stripe charge fails (e.g., card declined). * `delegate.created`: Fired when a user successfully completes a setup session and a delegate token is generated. * `delegate.revoked`: Fired when a user revokes a delegate token from their dashboard. ### Webhook Format All webhooks are sent as `POST` requests with a JSON body and an `X-Delegare-Signature` header for verification. ```json Example Payload theme={null} { "id": "evt_01H...", "type": "payment.succeeded", "data": { "transactionId": "txn_123456789", "amountCents": 500, "rail": "stripe", "status": "succeeded" }, "created_at": "2024-03-27T10:00:00Z" } ``` ### Verifying Signatures We strongly recommend verifying the `X-Delegare-Signature` header using your webhook signing secret (available in your dashboard) to ensure the request actually came from Delegare. # Delegare Market Source: https://docs.delegare.dev/concepts/delegare-market The unified discovery marketplace for monetized AI agent APIs — aggregating across CDP Bazaar (x402) and MPPScan (MPP) in one place. [market.delegare.dev](https://market.delegare.dev) is Delegare's agent API marketplace. It aggregates endpoints from both major agent payment discovery networks — **CDP Bazaar / agentic.market** (x402) and **MPPScan** (MPP) — into a single searchable catalog. If you build a paid API with `@delegare/x402`, your endpoint gets listed on Delegare Market automatically, alongside the upstream directories. *** ## How Listing Works When you use `@delegare/x402` with `declareDiscoveryExtension`, your 402 response simultaneously emits: * **`PAYMENT-REQUIRED` header** — x402 v2 format, read by CDP Bazaar → agentic.market * **`WWW-Authenticate: Payment` header** — MPP/RFC 7235 format, read by MPPScan Delegare Market pulls from both upstream catalogs and re-indexes them with unified search, category filtering, and quality ranking. There's nothing extra to configure — one middleware, three directories. ``` @delegare/x402 middleware │ ├── PAYMENT-REQUIRED ──→ CDP Bazaar ──→ agentic.market │ ├── WWW-Authenticate ──→ MPPScan ──→ mppscan.com │ └── Both ──────────────→ Delegare Market ──→ market.delegare.dev ``` *** ## Getting Listed ### 1. Add `declareDiscoveryExtension` to your routes ```typescript theme={null} import { requireX402Payment, declareDiscoveryExtension } from '@delegare/x402'; app.post('/api/your-endpoint', declareDiscoveryExtension({ description: "What your endpoint does, written for AI agents to understand.", inputSchema: { type: "object", properties: { yourParam: { type: "string", description: "What it does" } }, required: ["yourParam"] }, bodyType: "json", output: { example: { result: "...", costCents: 10 }, schema: { type: "object", properties: { result: { type: "string" }, costCents: { type: "number" } } } } }), requireX402Payment({ price: '0.10', payTo: '0xYourWallet' }), handler ); ``` ### 2. Trigger the first CDP settlement CDP Bazaar indexes your endpoint after the first `PAYMENT-SIGNATURE` credential settles through their facilitator. The fastest way to trigger this without waiting for organic traffic: ```bash theme={null} # In your vault/scripts directory — uses @x402/fetch with your wallet PRIVATE_KEY=0x... node dist/cdp-payment/cdp-first-payment.js ``` Or make any real payment to your endpoint using an `@x402/fetch`-based client. ### 3. Register on MPPScan Visit [mppscan.com/register](https://mppscan.com/register) and enter your server's base URL. MPPScan reads your `openapi.json` and `WWW-Authenticate` headers for discovery — no payment required. ### 4. You're listed Once both upstream sources have your endpoint, Delegare Market automatically picks it up on its next crawl. Check your listing at [market.delegare.dev](https://market.delegare.dev). *** ## Required env vars For CDP Bazaar indexing to work (step 2), the middleware needs CDP credentials to authenticate the settlement call: ```env theme={null} COINBASE_API_KEY=your-cdp-key-id # CDP API key UUID COINBASE_API_SECRET=your-base64-secret # Base64-encoded Ed25519 key (64 bytes) ``` Without these, the USDC transfer still goes through but CDP won't write the catalog entry. *** ## What Agents See A listing on Delegare Market shows agents: * **Description** — from `declareDiscoveryExtension({ description })` * **Input parameters** — from `inputSchema.properties` * **Output shape** — from `output.schema` * **Price** — from `requireX402Payment({ price })` * **Payment methods** — USDC on Base, plus fiat credit bundle if configured * **Live endpoint URL** — directly callable by agents *** ## Why One Marketplace Matters | Directory | Protocol | Indexed via | | -------------------------------------------------- | -------------- | ------------------------------- | | [agentic.market](https://agentic.market) | x402 v2 | CDP Bazaar settlement | | [mppscan.com](https://mppscan.com) | MPP / RFC 7235 | openapi.json + WWW-Authenticate | | [market.delegare.dev](https://market.delegare.dev) | Both | Aggregated from both | Agents discovering via Delegare SDK, Claude, or ChatGPT tool use can search across all x402 and MPP endpoints in one query. For merchants, one middleware integration gets you listed on all three without managing separate registrations for each protocol. # Dual-Rail Settlement Source: https://docs.delegare.dev/concepts/dual-rail-payments How Delegare settles payments across Fiat and Crypto. Delegare is built with a **dual-rail architecture**, allowing agents to settle payments through the most efficient path available—whether that's traditional fiat (Stripe) or decentralized finance (Base L2). ## What are Dual-Rails? When a merchant integrates Delegare, they can choose to accept payments via: 1. **The Fiat Rail (Stripe):** Traditional credit card and bank transfer settlement. Best for businesses that need to keep their accounting in USD/EUR. 2. **The Crypto Rail (Base):** USDC settlement on the Base Layer 2 network. Best for low-fee, instant global settlement. ## Automatic Failover One of the core benefits of the dual-rail system is **automatic failover**. If a user has both a card and a wallet connected: * The Vault will attempt the merchant's preferred rail first. * If the preferred rail fails (e.g., insufficient crypto balance or a declined card), the Vault can automatically attempt to settle on the secondary rail. * This ensures that agents can complete their tasks with the highest possible success rate. ## Merchant Experience Merchants don't need to manage multiple complex integrations. The Delegare API abstracts the rail complexity: * You call one `/charge` endpoint. * You receive one unified webhook for payment success. * You can view all transactions (fiat and crypto) in a single unified [Dashboard](https://app.delegare.dev). ## Low Fees By leveraging Base L2 for crypto payments, Delegare makes AI micro-payments economically viable: * **Under \$1.00:** 3% of the transaction amount, with a **minimum of 0.5¢** (which covers all Base network gas costs). * **\$1.00 and above:** A flat fee of **3¢ per transaction**, significantly lower than traditional payment processors. # Intent Mandates Source: https://docs.delegare.dev/concepts/intent-mandates Understanding the core primitive of the AP2-compliant Delegare protocol. An **Intent Mandate** is a cryptographically secured authorization that allows an agent to spend up to a certain amount on behalf of a user. Delegare implements the **AP2 protocol standard** for these authorizations. ## Verifiable Digital Credentials Unlike legacy API tokens, an Intent Mandate is a **Verifiable Credential (SD-JWT-VC)**. It contains the specific spending constraints (limits, merchant allowlists, expiration) and is signed by the Delegare Platform DID (`did:web:delegare.dev`) using asymmetric cryptography (ES256). ## Atomic Limit Enforcement The most critical feature of Delegare is its **guaranteed limit enforcement**. When an agent requests a charge, the Vault performs a single atomic operation in DynamoDB: 1. **Cryptographic Verification:** Verifies the `intentMandate` signature against the Platform's public key. 2. **Check Status:** Ensures the mandate is `active` and not expired. 3. **Check Allowlist:** Validates that the `merchantId` (or Merchant DID) is permitted. 4. **Check Monthly Reset:** If the current date has rolled over into a new month, the monthly spend counter is reset to zero. 5. **Conditional Increment:** Increments the spend counter only if the new total is within the user's defined limits. This approach eliminates race conditions where two agents (or the same agent calling twice) could exceed the monthly limit by hitting the API at the exact same millisecond. ## Mandate Lifecycle * **Setup:** User defines limits and connects a payment method via the Setup UI. * **Issuance:** A signed `intentMandate` (SD-JWT-VC) is issued to the agent. * **Active:** Agents present the mandate to merchants to authorize payments. * **Revocation:** Users can revoke mandates at any time via the dashboard, instantly disabling all future charges across both fiat and crypto rails. ## Security Intent Mandates are never stored in plaintext on the client. They are cryptographically signed using the Delegare Platform's private ES256 key. Because we use asymmetric signatures, anyone can verify the mandate's authenticity using the public keys published at `/.well-known/jwks.json`, but only the Vault can issue them. Even if a merchant database is compromised, a mandate cannot be modified to increase its own spending limits without breaking the cryptographic signature. # Security Model Source: https://docs.delegare.dev/concepts/security-model How Delegare ensures safe, spend-limited payments for AI agents — architecture, threat model, and data handling. When giving an AI agent economic capabilities, the most critical question is: **"What happens if the agent goes rogue or the merchant is compromised?"** Delegare's architecture is designed around least privilege, strict enforcement, and zero custody. This page is the reference for exactly what we store, what we don't, and how each component defends against realistic attacks. ## Authorization Flow The full path from buyer setup to merchant settlement. Every payment traverses the vault, which is where limits are enforced. ```mermaid theme={null} sequenceDiagram participant U as Buyer participant V as Delegare Vault participant K as AWS KMS participant A as AI Agent participant M as Merchant participant C as DelegareRouter (Base) Note over U,V: 1. One-time setup U->>V: Approve spending limits + connect payment method V->>K: Generate session key, encrypt with mandate-bound context V->>V: Store encrypted session key + issue Intent Mandate (SD-JWT-VC) V-->>A: Deliver Intent Mandate (scoped, signed, expiring) Note over A,V: 2. Runtime charge A->>V: /charge { intentMandate, amount, merchant, idempotencyKey } V->>V: Verify signature · check status · enforce limit atomically alt Crypto rail V->>K: Decrypt session key (requires exact mandate context) V->>C: payMerchant(from, to, amount) — signed by session key C-->>M: USDC transferred on-chain else Fiat rail V->>V: Create Stripe PaymentIntent on buyer's saved method V-->>M: Payout via Stripe end V-->>A: Receipt { receiptId, status, txHash? } ``` ## Core Security Principles ### 1. No Credential Sharing AI models (and the agents running them) are highly susceptible to prompt injection and data leakage. Therefore, **Delegare never exposes credit card numbers, private keys, or seed phrases to the agent.** The agent only holds an **Intent Mandate** — a cryptographic Verifiable Credential (SD-JWT-VC) that grants tightly scoped permission to spend *up to* a specific limit. See [Intent Mandates](/concepts/intent-mandates) for the anatomy of the credential. ### 2. Session Key Isolation (Crypto Rail) Each spending mandate gets its own **dedicated ERC-4337 session key** — a unique keypair generated at mandate creation time. This is the only key authorized to initiate payments from the buyer's smart wallet. **Who holds the session key?** The private key is **KMS-encrypted** and stored as a ciphertext field on the mandate's own row in DynamoDB. It is: * **Not accessible to Delegare staff** — decryption requires the exact KMS encryption context bound to that specific `mandateId`; no other context — including broad IAM access — can decrypt it. All KMS calls are audit-logged in CloudTrail. * **Not accessible to the agent** — the agent only holds the intent mandate (a spending *permission*), never the signing key. * **Not accessible to the merchant** — the merchant receives USDC directly from the Base blockchain, routed by the on-chain DelegareRouter contract. The proxy is deployed at [`0x2dD6…FB03`](https://basescan.org/address/0x2dD63b8aB1F6058C626Aa977616b0c3Fd4CDFB03) on Base mainnet and [`0x85f2…0f62`](https://sepolia.basescan.org/address/0x85f2afB670E54a3a0F31966F49A18C73ea6a0f62) on Base Sepolia. The session key can only execute `payMerchant()` calls through the DelegareRouter smart contract, which enforces token whitelisting and payment parameters on-chain. It cannot drain the wallet, transfer arbitrary tokens, or call other contracts. **Delegare does not custody your funds.** Your USDC stays in your own smart wallet (e.g. Coinbase Smart Wallet). The session key is authorized by *you* during setup to spend from your wallet up to the mandate's limit — the same way you'd authorize a subscription in your bank's app. Delegare provides the infrastructure to route these payments; the blockchain enforces the rules. ### 3. Atomic Server-Side Limits When an agent attempts a charge, the `amountCents` is evaluated against the mandate's remaining limit server-side. * DynamoDB atomic counters (`UpdateItem` with `ADD`) enforce the budget with zero race conditions. * An agent cannot send 10 concurrent requests to exhaust a \$5 limit multiple times over. * **Can an agent exceed its limit?** No. The limit is enforced atomically before any payment is initiated. ### 4. Merchant Allowlists Intent Mandates are bound to a single merchant (via their `merchantId`) or a specific allowlist. If an agent tries to use a mandate authorized for Merchant A at Merchant B, the cryptographic verification fails. The mandate is useless outside its scope. ### 5. Ephemeral and Revokable * Mandates have strict time-to-live (TTL) expirations. **Default: 1 year; configurable per mandate at setup time.** * Users can instantly revoke an active mandate via the [Delegare dashboard](https://app.delegare.dev), immediately killing the agent's ability to spend. * **Revocation wipes the encrypted session key.** Revoked mandates cannot be resurrected — the DynamoDB row is retained for audit but the encrypted private key field is removed on revocation. There is no blocklist to fall out of sync; the key material itself is gone. * Revocation propagates to both rails atomically and is effective for the next charge (no in-flight window, because every charge re-verifies the mandate at request time). * Revoking a mandate does not affect your wallet, your other mandates, or past charges. ### 6. Idempotency & Retries The `/charge` endpoint requires an `idempotencyKey`. If a network timeout occurs, the agent can safely retry with the same key without double-charging. *** ## Threat Model The defenses above mitigate concrete attacker scenarios. Each row answers "what if?" directly. | Threat | Blast Radius | What Stops It | | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | **Agent is prompt-injected** into a large charge | Capped at `maxPerTxCents`; then capped at remaining `maxMonthlySpendCents` | Atomic limit check before any rail is touched | | **Agent tries to pay a different merchant** | Zero funds moved | Merchant-binding claim in the SD-JWT; signature verification fails | | **Agent replays an old mandate after revocation** | Zero funds moved | Every charge re-verifies `status`; revoked mandates have no session key to decrypt | | **Merchant database is breached** and mandate JWTs leak | Only remaining limit on mandates issued to *that* merchant; buyer can revoke | Mandates are merchant-bound; leaked JWT is worthless at any other merchant | | **Buyer device / browser is compromised** | Attacker can create or revoke mandates; cannot drain the wallet directly | Session keys never touch the device; wallet spending requires a session key Delegare holds under KMS | | **Stripe webhook is spoofed** | Zero state change | Stripe signature verification + idempotency keys on every update | | **Delegare employee attempts to drain a buyer wallet** | No access path | KMS decryption requires per-`mandateId` context; broad IAM cannot substitute; all calls in CloudTrail | | **Delegare infra is fully breached** (hypothetical worst-case) | Attacker can drain session-key balances up to each mandate's remaining limit; cannot drain the buyer's wallet beyond authorized amounts | Router contract caps spend at the on-chain session-key allowance the buyer signed; Stripe rail enforced by Stripe's PCI boundary | | **Router contract bug** | Bounded by on-chain allowance per session key | Contract is pausable by admin multisig; buyer can revoke the on-chain session key authorization in their wallet | | **Old charge replayed by a malicious merchant** | Zero duplicate charge | Same `idempotencyKey` returns the existing receipt; no double-settlement | *** ## Data Inventory What Delegare stores, where, how it's protected, and for how long. The **Never touches Delegare** rows are the important ones. | Data | Where | Protection | Retention | | ---------------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | Card number / CVV | **Never touches Delegare** | Stripe tokenizes in-browser; we only see a Stripe `pm_` reference | N/A | | Wallet seed phrase | **Never touches Delegare** | Buyer's wallet (e.g. Coinbase Smart Wallet) keeps it | N/A | | Full wallet private key | **Never touches Delegare** | Buyer signs the session-key authorization once; we never see the wallet key | N/A | | **Session key (private)** | DynamoDB | KMS envelope encryption, context-bound to `mandateId` — cross-mandate reuse cryptographically impossible | Until mandate revoked or expired; then `REMOVE`d from the row | | Intent Mandate (SD-JWT-VC) | **Agent-side only** | Buyer controls who holds it; signed by Delegare's Platform DID | Buyer-controlled | | Stripe customer ID (`cus_…`) | DynamoDB | At-rest (AWS-managed KMS on table) | Until account closed | | Buyer email | DynamoDB | At-rest | Until account closed | | Spending-limit state (monthly counter, etc.) | DynamoDB | At-rest | 7 years (tax/compliance) | | Transaction log (amount, merchant, time, rail) | DynamoDB | At-rest | 7 years (tax/compliance) | | OAuth access / refresh tokens | DynamoDB | Hashed; TTL-bounded | Short-lived | | KMS encryption context metadata | CloudTrail | AWS-managed, immutable | 90 days (CloudTrail default) | **Delegare never sees or stores:** your card number, your CVV, your wallet seed, your wallet's main private key, or your bank credentials. What we hold is enough to route authorized amounts — and nothing more. *** ## What You Trust — And What You Don't Delegare minimizes trust by building on existing, battle-tested infrastructure rather than asking you to trust a new system: | Layer | What handles it | Trust basis | | -------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | **Fiat payments** | [Stripe](https://stripe.com) | PCI-DSS Level 1, bank-grade fraud detection, established since 2010 | | **Crypto payments** | [Base](https://base.org) (Coinbase L2) | Open-source EVM chain, secured by Ethereum L1 | | **Smart contract** | DelegareRouter | On-chain, auditable, enforces token whitelisting and payment routing | | **Session key storage** | AWS KMS + DynamoDB | KMS envelope encryption; decryption requires mandate-bound context — cross-mandate reuse is cryptographically impossible | | **Spending limits** | DynamoDB atomic counters | Race-condition-free enforcement, server-side | | **Transport** | TLS 1.2+ with HSTS | Every API + dashboard hop; certificates managed by AWS ACM | | **Operational compliance** | SOC 2 Type 2 audited AWS infra | Operated by SecureLend; full compliance posture at [securelend.trustshare.com](https://securelend.trustshare.com/home) | **Delegare is the infrastructure layer** that abstracts across these systems. It does not hold your funds, does not have access to your full wallet, and does not have the ability to spend beyond what each mandate authorizes. ### What this means in practice * **You do not trust the agent** with your card or wallet. You trust it with a scoped \$10 allowance that auto-expires. * **You do not trust the merchant** with your payment credentials. The merchant receives USDC on-chain (crypto) or a Stripe charge (fiat) — they never see your card number or private key. * **You do not trust Delegare with custody.** Your funds stay in your Stripe-linked account or your own smart wallet. Delegare routes authorized amounts using session keys you approved, over infrastructure (Stripe, Base) that exists independently of Delegare. If a merchant is compromised, the attacker only gains access to the remaining balance on mandates issued to that merchant — not your bank account, not your wallet, not any other mandate. *** ## Business Continuity A legitimate question for any custody-adjacent service: **what happens if Delegare disappears?** * **Your wallet stays yours.** The session-key authorization lives on-chain in your own smart wallet. If Delegare vanished tomorrow, the session keys we hold would simply become inert — they can only call `payMerchant()` on the DelegareRouter, and you retain the ability to revoke them directly from your wallet with no Delegare involvement. * **Your Stripe relationship stays yours.** Stripe customer records and payment methods are held in your merchant's / your own Stripe account. Delegare stores a `pm_` reference, not your card. * **Mandate records are exportable.** The dashboard exposes a full transaction and mandate history you can download at any time. * **The DelegareRouter is immutable in its rules.** Token whitelist changes and pauses are multisig-gated; no single operator can redirect funds. *** ## Known Limitations We believe honesty builds more trust than polish. Where we've chosen a trade-off, here it is: * **We rely on AWS KMS.** If AWS itself is compromised, our at-rest encryption is only as good as AWS's. We consider this acceptable because the alternative — rolling our own key management — is almost always worse. * **Fiat payments require us to store a Stripe `pm_` pointer.** This is a reference, not a card number, but it is a piece of data we retain about each buyer. Revoking a mandate and deleting the account removes it. * **No standalone third-party security audit of the vault application yet.** Delegare runs on SOC 2 Type 2 audited AWS infrastructure operated by SecureLend — the full compliance posture is published at [securelend.trustshare.com](https://securelend.trustshare.com/home). A dedicated third-party audit of the vault application and smart contract is on the roadmap and results will be published here when complete. Until then, use mandate limits that match your risk tolerance. * **Session key gas is funded by Delegare.** The 0.5¢ minimum transaction fee covers gas so neither the buyer nor the merchant pays separately. Abuse protection is rate-based; a compromised mandate could consume some gas stipend, but cannot exceed its spend limits. * **Revocation is effective for the next charge, not mid-charge.** A charge that has already passed the atomic limit check and reached the rail will complete. In practice this window is sub-second, but it is not zero. *** ## Platform Fee Transparency Delegare charges a small platform fee per transaction, separate from the underlying rail costs: | Transaction amount | Delegare fee | | ------------------ | ---------------------------------------------------------------- | | \< \$1.00 | 3% of amount | | ≥ \$1.00 | Flat 3 cents | | Minimum | 0.5 cents (**includes Base gas** — no separate gas pass-through) | Rail costs for fiat (Stripe acquiring fees) are passed through at cost. On the crypto rail, the 0.5¢ minimum already includes the session key's gas on Base, so merchants and buyers never receive a surprise gas line item. *** ## Reporting a Security Issue We welcome responsible disclosure. * **Email:** [security@delegare.dev](mailto:security@delegare.dev) * **Scope:** the Delegare vault API, the DelegareRouter smart contract, the dashboard, and the `@delegare/*` packages on npm. * **Out of scope:** denial-of-service on non-production environments, issues already covered in [Known Limitations](#known-limitations), and third-party systems we build on (Stripe, AWS, Base) — please report those to the upstream project. * **Response:** we acknowledge within 2 business days and aim to resolve or publish a mitigation within 30 days. * **Bounty:** no formal bounty program yet, but we pay fairly for valid reports and will credit you in the resolution notes if you'd like. Please **do not** open public GitHub issues for suspected vulnerabilities. # x402 Payments (Set-and-Forget) Source: https://docs.delegare.dev/concepts/x402-payments How Delegare makes x402 protocol microtransactions seamless for AI agents, with multi-protocol discovery across CDP Bazaar and MPPScan. The `x402` protocol (an extension of the HTTP `402 Payment Required` status) allows APIs to monetize individual endpoints by demanding a microtransaction before returning a resource. While `x402` is powerful for agent-to-agent (A2A) commerce, existing implementations have two critical gaps: 1. **The wallet popup** — every time an agent hits a paywall, the human user must manually confirm a transaction. 2. **Invisible to agents** — endpoints using the official `@x402` packages don't appear in any agent directory until a human manually registers them. `@delegare/x402` solves both. It combines x402 with Intent Mandates for set-and-forget payments, and simultaneously emits discovery headers that make your endpoint automatically appear on [Delegare Market](https://market.delegare.dev) (which aggregates across protocols), [agentic.market](https://agentic.market) (CDP Bazaar), and [mppscan.com](https://mppscan.com). *** ## How It Works The agent calls `POST /api/extract` on the merchant's server. The middleware responds with `402 Payment Required` containing three parallel discovery payloads: * **`PAYMENT-REQUIRED` header** (base64 JSON) — x402 v2, read by CDP Bazaar and `@x402/fetch` clients * **`WWW-Authenticate: Payment ...` header** — MPP/RFC 7235, read by MPPScan and MPP-compatible wallets * **JSON body** — x402 v1, backward-compatible with older clients `@delegare/sdk` intercepts the 402, verifies the amount is within the agent's budget, and forwards the intent mandate to Delegare's settlement infrastructure. Delegare settles on Base L2 via the mandate's session key and the DelegareRouter contract. USDC arrives directly in the merchant's wallet. No popups. The agent retries with a payment credential. The middleware verifies it and returns the gated resource. On the first settlement via the CDP Facilitator (`PAYMENT-SIGNATURE` credential), CDP writes a catalog entry. The endpoint appears on [agentic.market](https://agentic.market) within \~10 minutes. *** ## For Merchants: Monetizing APIs ### Basic setup ```bash theme={null} npm install @delegare/x402 ``` ```typescript theme={null} import express from 'express'; import { requireX402Payment } from '@delegare/x402'; const app = express(); app.get('/premium-data', requireX402Payment({ price: '0.05', payTo: '0xYourMerchantWalletAddress', }), (req, res) => { res.json({ secret: 'AI agents love this data' }); } ); ``` ### Adding agent discovery Use `declareDiscoveryExtension` before `requireX402Payment` to make your endpoint searchable on [Delegare Market](https://market.delegare.dev), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com): ```typescript theme={null} import { requireX402Payment, declareDiscoveryExtension } from '@delegare/x402'; app.post('/api/extract', declareDiscoveryExtension({ description: "Extract structured financial data from documents. $0.15/page.", inputSchema: { type: "object", properties: { documentId: { type: "string" }, domain: { type: "string", enum: ["commercial_loan", "equity_investment"] } }, required: ["documentId"] }, bodyType: "json", output: { example: { extractedData: { gross_income: 1250000 }, costCents: 150 }, // schema is required — output.example alone is not enough for Bazaar schema: { type: "object", properties: { extractedData: { type: "object" }, costCents: { type: "number" } } } } }), requireX402Payment({ price: '0.15', payTo: '0xYourWallet' }), async (req, res) => { res.json({ data: '...' }); } ); ``` ### What the middleware handles | Client credential | Rail | What happens | | ------------------------ | ------------------ | ---------------------------------------------------------- | | None | — | Returns `402` with x402 v2, MPP, and v1 discovery payloads | | `X-Bundle-Token` | Fiat credit bundle | Validates JWT, deducts credit from your DB | | `PAYMENT-SIGNATURE` | x402 v2 USDC | Settles via CDP Facilitator → indexes on agentic.market | | `X-PAYMENT` | x402 v1 USDC | Settles via Delegare Facilitator | | `X-DELEGARE-MANDATE` | AP2 intent mandate | Settles via Delegare Vault using session key | | `Authorization: Payment` | MPP/RFC 7235 | Settles via Delegare Facilitator | You never touch private keys or on-chain logic. USDC arrives directly in your wallet from the Base blockchain. ### Required env vars for Bazaar indexing ```env theme={null} COINBASE_API_KEY=your-cdp-key-id # CDP API key UUID COINBASE_API_SECRET=your-base64-secret # Base64-encoded Ed25519 key (64 bytes) ``` When set, the middleware authenticates CDP settlement calls — required for the catalog write to succeed on first settlement. ### Configuration reference ```typescript theme={null} requireX402Payment({ price: '0.05', // Decimal USDC payTo: '0xYourWallet', // Base wallet address testMode: true, // Use Base Sepolia (default: false) apiUrl: 'https://api.sandbox.delegare.dev/v1', resource: 'https://yourapi.com/api/endpoint', // Full URL — used as catalog key mimeType: 'application/json', maxTimeoutSeconds: 300, creditBundle: { ... } }); ``` ### Accessing payment context ```typescript theme={null} app.get('/premium-data', requireX402Payment({ price: '0.05', payTo: '0xYourWallet' }), (req, res) => { const payer = (req as any).x402Payer; // Payer's wallet address const txHash = (req as any).x402Transaction; // On-chain tx hash res.json({ data: '...', paidBy: payer }); } ); ``` Read the [x402 Middleware Documentation](/sdk-tools/x402-middleware) for the full configuration reference and fiat bundle setup. *** ## For Agents: Seamlessly Paying Paywalls Replace standard `fetch` calls with `delegare.fetch`. When the API returns a 402, the SDK resolves it automatically using the user's intent mandate. ```typescript theme={null} import { Delegare } from '@delegare/sdk'; const delegare = new Delegare({ merchantId: '...', apiKey: '...' }); // If the API returns a 402, the SDK auto-pays and retries — no popups. const response = await delegare.fetch( 'https://merchant.com/premium-data', { method: 'GET' }, userIntentMandate ); ``` ### How the SDK resolves x402 1. Makes the initial request. 2. On `402`, sends the intent mandate via `X-DELEGARE-MANDATE`. 3. Merchant middleware forwards to Delegare for settlement. 4. Delegare settles on-chain via the mandate's KMS-encrypted session key. 5. SDK returns the final response with the gated data. The agent never holds private keys. The session key is scoped to the individual mandate — not accessible to the agent, merchant, or Delegare. ### x402 v2 clients (`@x402/fetch`) Agents using Coinbase's `@x402/fetch` client send a `PAYMENT-SIGNATURE` credential. The middleware routes this to the CDP Facilitator, which also triggers Bazaar indexing on first settlement. ### Model Context Protocol (MCP) If your agent runs on MCP (Claude, ChatGPT, or any MCP-compatible client), the `delegare_fetch` tool handles x402 automatically: ``` "Fetch the data from https://merchant.com/premium-data using my mandate" ``` No code required — the MCP server resolves the 402 challenge behind the scenes. *** ## Discovery: How Agents Find Your API `declareDiscoveryExtension` embeds metadata in every 402 response. Three directories index it: | Platform | Protocol | Header read | How to appear | | -------------------------------------------------- | ------------- | ------------------ | ---------------------------------------- | | [market.delegare.dev](https://market.delegare.dev) | x402 v2 + MPP | Both | Auto-aggregated from the two below | | [agentic.market](https://agentic.market) | x402 v2 | `PAYMENT-REQUIRED` | Auto on first CDP Facilitator settlement | | [mppscan.com](https://mppscan.com) | MPP/RFC 7235 | `WWW-Authenticate` | Register at mppscan.com/register | Delegare Market is the primary destination — it aggregates x402 and MPP endpoints from both upstream sources. Agents using the Delegare SDK or searching via Claude/ChatGPT tools query it in one request. All three read `inputSchema` and `outputSchema` from the metadata to show agents what parameters your endpoint accepts and what it returns. # Testing & Sandboxing Source: https://docs.delegare.dev/development/testing How to test your Delegare integration safely. Delegare provides a dedicated **Sandbox** environment that mirrors production but runs on test networks. Use this environment for all development and automated testing. ## Environment URLs | Environment | Base URL | Rail (Fiat) | Rail (Crypto) | | :------------- | :------------------------------------ | :--------------- | :------------ | | **Sandbox** | `https://api.sandbox.delegare.dev/v1` | Stripe Test Mode | Base Sepolia | | **Production** | `https://api.delegare.dev/v1` | Stripe Live Mode | Base Mainnet | ## Sandbox Testing Steps ### 1. Use Test API Keys Log in to the [Sandbox Dashboard](https://app.sandbox.delegare.dev) to retrieve your Test Merchant ID and Test API Key. These keys are only valid for the sandbox URL. ### 2. Stripe Test Cards When using the Setup UI in Sandbox mode, you can use Stripe's standard test cards (e.g., `4242 4242 4242 4242`) to simulate successful or failed authorizations. ### 3. Base Sepolia ETH/USDC For crypto rail testing, ensure your test agent or user wallet has **Base Sepolia ETH** for gas and **Base Sepolia USDC** for payments. * **Base Faucet:** [https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet](https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet) ## Webhook Testing You can use tools like `ngrok` to expose your local server and set the `webhookUrl` in the Sandbox Dashboard. Delegare will sign every webhook with your sandbox-specific `webhookSecret` using HMAC-SHA256. ```bash theme={null} # Example X-Delegare-Signature verification (Node.js) const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', process.env.DELEGARE_WEBHOOK_SECRET); hmac.update(JSON.stringify(req.body)); const signature = hmac.digest('hex'); if (signature === req.headers['x-delegare-signature']) { // Verified! } ``` # Express Checkout Example Source: https://docs.delegare.dev/examples/express-checkout A complete e-commerce mock using the Delegare SDK. This example demonstrates how a merchant backend can accept `intentMandate` (SD-JWT-VC) tokens from an agent and process a payment via the Delegare SDK. The source code is available in the `examples/express-checkout` directory of the Delegare repository. ## Overview 1. **Setup Buyer:** The merchant creates a setup session for the user. 2. **Authorization:** The user completes the setup via the Delegare UI, generating an Intent Mandate. 3. **Checkout:** The AI agent sends the Intent Mandate to the merchant's `/api/checkout` endpoint. 4. **Execution:** The merchant backend uses `@delegare/sdk` to charge the mandate. ## Merchant Backend (Node.js) ```javascript theme={null} const { Delegare } = require('@delegare/sdk'); const express = require('express'); const delegare = new Delegare({ merchantId: process.env.DELEGARE_MERCHANT_ID, apiKey: process.env.DELEGARE_API_KEY, baseUrl: 'https://api.sandbox.delegare.dev/v1' }); const app = express(); app.use(express.json()); app.post('/api/checkout', async (req, res) => { const { intentMandate, item } = req.body; try { // 1. Charge the agent! const receipt = await delegare.charge({ intentMandate, amountCents: 1500, // $15.00 currency: 'usd', description: `Order: ${item}`, idempotencyKey: `order_${Date.now()}` }); res.json({ success: true, receipt }); } catch (error) { res.status(402).json({ error: error.message }); } }); app.listen(4000); ``` ## Running the Demo locally If you have the Delegare repository cloned, you can run the interactive demo: ```bash theme={null} cd examples/express-checkout pnpm install # Follow instructions in README to set your .env pnpm start ``` Then, in a separate terminal, run the buyer setup script: ```bash theme={null} node setup-buyer.js ``` This script will give you a setup URL. Open it, complete the flow in Sandbox mode, and the script will automatically output a `curl` command you can use to test the checkout! ## Testing the x402 API Paywall This example also demonstrates the `@delegare/x402` middleware, which automatically protects the `/api/premium-data` endpoint and charges AI agents \$0.05 per request. > **⚠️ IMPORTANT: x402 requires Crypto (USDC)** > The `x402` protocol settles natively on-chain. To test this flow, your "Buyer" account MUST have a **Crypto Wallet** connected. > > 1. Ensure you are testing from a separate "Buyer" account (not your Merchant account). Use an incognito window if necessary. > 2. Ensure that Buyer account has connected a Coinbase Smart Wallet (or similar) loaded with testnet USDC and ETH on Base Sepolia. > 3. When you run `node setup-buyer.js` to generate the mandate, **you must authorize the Crypto spending option**, which will require you to actively sign a transaction on the Sepolia blockchain in your wallet. (A Fiat-only mandate will fail the x402 check!) You can test this flow locally using the provided `x402.js` script! Simply add your *Crypto-authorized* mandate token to your `.env` file: ```env theme={null} DELEGARE_MANDATE=eyJhbGci... ``` Then run the script: ```bash theme={null} pnpm x402 ``` The script uses `delegare.fetch()` to automatically detect the `402 Payment Required` challenge, authorize the \$0.05 USDC payment via the Delegare SDK, and retry the request to securely fetch the premium data! > **💡 Note on Dashboard Tracking:** > If you provide a raw 0x address in `MERCHANT_USDC_WALLET` inside your `.env` that is *not* connected to your Merchant profile, the payment will succeed on-chain, but the Delegare backend won't know it belongs to you! It will be recorded under a generic "Web3 Merchant" and won't appear in your dashboard. To see x402 transactions in your dashboard, make sure you connect that exact USDC wallet via the **Payment Methods** tab first. # Introduction Source: https://docs.delegare.dev/introduction Trustless agent payment authorization for the AI economy. Delegare (Latin for "to delegate") is the first AP2-compliant payment authorization infrastructure for AI agents. It allows human users to grant spending power to AI agents by issuing Verifiable Digital Credentials (Intent Mandates), without ever handing over credit card numbers or private keys. Works with any AP2-compatible merchant globally. Runs on Stripe for fiat, Base for USDC/USDT. ## The Problem AI agents today are limited by their inability to perform economic actions. Existing solutions require either: 1. **Full Custody:** Giving an agent your credit card or wallet seed phrase (massive security risk). 2. **Pre-funding:** Locking capital into a per-agent wallet (capital inefficient). ## The Delegare Solution Delegare introduces **Intent Mandates** — cryptographically signed tokens that enforce strict spending limits, merchant allowlists, and time-based expirations. Users authorize an intent mandate once via a secure UI. Agents use the `intentMandate` to authorize payments autonomously. Settle via Stripe (Fiat) or Base L2 (Crypto) with automatic fallback. DynamoDB-backed atomic counters prevent overspending and race conditions. `@delegare/x402` emits x402 v2 and MPP headers simultaneously — auto-indexed on [market.delegare.dev](https://market.delegare.dev), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com). First AP2-compliant merchant middleware — scoped agent spending with cryptographic authorization. ## How it works 1. **Merchant** requests a setup session. 2. **User** authorizes limits (e.g., "$50/mo total, max $10 per tx"). 3. **Agent** receives a `intentMandate`. 4. **Agent** calls `/charge` with the token whenever it needs to buy something. 5. **Vault** validates limits atomically and executes the payment on the best available rail. # Quickstart Source: https://docs.delegare.dev/quickstart Get your first Delegare payment working in 10 minutes. The fastest way to understand Delegare is to run our end-to-end example. You will act as both the **Merchant** (setting up a server) and the **User** (authorizing a spending mandate). **Prerequisites:** You need Node >=22 and pnpm >=9 installed on your machine. ### 1. Get Sandbox Credentials 1. Go to the [Delegare Sandbox Dashboard](https://app.sandbox.delegare.dev). 2. Register a new test merchant account. 3. Copy your `merchantId` and `testApiKey`. ### 2. Clone the Example App We have provided an Express server that acts as a mock merchant (e.g., a pizza shop or API service). ```bash theme={null} git clone https://github.com/delegare/delegare.git cd delegare/examples/express-checkout pnpm install ``` ### 3. Configure the Environment Create an environment file: ```bash theme={null} cp .env.example .env ``` Open `.env` and paste your sandbox credentials: ```env theme={null} DELEGARE_BASE_URL=https://api.sandbox.delegare.dev/v1 DELEGARE_MERCHANT_ID="your_merchant_id" DELEGARE_API_KEY="your_test_api_key" # Optional: Set this to your USDC wallet address if you want to test x402 auto-payments # MERCHANT_USDC_WALLET="0x..." ``` ### 4. Run the Merchant Server Start your mock merchant backend: ```bash theme={null} pnpm dev ``` *(Leave this running in the terminal)* ### 5. Generate a Buyer Mandate Open a **new terminal tab** in the same directory. We will now run a script that simulates a user approving a budget for an AI agent. ```bash theme={null} pnpm setup ``` 1. The script will generate a Setup URL. Click the link to open it in your browser. 2. In the Sandbox UI, authorize a \$50/month limit for this agent. You can use Stripe test cards. 3. Once approved, return to your terminal. The script will print out a long string starting with `eyJhbGci...` - this is your **Intent Mandate**. ### 6. Execute an Agent Charge Now, pretend you are the AI agent who holds this mandate and wants to buy something from the merchant. Run this `curl` command, replacing the `intentMandate` with your token: ```bash theme={null} curl -X POST http://localhost:4000/api/checkout \ -H "Content-Type: application/json" \ -d '{ "intentMandate": "eyJhbGciOiJFU...", "item": "large_pepperoni_pizza", "deliveryAddress": "123 AI Avenue" }' ``` ### 7. View the Result Look at your first terminal (the merchant server). You should see logs indicating that the Delegare SDK successfully executed the charge against the agent's limit. **Congratulations!** You just processed an agent-authorized payment without sharing any credit card details. *** ### Next Steps * Learn how to integrate the [Typescript SDK](/sdk-tools/typescript-sdk) into your own backend. * Read about our [Security Model](/concepts/security-model) to see how limits are enforced. * Add payment capabilities to Claude Desktop with our [MCP Tools](/sdk-tools/mcp-tools). # LangChain Integration Source: https://docs.delegare.dev/sdk-tools/langchain Use Delegare directly within LangChain and LangGraph # Delegare Toolkit The Delegare toolkit enables your LangChain and LangGraph agents to execute payments, check budgets, and handle x402-gated content automatically via the [Delegare API](https://delegare.dev/). Unlike standard payment gateways, Delegare issues an **Intent Mandate** (SD-JWT-VC) rather than returning raw card details. The agent uses this mandate to request charges up to the user's pre-authorized budget, ensuring payments are entirely separated from the LLM context. ## Setup First, you need to install the `langchain-delegare` package: ```bash theme={null} pip install langchain-delegare ``` Second, sign up for a merchant account at [Delegare](https://app.delegare.dev) and retrieve your API Key and Merchant ID. Set these as environment variables: ```bash theme={null} export DELEGARE_MERCHANT_ID="your_merchant_id" export DELEGARE_API_KEY="your_api_key" ``` ## Initializing the Toolkit You can instantiate the `DelegareToolkit` using environment variables or by passing your credentials explicitly. It's recommended to define an `allowed_amounts_cents` whitelist for safety. ```python theme={null} import os from langchain_delegare import DelegareToolkit # Initialize with environment variables and a safety whitelist toolkit = DelegareToolkit.from_api_key( merchant_id=os.environ.get("DELEGARE_MERCHANT_ID"), api_key=os.environ.get("DELEGARE_API_KEY"), allowed_amounts_cents=[50, 499, 1000] # Safe whitelist: 50¢, $4.99, $10.00 ) # Get all 7 payment tools tools = toolkit.get_tools() for tool in tools: print(tool.name) ``` ## Available Tools The toolkit provides 7 unique tools designed for distinct phases of the agent payment lifecycle: 1. **`setup_spending_mandate`**: Generates a one-time browser link for the user to securely input their card/wallet. 2. **`poll_setup_session`**: Checks if the user completed the setup. Once completed, returns the `intentMandate` string. 3. **`check_mandate_balance`**: Retrieves the remaining budget of an active intent mandate. 4. **`authorize_agent_payment`**: Executes a charge against a mandate (enforced server-side). 5. **`delegare_fetch`**: Fetches URLs and automatically resolves HTTP 402 errors using the mandate. 6. **`revoke_mandate`**: Cancels an active mandate. 7. **`verify_receipt`**: Cryptographically verifies the `X-PAYMENT-RESPONSE` payload of a settled charge. ## Usage in an Agent Here is a full example showing how to initialize the tools and connect them to an agent built with LangGraph. ### Agent with Budget Awareness Delegare provides a custom `DelegareBudgetCallbackHandler` that intercepts tool completions and monitors mandate budgets automatically to stop LLMs from overspending before the Delegare API physically rejects the transaction. ```python theme={null} import asyncio import os from langchain_openai import ChatOpenAI from langchain_delegare import DelegareToolkit, DelegareBudgetCallbackHandler from langchain_core.messages import HumanMessage from langgraph.prebuilt import create_react_agent async def run_agent(): # 1. Initialize tools toolkit = DelegareToolkit.from_api_key( merchant_id=os.environ.get("DELEGARE_MERCHANT_ID"), api_key=os.environ.get("DELEGARE_API_KEY") ) tools = toolkit.get_tools() # 2. Attach a callback to halt at 90% budget utilization budget_handler = DelegareBudgetCallbackHandler( async_client=toolkit.async_client, halt_at_pct=0.90 ) # 3. Create the agent llm = ChatOpenAI(model="gpt-4o") agent = create_react_agent(llm, tools) # 4. Invoke with mandate ID loaded in context try: response = await agent.ainvoke( {"messages": [HumanMessage(content="Process a $5 charge for the API subscription using mandate 'mandate_abc123'")]}, config={"callbacks": [budget_handler]} ) print(response["messages"][-1].content) except Exception as e: print(f"Agent execution halted: {e}") if __name__ == "__main__": asyncio.run(run_agent()) ``` ### LangGraph Idempotency When dealing with payments, idempotent execution is critical. If a LangGraph workflow crashes and retries, you want to guarantee the agent doesn't double-charge the user. The integration provides `get_idempotency_key` which securely hashes LangGraph thread states into deterministic UUIDs. ```python theme={null} from langchain_delegare import get_idempotency_key def charge_node(state, config): thread_id = config["configurable"]["thread_id"] run_id = config["run_id"] tool_call_id = "call_xyz123" # usually state["tool_calls"][-1]["id"] # Derives a deterministic UUIDv5 safe_key = get_idempotency_key(thread_id, run_id, tool_call_id) # Your agent's charge logic # authorize_payment(..., idempotency_key=safe_key) ``` ## Runnables and LCEL For seamless data retrieval requiring x402 payment headers, you can use the `X402AutoPayRunnable` directly in your LCEL chains. It catches 402 errors, executes the required micro-payment via the intent mandate, and retries the fetch autonomously. ```python theme={null} from langchain_delegare import X402AutoPayRunnable x402_fetcher = X402AutoPayRunnable( sync_client=toolkit.sync_client, async_client=toolkit.async_client ) chain = x402_fetcher | prompt | model ``` # MCP Server & Tools Source: https://docs.delegare.dev/sdk-tools/mcp-tools Powering AI agents with payment capabilities via Model Context Protocol. Delegare provides an official MCP Server that enables LLMs (like Claude or GPT-4) to perform economic actions autonomously using Intent Mandates. The server is available in the `packages/mcp-server` directory of the Vault repository. ## Available Tools The MCP server exposes the following tools to the agent: ### 1. `setup_spending_mandate` Generates a setup URL for the human user. * **Input:** `maxAmountPerTxCents`, `maxMonthlySpendCents`, `railPreference` * **Output:** A markdown link for the user to authorize. ### 2. `check_mandate_balance` Allows the agent to see how much it can spend. * **Input:** `mandateId` * **Output:** Remaining monthly balance. ### 3. `authorize_agent_payment` The core tool for making purchases. * **Input:** `amountCents`, `currency`, `description`, `recipient` * **Output:** A cryptographic Intent Mandate (SD-JWT-VC) or a success receipt if the server handles the execution. ### 4. `delegare_fetch` A tool for scraping or fetching data from third-party APIs that may be monetized. * **Input:** `url`, `method`, `body`, `bundleToken` (optional) * **Output:** The fetched HTTP response content. * **x402 Auto-Payment:** If the target URL returns a `402 Payment Required` challenge, this tool intercepts it. It evaluates the payment options (Crypto USDC vs. Fiat Credit Bundle), resolves the payment using the agent's mandate or bundle token, and resubmits the request to fetch the data. ### 5. `purchase_bundle` Allows the agent to purchase an API credit bundle if a merchant requires fiat payment or if the agent doesn't have a crypto wallet. * **Input:** `merchantBundleUrl` * **Output:** A checkout link for the user to complete the fiat payment via Stripe, plus available tiers. ### 6. `check_bundle_balance` Checks the remaining requests on a purchased API credit bundle. * **Input:** `merchantBalanceUrl`, `bundleToken` * **Output:** Remaining credits and tier details. ## MCP Authentication Guard To prevent unauthorized tool calls, the MCP server implements an `mcpAuthGuard`. * Every tool call must be authorized by an OAuth session. * Credentials (`merchantId`, `apiKey`) are never exposed to the LLM prompt. * The guard injects the required metadata into the tool context based on the bearer token in the request header. ### Running Locally with Python The Delegare MCP Server is also published to PyPI, allowing you to run it locally or embed it within your own orchestration environments. ```bash theme={null} pip install delegare-mcp ``` To run the MCP server locally over `stdio`: ```bash theme={null} export DELEGARE_MERCHANT_ID="your_merchant_id" export DELEGARE_API_KEY="your_api_key" python -m delegare_mcp.server ``` #### Claude Desktop Local Config If you prefer to run the server locally rather than connecting to the remote endpoint, configure Claude Desktop to spawn the Python process: ```json theme={null} { "mcpServers": { "delegare": { "command": "python", "args": ["-m", "delegare_mcp.server"], "env": { "DELEGARE_MERCHANT_ID": "your_merchant_id", "DELEGARE_API_KEY": "your_api_key" } } } } ``` ## Usage with Claude.ai Connect Delegare as a remote MCP connector on Claude.ai: 1. Go to **Settings** → **Connectors** → **Add custom connector**. 2. Set the **Name** to `Delegare`. 3. Set the **Remote MCP server URL** to: | Environment | URL | | ----------- | -------------------------------------- | | Sandbox | `https://api.sandbox.delegare.dev/mcp` | | Production | `https://api.delegare.dev/mcp` | 4. Click **Add**. Claude.ai will automatically handle OAuth authentication when you first use a Delegare tool. ## Usage with ChatGPT 1. Go to **Settings** → **Apps** and enable **Developer mode**. 2. Click **Add app** and paste the MCP URL from the table above. 3. Open a new chat, click **+**, select **Delegare**, and start a conversation. ## Usage in Claude Desktop Add Delegare as a remote MCP server in your `claude_desktop_config.json`: ```json theme={null} { "mcpServers": { "delegare": { "type": "streamableHttp", "url": "https://api.sandbox.delegare.dev/mcp" } } } ``` # OpenClaw Plugin Source: https://docs.delegare.dev/sdk-tools/openclaw-plugin Enable autonomous payments for your OpenClaw agents. The official **Delegare** plugin for OpenClaw gives your AI agents the ability to autonomously execute payments and bypass `x402` paywalls. By installing this plugin, your agent gains access to the Delegare tool suite, allowing it to spend funds safely using a pre-authorized **AP2 Intent Mandate (SD-JWT-VC)** without needing you to approve every transaction. *** ## 1. Installation The Delegare plugin is a native OpenClaw extension. Install it directly using the OpenClaw CLI: ```bash theme={null} openclaw plugins install @delegare/openclaw-plugin ``` ## 2. Configuration & Authentication OpenClaw operates as a secure, headless execution environment. Because it cannot natively intercept web-based OAuth redirects, Delegare uses **Long-Lived Access Tokens** specifically designed for Agent configuration. Getting your agent connected is a simple, one-time setup: 1. **Ask your Agent to Connect** Simply tell your OpenClaw agent: *"Connect to Delegare."* The agent will invoke the `delegare_connect` tool, which will instantly reply with a secure, self-service setup link. 2. **Generate your Token** Click the link the agent provides (or visit [app.delegare.dev/connect/agent?platform=openclaw](https://app.delegare.dev/connect/agent?platform=openclaw)). * Log in securely using your standard Google/Apple account. * Delegare will instantly provision a 90-day secure access token for your agent. 3. **Update your Config** The dashboard will provide a pre-formatted JSON snippet. Open your OpenClaw gateway configuration file (usually located at `~/.openclaw/openclaw.json`) and paste it into your `plugins` block: ```json ~/.openclaw/openclaw.json theme={null} { "plugins": { "allow": ["delegare"], "entries": { "delegare": { "enabled": true, "config": { "accessToken": "token_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } } } }, "tools": { "allow": ["*"] } } ``` *Note: You can replace `"*"` in the tools array with specific names like `"delegare_fetch"` or `"setup_spending_mandate"` if you prefer strict capability scoping.* **Restart your OpenClaw gateway** to apply the new configuration. Your agent is now fully authenticated! *** ## 3. 🧪 Testing in the Sandbox If you are developing a local e-commerce backend and want to test the plugin without using real money, you can easily point your agent to the Delegare Sandbox API. Simply update your `config` block in `~/.openclaw/openclaw.json` to include the Sandbox `baseUrl`: ```json ~/.openclaw/openclaw.json theme={null} { "plugins": { "allow": ["delegare"], "entries": { "delegare": { "enabled": true, "config": { "accessToken": "token_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "baseUrl": "https://api.sandbox.delegare.dev/v1" } } } }, "tools": { "allow": ["*"] } } ``` *(Remember to use a Sandbox Token generated from `app.sandbox.delegare.dev` if you use the Sandbox API!)* *** ## 4. Usage Your agent is now economically enabled! Start a **new chat session** in OpenClaw (so it loads the updated tool context) and try prompting it with tasks that require payment or data retrieval: ```text Agent Prompt theme={null} Fetch the data from https://premium-api.com/data. If it asks for payment via x402, use your mandate to pay it. ``` ```text Agent Prompt theme={null} What is my current Delegare mandate balance? ``` ```text Agent Prompt theme={null} Pay @coffee-shop $5.00 for the espresso order. ``` *** ## Security Features * **Zero Popups:** Once limits are set, the agent handles transaction signing server-side. No wallet popups will interrupt its workflow. * **Non-Custodial:** Your master private key never leaves your device. The agent only receives a tightly scoped, easily revokable session key. * **Strict Bounds:** Every transaction is verified by the Vault backend against the human-defined per-transaction and monthly limits. ## Links * [MCP Tools Documentation](/sdk-tools/mcp-tools) * [Protocol Concepts](/concepts/intent-mandates) * [GitHub Repository](https://github.com/delegare/delegare) # Python SDK Source: https://docs.delegare.dev/sdk-tools/python-sdk Official Python SDK for Delegare # Python SDK The Delegare Python SDK provides robust, type-safe clients for interacting with the Delegare API. It includes fully synchronous and asynchronous implementations, Pydantic v2 typing, and seamless x402 auto-payment routines. ## Installation ```bash theme={null} pip install delegare ``` ## Quick Start ```python theme={null} import os from delegare import Delegare, ApiKeyAuth, ChargeRequest auth = ApiKeyAuth( merchant_id=os.environ.get("DELEGARE_MERCHANT_ID"), api_key=os.environ.get("DELEGARE_API_KEY") ) with Delegare(auth) as client: charge = client.charge(ChargeRequest( amountCents=500, currency="usd", intentMandate="mandate_123", idempotencyKey="idem_123", description="Data extraction" )) print(f"Charge ID: {charge.receipt_id}") print(f"Status: {charge.status}") ``` ## Features ### Synchronous and Asynchronous Clients The SDK natively supports `Delegare` and `AsyncDelegare` implementations, giving you parity regardless of whether you're using `asyncio` or standard synchronous scripts. ### X402 Auto-Payment You can use the built-in `.fetch()` utility to automatically process any HTTP requests that return `402 Payment Required` headers. The client automatically retrieves the `accepts` schema, makes the corresponding charge against the provided intent mandate, and retries the request seamlessly. ```python theme={null} response = client.fetch( "https://api.example.com/premium-endpoint", intent_mandate="mandate_123" ) print(response.json()) ``` # Shopify Custom Payment App Source: https://docs.delegare.dev/sdk-tools/shopify-app Accepting agent payments on Shopify via Delegare. The Delegare Shopify integration allows Shopify merchants to accept autonomous payments from AI agents. The prototype is available in the `packages/shopify-app` directory of the Delegare repository. ## How it works 1. **Merchant Onboarding:** The merchant installs the Delegare app on their Shopify store. The app automatically registers them as a Delegare merchant. 2. **Checkout Integration:** Delegare appears as a custom payment method during Shopify checkout. 3. **Buyer Interaction:** When a buyer selects Delegare, they are presented with a UI to enter an **Intent Mandate** (SD-JWT-VC). 4. **Autonomous Capture:** An AI agent can also intercept this session and provide the mandate autonomously via an MCP tool. 5. **Settlement:** The Shopify app uses the `@delegare/sdk` to charge the mandate, and the order is marked as **Paid** in Shopify. ## Prototype Setup To run the Shopify app prototype: ```bash theme={null} cd packages/shopify-app pnpm install # Configure your Shopify and Delegare keys in .env pnpm start ``` For a live demonstration, see the [express-checkout](/examples/express-checkout) example. # Typescript SDK Source: https://docs.delegare.dev/sdk-tools/typescript-sdk The official @delegare/sdk for Node.js and Browser. The Delegare SDK provides a simple, type-safe interface for interacting with the Delegare protocol. ## Installation ```bash theme={null} pnpm add @delegare/sdk # or npm install @delegare/sdk ``` ## Initialization Initialize the client with your Merchant credentials. ```typescript theme={null} import { Delegare } from '@delegare/sdk'; const delegare = new Delegare({ merchantId: 'm_123...', apiKey: process.env.DELEGARE_API_KEY, // Use sandbox URL for testing baseUrl: 'https://api.sandbox.delegare.dev/v1' }); ``` ## Core Methods ### Create Setup Session Generates a URL where your user can authorize a spending mandate. ```typescript theme={null} const session = await delegare.createSetupSession({ maxPerTxCents: 1000, // $10.00 maxMonthlySpendCents: 5000, // $50.00 rail: 'both', // allow fiat and crypto redirectUrl: 'https://your-app.com/callback' }); console.log(session.setupUrl); ``` ### Charge Mandate Executes a payment using an `intentMandate` (SD-JWT-VC) provided by an agent. ```typescript theme={null} const receipt = await delegare.charge({ intentMandate: 'eyJhbGci...', amountCents: 1500, currency: 'usd', description: 'AI Agent Purchase', idempotencyKey: 'order_789' }); if (receipt.status === 'completed') { console.log('Payment successful!', receipt.receiptId); } ``` ### Check Balance Query the remaining monthly limit for a specific mandate. ```typescript theme={null} const balance = await delegare.getMandateBalance('mandate_id_here'); console.log(`Remaining: $${balance.remainingMonthlyCents / 100}`); ``` ### Fetch (x402 Auto-Payment) A drop-in replacement for the native `fetch` API that automatically intercepts and handles `x402` (HTTP 402 Payment Required) challenges. If the requested endpoint returns a `402` status with `X-PAYMENT` requirements, the SDK will: 1. Verify the price is within the agent's pre-authorized spending mandate. 2. Sign the required transaction automatically under the hood (zero popups). 3. Append the signed `X-Payment` header and seamlessly retry the request. ```typescript theme={null} // Works exactly like a normal fetch, but passes the mandate as the 3rd argument const response = await delegare.fetch( 'https://api.example.com/premium-data', { method: 'GET' }, intentMandate // Your agent's SD-JWT-VC spending token ); const data = await response.json(); ``` # x402 Middleware Source: https://docs.delegare.dev/sdk-tools/x402-middleware Gate your API routes behind USDC micropayments using Google's AP2 protocol alongside multi-protocol discovery — CDP Bazaar, MPPScan, and Delegare AP2 mandates. The `@delegare/x402` package lets merchants monetize API endpoints using the [x402 protocol](/concepts/x402-payments) while crucially implementing [Google's AP2 (Agentic Payment Protocol)](https://github.com/google-agentic-commerce/AP2). This guarantees secure, autonomous transactions where the **AI agent never holds private keys, credit card credentials, or raw funds**. Instead, agents operate strictly via pre-authorized intent mandates (SD-JWT-VC). Beyond security, it handles the 402 challenge, payment verification, and settlement across multiple payment rails, and automatically embeds discovery metadata. This makes your endpoint seamlessly indexable on [Delegare Market](https://market.delegare.dev), [agentic.market](https://agentic.market) (CDP Bazaar), and [mppscan.com](https://mppscan.com) (MPP) — one middleware, zero exposed credentials, three directories. ## 🔒 Secured by Google's AP2 Protocol Traditional agentic payments force developers to provision wallets with live funds or inject raw credit card details into the LLM context window—a massive security vulnerability. `@delegare/x402` natively implements [Google's AP2 (Agentic Payment Protocol)](https://github.com/google-agentic-commerce/AP2): 1. **No Keys in Context:** Agents are issued an **Intent Mandate** (SD-JWT-VC) rather than returning raw card details or wallet seeds. 2. **Bounded Authority:** Mandates define strict, server-side enforced spending limits and permitted rails. 3. **Zero-Trust Validation:** The middleware cryptographically verifies the mandate before settling the payment on-chain or via fiat fallbacks. ## Installation ```bash theme={null} npm install @delegare/x402 ``` ## Quick Start ```typescript theme={null} import express from 'express'; import { requireX402Payment } from '@delegare/x402'; const app = express(); app.get('/premium-data', requireX402Payment({ price: '0.05', // 5 cents USDC per call payTo: '0xYourWalletAddress', // Your Base wallet }), (req, res) => { res.json({ data: 'premium content' }); } ); app.listen(4000); ``` ## Dual-Rail Payments (Fiat Fallback) Not all agent developers have a crypto wallet. Configure a **Credit Bundle Fallback** to add a Stripe-backed fiat path alongside the crypto path. ```typescript theme={null} app.post('/api/agent', requireX402Payment({ price: '0.02', payTo: '0xYourWalletAddress', creditBundle: { tiers: [ { name: 'Starter', usdCents: 1000, requests: 500 }, { name: 'Pro', usdCents: 5000, requests: 3000 } ], purchaseUrl: 'https://yourapp.com/billing/bundles', validateAndDeduct: async (token: string) => { return { valid: true, creditsRemaining: 499, tenantId: 'org-123' }; }, }, }), (req, res) => res.json({ success: true }) ); ``` Clients pay once via Stripe, receive a bundle token, and send it via `X-Bundle-Token` to bypass crypto. ## Agent Discovery (Delegare Market, CDP Bazaar + MPPScan) Use `declareDiscoveryExtension` to make your endpoint automatically discoverable on [Delegare Market](https://market.delegare.dev), [agentic.market](https://agentic.market), and [mppscan.com](https://mppscan.com). Place it before `requireX402Payment`. The metadata is embedded in both the `PAYMENT-REQUIRED` header (x402 v2, read by CDP Bazaar) and the `WWW-Authenticate` header (MPP/RFC 7235, read by MPPScan) on every 402 response. ```typescript theme={null} import { requireX402Payment, declareDiscoveryExtension } from '@delegare/x402'; app.post('/api/extract', declareDiscoveryExtension({ description: "Extract structured financial data from documents. $0.15/page.", inputSchema: { type: "object", properties: { documentId: { type: "string", description: "Document ID" }, domain: { type: "string", enum: ["commercial_loan", "equity_investment"] } }, required: ["documentId"] }, bodyType: "json", output: { example: { extractedData: { gross_income: 1250000 }, costCents: 150 }, schema: { type: "object", properties: { extractedData: { type: "object" }, costCents: { type: "number" } } } } }), requireX402Payment({ price: '0.15', payTo: '0xYourWalletAddress' }), async (req, res) => { res.json({ data: '...' }); } ); ``` `output.schema` is required (not just `example`) for CDP Bazaar to accept the index entry. Without it, the validator will report "schema is invalid" even if all other checks pass. ### How Bazaar Indexing Works CDP Bazaar indexes your endpoint the **first time a `PAYMENT-SIGNATURE` credential is settled** through their facilitator. The middleware handles this automatically: 1. An agent hits your endpoint with `PAYMENT-SIGNATURE` (x402 v2 credential from `@x402/fetch`) 2. The middleware passes the full payment payload — including your `declareDiscoveryExtension` metadata — directly to CDP's `/settle` endpoint 3. CDP settles on-chain and writes the catalog entry 4. Your endpoint appears on [agentic.market](https://agentic.market) within \~10 minutes To trigger indexing for existing endpoints without waiting for organic traffic, use the `@x402/fetch` client with your own wallet to make one test payment per endpoint. See the [CDP Bazaar docs](https://docs.cdp.coinbase.com/x402/bazaar) for details. ### Required Environment Variables for Bazaar ```env theme={null} COINBASE_API_KEY=your-cdp-key-id # CDP API key UUID COINBASE_API_SECRET=your-cdp-secret # Base64-encoded Ed25519 key (64 bytes) ``` When set, the middleware automatically authenticates CDP settlement calls with a signed JWT — required for Bazaar catalog writes. ## What the 402 Response Emits Every unauthenticated request receives three parallel discovery headers: | Header | Protocol | Read by | | ------------------------------- | -------------- | --------------------------------------------------------------------------------------- | | `PAYMENT-REQUIRED` | x402 v2 | [Delegare Market](https://market.delegare.dev), CDP Bazaar, agentic.market, @x402/fetch | | `WWW-Authenticate: Payment ...` | MPP / RFC 7235 | [Delegare Market](https://market.delegare.dev), MPPScan, MPP-compatible wallets | | `BAZAAR-EXTENSION` | Delegare debug | Custom clients | Plus a JSON body for backward-compatible x402 v1 clients. ## Payment Rails (Priority Order) The middleware accepts five types of payment credentials in this order: | Client header | Rail | Settlement | | ------------------------ | ------------------ | --------------------------- | | `X-Bundle-Token` | Fiat credit bundle | Your backend (Stripe) | | `PAYMENT-SIGNATURE` | x402 v2 USDC | CDP Facilitator → Base | | `X-PAYMENT` | x402 v1 USDC | Delegare Facilitator → Base | | `X-DELEGARE-MANDATE` | AP2 intent mandate | Delegare Vault | | `Authorization: Payment` | MPP/RFC 7235 | Delegare Facilitator | ## Configuration ```typescript theme={null} requireX402Payment({ // Required price: '0.05', // Decimal USDC (e.g. "0.05" = 5 cents) payTo: '0xYourWallet', // Base wallet receiving payment // Optional testMode: true, // Use Base Sepolia (default: false) apiUrl: 'https://api.sandbox.delegare.dev/v1', resource: 'https://yourapi.com/api/endpoint', // Full URL — used as catalog key mimeType: 'application/json', maxTimeoutSeconds: 300, creditBundle: { ... } }); ``` ## Accessing Payment Context ```typescript theme={null} app.get('/premium-data', requireX402Payment({ price: '0.05', payTo: '0xYourWallet' }), (req, res) => { const payer = (req as any).x402Payer; // Payer's wallet address const txHash = (req as any).x402Transaction; // On-chain tx hash res.json({ data: '...', paidBy: payer }); } ); ``` ## Testing with Sandbox ```typescript theme={null} requireX402Payment({ price: '0.01', payTo: '0xYourTestnetWallet', testMode: true, apiUrl: 'https://api.sandbox.delegare.dev/v1', }); ``` ## Related * [x402 Payments (concept)](/concepts/x402-payments) — How x402 works end-to-end * [TypeScript SDK](/sdk-tools/typescript-sdk) — Agent-side `delegare.fetch()` for auto-paying 402s * [MCP Tools](/sdk-tools/mcp-tools) — `delegare_fetch` tool for LLM agents * [CDP Bazaar](https://docs.cdp.coinbase.com/x402/bazaar) — Coinbase discovery catalog * [MPPScan Discovery](https://mppscan.com/discovery) — MPP discovery spec