{
  "markdown": "# DRAIN\n\n<div align=\"center\">\n  <img src=\"docs/drain-logo.png\" alt=\"DRAIN Logo\" width=\"800\">\n</div>\n\n**Decentralized Runtime for AI Networks**\n\nAn open protocol for trustless, streaming micropayments between AI consumers and providers.\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](./CONTRIBUTING.md)\n[![ERC-8190](https://img.shields.io/badge/ERC-8190-blue?logo=ethereum)](https://ethereum-magicians.org/t/erc-8184-draft-payment-channels-with-signed-vouchers-streaming-micropayments-for-ai-agents/28012)\n\n> **[ERC-8190](https://ethereum-magicians.org/t/erc-8184-draft-payment-channels-with-signed-vouchers-streaming-micropayments-for-ai-agents/28012)**: This protocol is being formalized as an Ethereum standard — *Payment Channels with Signed Vouchers*. The ERC defines the minimal interface for unidirectional payment channels using EIP-712 signed vouchers, complementary to [ERC-8183](https://eips.ethereum.org/EIPS/eip-8183) (Agentic Commerce).\n\n---\n\n<div align=\"center\">\n\n### ⚡ Superior to Per-Request-Providers.\n\n</div>\n\n```\n╔══════════════════════════════════════════════════════════════════════════════╗\n║                           1000 AI REQUESTS                                   ║\n╠══════════════════════════════════════════════════════════════════════════════╣\n║                                                                              ║\n║   DRAIN              │  Per-Request Payments (x402, etc.)                    ║\n║   ─────              │  ────────────────────────────────                     ║\n║   2 transactions     │  1000 transactions                                    ║\n║   ~$0.04 gas         │  ~$20+ gas                                            ║\n║   0ms latency        │  2-5 sec per request                                  ║\n║   1 wallet popup     │  1000 wallet popups (or API key)                      ║\n║                                                                              ║\n╚══════════════════════════════════════════════════════════════════════════════╝\n```\n\n<div align=\"center\">\n\n| 🏦 **2 On-Chain TXs** | ⚡ **Zero Latency** | 💸 **~$0.04 Total Gas** | 🔐 **No API Keys** |\n|:---:|:---:|:---:|:---:|\n| Open + Close only | Off-chain vouchers | 500x cheaper at scale | Cryptographic auth |\n\n</div>\n\n---\n\n## Why DRAIN?\n\nExisting decentralized AI protocols require holding volatile tokens, creating speculation dynamics that overwhelm utility. Meanwhile, **78% of the world lacks credit cards**, and AI agents can't have bank accounts.\n\nDRAIN fills this gap: **stablecoin micropayments without tokens, complexity, or intermediaries.**\n\n| Problem | DRAIN Solution |\n|---------|----------------|\n| Token volatility | USDC-only, predictable pricing |\n| High fees | ~$0.02 per tx on Polygon (varies: $0.015-0.025) |\n| AI agents can't pay | First-class programmatic support |\n| Credit card barriers | Permissionless crypto access |\n\n## Overview\n\nDRAIN enables permissionless, pay-per-token AI inference without intermediaries. Users open payment channels with USDC, stream requests to any compatible provider, and settle on-chain only when needed.\n\n**Core Principles:**\n\n* **Minimal** – The protocol defines only what's necessary\n* **Permissionless** – Anyone can be a provider or consumer\n* **Trustless** – Cryptography replaces trust\n* **Immutable** – No admin keys, no upgrades, no fees\n\n## How It Works\n\nDRAIN is like a **prepaid card for AI**: deposit USDC, use it across requests, withdraw the remainder.\n\n<div align=\"center\">\n  <img src=\"docs/drain-infographic.png\" alt=\"DRAIN Protocol Overview\" width=\"800\">\n</div>\n\n```\n┌──────────────────────────────────────────────────────────────────┐\n│                        Off-Chain (Fast & Free)                   │\n│                                                                  │\n│    Consumer                                      Provider        │\n│        │                                             │           │\n│        │───────── Request + Voucher ────────────────►│           │\n│        │◄──────── AI Response ───────────────────────│           │\n│        │───────── Request + Voucher ────────────────►│           │\n│        │◄──────── AI Response ───────────────────────│           │\n│        │                    ...                      │           │\n│                                                                  │\n└────────┼─────────────────────────────────────────────┼───────────┘\n         │                                             │\n         │              On-Chain (Rare)                │\n         ▼                                             ▼\n┌──────────────────────────────────────────────────────────────────┐\n│                        DRAIN Contract                            │\n│                                                                  │\n│     open(provider, amount, duration)    →  Lock USDC             │\n│     claim(channelId, amount, signature) →  Pay provider          │\n│     close(channelId)                    →  Refund remainder      │\n└──────────────────────────────────────────────────────────────────┘\n```\n\n### The Two Roles\n\n| Role | What They Do | On-Chain Actions |\n|------|--------------|------------------|\n| **Consumer** | Pays for AI services | `open` (deposit), `close` (refund) |\n| **Provider** | Delivers AI responses | `claim` (withdraw earnings) |\n\n### Consumer Flow\n\n1. **Open Channel**: Deposit USDC for a specific provider and duration (~$0.02 gas, ~5 sec finality)\n2. **Use Service**: Send requests with signed vouchers (free, off-chain, $0.000005 per request)\n3. **Close Channel**: Withdraw unused USDC after expiry (~$0.02 gas, ~5 sec finality)\n\n### Provider Flow\n\n1. **Receive Request**: Validate voucher signature and amount\n2. **Deliver Service**: Return AI response\n3. **Claim Payment**: Submit highest voucher to get paid (~$0.02 gas, ~5 sec finality)\n\n### Channel Duration & Provider Protection\n\nThe **consumer sets the channel duration** when opening (e.g., 24h). But providers control their requirements:\n\n| Provider Can... | How |\n|-----------------|-----|\n| **Require minimum duration** | Reject vouchers from channels < X hours |\n| **Recommend duration** | Document in API: \"We recommend 24h channels\" |\n| **Claim anytime** | No deadline until consumer calls `close()` |\n\n**Key insight:** Even after channel expiry, the provider can claim as long as the consumer hasn't closed. The consumer must actively call `close()` – it's not automatic.\n\n### Vouchers Are Cumulative\n\nEach voucher contains the **total** amount spent, not the increment:\n\n```\nRequest 1: voucher.amount = $0.10  (total spent so far)\nRequest 2: voucher.amount = $0.25  (total, not $0.15 increment)\nRequest 3: voucher.amount = $0.40  (total, not $0.15 increment)\n```\n\nProvider only needs to claim the **last** voucher to receive full payment.\n\n### Payment Currency\n\n| Asset | Network | Why |\n|-------|---------|-----|\n| **USDC** | Polygon | Stable ($1), liquid ($500M+), low fees (~$0.02/tx, varies: $0.015-0.025) |\n\nUSDC on Polygon can be bridged from Ethereum, Base, Arbitrum via [Circle CCTP](https://www.circle.com/en/cross-chain-transfer-protocol).\n\n## Handshake58 Marketplace\n\nThe official DRAIN marketplace is **Handshake58** - a provider directory where AI agents can discover and pay for AI inference.\n\n| Link | Description |\n|------|-------------|\n| **https://www.handshake58.com** | Main marketplace |\n| **https://www.handshake58.com/for-agents** | Quick start for AI agents |\n| **https://www.handshake58.com/api/mcp/providers** | Provider discovery API |\n\n### For AI Agents\n\nInstall the MCP Server and start using AI with crypto payments:\n\n```bash\nnpm install -g drain-mcp\n```\n\nConfigure in Claude Desktop or Cursor:\n\n```json\n{\n  \"mcpServers\": {\n    \"drain\": {\n      \"command\": \"drain-mcp\",\n      \"env\": {\n        \"DRAIN_PRIVATE_KEY\": \"your-polygon-wallet-key\"\n      }\n    }\n  }\n}\n```\n\nThat's it! The MCP server auto-discovers providers from Handshake58.\n\n### Agent-Oriented Endpoints\n\n| URL | Purpose |\n|-----|---------|\n| `/for-agents` | Static, crawlable agent page |\n| `/api/agent` | Quick discovery JSON |\n| `/llms.txt` | 25-line agent instruction |\n| `/skill.md` | Full documentation (MCP first) |\n\n---\n\n## Protocol Specification (ERC-8190)\n\nDRAIN implements **[ERC-8190: Payment Channels with Signed Vouchers](https://ethereum-magicians.org/t/erc-8184-draft-payment-channels-with-signed-vouchers-streaming-micropayments-for-ai-agents/28012)** — an Ethereum standard for streaming micropayments via EIP-712 signed vouchers.\n\n| Component                | Description                                      | Standard |\n| ------------------------ | ------------------------------------------------ | -------- |\n| **Smart Contract** | Escrow and settlement logic (`IPaymentChannel`) | ERC-8190 (normative) |\n| **Voucher Format** | EIP-712 typed signatures for off-chain payments  | ERC-8190 (normative) |\n| **Service Interaction** | HTTP 402 discovery, cost reporting, error codes | ERC-8190 (RECOMMENDED) |\n| **API Standard**   | OpenAI-compatible interface with payment headers | Application layer |\n\nThe protocol intentionally excludes provider discovery, reputation systems, dispute resolution, and governance. See [ERC-8183](https://eips.ethereum.org/EIPS/eip-8183) (Agentic Commerce) and [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) (Trustless Agents) for complementary standards.\n\nFull specification: See `contracts/` for the Solidity implementation and the [ERC-8190 draft](https://github.com/ethereum/ERCs/pull/1592) for the formal standard.\n\n## Security Model\n\n| Party | Protected Against | How |\n|-------|-------------------|-----|\n| **Consumer** | Overcharging | Only signs amounts they agree to |\n| **Consumer** | Non-delivery | Stops signing, refunds after expiry |\n| **Provider** | Overspending | `amount ≤ deposit` enforced on-chain |\n| **Provider** | Double-spend | USDC locked in contract, not wallet |\n\nEIP-712 signatures with `chainId` and `verifyingContract` prevent replay attacks. OpenZeppelin ECDSA provides malleability protection.\n\n## Voucher Format\n\n```solidity\n// EIP-712 typed data\nstruct Voucher {\n    bytes32 channelId;\n    uint256 amount;  // Cumulative total spent\n    uint256 nonce;   // Incrementing per voucher\n}\n```\n\nConsumer signs vouchers off-chain. Provider submits latest voucher to claim payment.\n\n## Economics\n\n| Role | Cost |\n|------|------|\n| **Consumer** | ~$0.02 open + provider rate + ~$0.02 close |\n| **Provider** | ~$0.02 claim gas, keeps 100% of fees |\n| **Protocol** | Zero fees |\n\nTotal overhead: **<$0.05** per session regardless of usage.\n\n**Minimum Deposit Recommendations:**\n- **$0.10**: Testing (40% gas overhead, ~100 messages)\n- **$0.50**: Recommended minimum (8% gas overhead, ~500 messages)\n- **$1.00**: Optimal (4% gas overhead, ~1000 messages)\n- **$5.00**: Best value (0.8% gas overhead, ~5000 messages)\n\nSee [Test Results](docs/AGENT_TEST_RESULTS.md) for verified cost data.\n\n## What DRAIN Is NOT\n\n| ❌ | Why |\n|----|-----|\n| Token | No speculation, no governance drama |\n| Marketplace | Discovery is separate, built on top |\n| Reputation system | Out of scope, can be layered |\n| Upgradeable | Immutable contracts, no admin keys |\n\n## Project Structure\n\n```\ndrain/\n├── contracts/                  # Solidity smart contracts\n│   ├── src/DrainChannel.sol    # Core payment channel contract\n│   ├── test/                   # 47 Foundry tests\n│   └── script/                 # Deploy scripts\n├── sdk/                        # TypeScript SDK\n│   ├── src/consumer.ts         # Consumer: open, sign, close\n│   └── src/provider.ts         # Provider: verify, claim\n├── provider/                   # Reference AI Provider\n│   ├── src/index.ts            # Express server (OpenAI-compatible)\n│   └── src/drain.ts            # Voucher validation\n├── mcp/                        # MCP Server for AI Agents\n│   ├── src/index.ts            # MCP server entry point\n│   └── src/tools/              # drain_chat, drain_balance, etc.\n└── demo/                       # AI-optimized examples\n    ├── README.md               # Quick start for AI agents\n    └── simple-demo.ts          # Minimal code example\n```\n\n## MCP Server (Agent-to-Agent) ✅ **VERIFIED**\n\nDRAIN includes an MCP (Model Context Protocol) server that enables AI agents to autonomously pay for AI services.\n\n**✅ Successfully tested with Claude Desktop** - An AI agent autonomously opened a $0.10 channel and made AI inference requests, proving the agent-to-agent payment economy works without human intervention.\n\n**Test Results**: $0.000005 per request, 20,000 requests possible with $0.10 channel. See [Test Results](docs/AGENT_TEST_RESULTS.md) and [Comparison with Credit Cards](docs/COMPARISON.md) for detailed metrics.\n\n```bash\nnpm install -g drain-mcp\n```\n\nConfigure in Cursor or Claude:\n\n```json\n{\n  \"mcpServers\": {\n    \"drain\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"drain-mcp\"],\n      \"env\": {\n        \"DRAIN_PRIVATE_KEY\": \"0x...\"\n      }\n    }\n  }\n}\n```\n\n**Available Tools:**\n\n| Tool | Description |\n|------|-------------|\n| `drain_providers` | Discover AI providers |\n| `drain_balance` | Check wallet balance |\n| `drain_open_channel` | Open payment channel |\n| `drain_chat` | AI chat with payment |\n| `drain_close_channel` | Close channel, get refund |\n\nSee [`mcp/README.md`](./mcp/README.md) for full documentation.\n\n## SDK Quick Start\n\n```bash\nnpm install @drain-protocol/sdk viem\n```\n\n```typescript\nimport { createDrainConsumer, CHAIN_IDS } from '@drain-protocol/sdk';\n\n// Open channel, sign vouchers, close when done\nconst consumer = createDrainConsumer(walletClient, account, {\n  chainId: CHAIN_IDS.POLYGON_MAINNET,\n});\n\nawait consumer.approveUsdc('10');\nconst { channelId } = await consumer.openChannel({\n  provider: '0x...',\n  amount: '10',\n  duration: '24h',\n});\n\nconst voucher = await consumer.signVoucher(channelId, '0.50');\n// Send voucher to provider...\n```\n\nSee [`sdk/README.md`](./sdk/README.md) for full documentation.\n\n## Reference Provider\n\nOpenAI-compatible API server that accepts DRAIN payments.\n\n**🟢 Live Provider:** https://drain-production-a9d4.up.railway.app/v1/pricing\n\n### Available Models & Pricing\n\n| Model | Input/1K Tokens | Output/1K Tokens | ~Cost/Message |\n|-------|-----------------|------------------|---------------|\n| **gpt-4o-mini** | $0.000225 | $0.0009 | ~$0.001 ✨ |\n| gpt-4o | $0.00375 | $0.015 | ~$0.01 |\n| gpt-4-turbo | $0.015 | $0.045 | ~$0.03 |\n| gpt-3.5-turbo | $0.00075 | $0.00225 | ~$0.002 |\n\n*Prices include 50% margin over OpenAI base rates*\n\n**Run your own:**\n\n```bash\ncd provider\ncp env.example .env  # Configure OPENAI_API_KEY, PROVIDER_PRIVATE_KEY\nnpm install\nnpm run dev\n```\n\n**Endpoints:**\n```\nGET  /v1/pricing          → View pricing per model\nGET  /v1/models           → List available models  \nPOST /v1/chat/completions → Chat (with X-DRAIN-Voucher header)\n```\n\n**DRAIN Headers:**\n```http\n# Request\nX-DRAIN-Voucher: {\"channelId\":\"0x...\",\"amount\":\"1000000\",\"nonce\":\"1\",\"signature\":\"0x...\"}\n\n# Response\nX-DRAIN-Cost: 8250\nX-DRAIN-Total: 158250\nX-DRAIN-Remaining: 9841750\n```\n\nSee [`provider/README.md`](./provider/README.md) for full documentation.\n\n## Provider Discovery\n\nDRAIN is a permissionless protocol - anyone can be a provider. Multiple discovery options:\n\n| Method | Best For | Link |\n|--------|----------|------|\n| **Handshake58** | Humans browsing providers | [Launch App](https://www.handshake58.com) |\n| **MCP Server** | AI agents (auto-discovery) | [npm package](https://www.npmjs.com/package/drain-mcp) |\n| **Direct Address** | Known provider integration | Use provider wallet address |\n\nThe marketplace is **optional** - DRAIN protocol works standalone with any provider address.\n\n## Demo & Examples\n\n**Quick Start for AI Agents**: See [`demo/README.md`](./demo/README.md) for machine-readable examples.\n\n**Live Demo**: https://www.handshake58.com\n\nTry DRAIN without writing code:\n1. **Connect Wallet** – MetaMask on Polygon Mainnet\n2. **Choose Provider & Model** – Select from available AI models\n3. **Open Channel** – Deposit USDC ($0.10 minimum recommended)\n4. **Chat** – Each message signs a voucher and calls the real AI ($0.000005 per request)\n5. **Close Channel** – Get unused USDC refunded\n\n## Development Status\n\n| Component               | Status         | Link |\n| ----------------------- | -------------- | ---- |\n| Smart Contract          | ✅ Complete    | [polygonscan](https://polygonscan.com/address/0x1C1918C99b6DcE977392E4131C91654d8aB71e64) |\n| Test Suite (47 tests)   | ✅ Complete | `contracts/test/` |\n| TypeScript SDK          | ✅ Available | `sdk/` |\n| Reference Provider      | ✅ Online | [Railway](https://drain-production-a9d4.up.railway.app/v1/pricing) |\n| MCP Server              | ✅ Published | [npm](https://www.npmjs.com/package/drain-mcp) |\n| **Handshake58**         | ✅ **LIVE** | **[Launch App](https://www.handshake58.com)** |\n\n### Deployed Contracts\n\n| Network | Contract | Address |\n|---------|----------|---------|\n| **Polygon Mainnet** | DrainChannelV2 (ERC-8190) | [`0x0C2B3aA1e80629D572b1f200e6DF3586B3946A8A`](https://polygonscan.com/address/0x0C2B3aA1e80629D572b1f200e6DF3586B3946A8A) |\n| **Polygon Mainnet** | DrainChannel (V1, immutable) | [`0x1C1918C99b6DcE977392E4131C91654d8aB71e64`](https://polygonscan.com/address/0x1C1918C99b6DcE977392E4131C91654d8aB71e64) |\n| Polygon Amoy (Testnet) | DrainChannel | [`0x61f1C1E04d6Da1C92D0aF1a3d7Dc0fEFc8794d7C`](https://amoy.polygonscan.com/address/0x61f1C1E04d6Da1C92D0aF1a3d7Dc0fEFc8794d7C) |\n\nDrainChannelV2 is the production contract used by [Handshake58](https://www.handshake58.com) and the ERC-8190 reference implementation. It adds cooperative close and optional platform fees over V1.\n\n\n## Getting Started\n\n```bash\ngit clone https://github.com/kimbo128/DRAIN.git\ncd DRAIN/contracts\n\n# Install Foundry if needed: https://book.getfoundry.sh\nforge build\nforge test -vvv\n```\n\n### Test Coverage\n\n```bash\nforge test --gas-report  # Gas optimization\nforge coverage           # Line coverage\n```\n\n## Target Chain\n\n| Chain   | Tx Cost | Finality | USDC Liquidity |\n| ------- | ------- | -------- | -------------- |\n| Polygon | ~$0.02 (varies: $0.015-0.025) | 5 sec    | $500M+ native  |\n\n**Why Polygon?**\n- Native USDC with Circle CCTP bridging\n- 5-second finality enables 10-minute challenge periods (300 blocks)\n- Proven infrastructure, no reorgs\n- Low gas costs (~$0.02 per transaction)\n\nFuture chains via CREATE2 for identical addresses.\n\n## FAQ\n\n<details>\n<summary><strong>What if the provider doesn't deliver?</strong></summary>\n\nStop signing vouchers. Your USDC stays locked until expiry, then you can close the channel and get a full refund. The provider can only claim what you've signed.\n</details>\n\n<details>\n<summary><strong>What if the consumer stops paying?</strong></summary>\n\nProvider stops delivering service and claims the last valid voucher. The consumer's deposit covers all signed vouchers.\n</details>\n\n<details>\n<summary><strong>Can I use ETH/MATIC instead of USDC?</strong></summary>\n\nNo. DRAIN v1 supports only USDC on Polygon. This keeps the protocol simple and prices predictable.\n</details>\n\n<details>\n<summary><strong>Can I close a channel early?</strong></summary>\n\nNo. Channels have a fixed duration (e.g., 24h) to protect providers. After expiry, unused funds are refundable.\n</details>\n\n<details>\n<summary><strong>When should providers claim?</strong></summary>\n\nRecommended: when accumulated earnings exceed ~$10 (to amortize ~$0.02 gas). Providers can claim **at any time** – before, during, or after channel expiry.\n</details>\n\n<details>\n<summary><strong>What happens to unclaimed vouchers after expiry?</strong></summary>\n\n**Providers are protected by the channel duration.** Here's the timeline:\n\n```\nChannel Open → Provider can claim (anytime) → Channel Expiry → Consumer can close\n     │                    │                        │                  │\n     └────────────────────┴────────────────────────┴──────────────────┘\n                    Provider can claim throughout this entire period\n```\n\n- **Provider can claim**: From channel open until consumer calls `close()`\n- **Consumer can close**: Only AFTER channel expiry\n- **The gap is your protection**: Even after expiry, if the consumer doesn't immediately close, you can still claim\n\n**Example with 24h channel:**\n1. Consumer opens channel at 10:00 AM\n2. Consumer uses service, signs vouchers worth $5\n3. Channel expires at 10:00 AM next day\n4. Consumer might close at 2:00 PM (4 hours later)\n5. Provider can claim anytime from 10:00 AM Day 1 until 2:00 PM Day 2 (28 hours!)\n\n**Best practice:** Set up monitoring to claim before expiry, but know you have a buffer.\n</details>\n\n<details>\n<summary><strong>Can I top up a channel?</strong></summary>\n\nNo. Open a new channel instead. This keeps the protocol simple and avoids edge cases.\n</details>\n\n## Related Projects\n\n| Project | Description | Link |\n|---------|-------------|------|\n| **Handshake58 Marketplace** | Official provider directory | [https://www.handshake58.com](https://www.handshake58.com) |\n| **For AI Agents** | Agent quick start | [https://www.handshake58.com/for-agents](https://www.handshake58.com/for-agents) |\n| **Provider API** | Discovery endpoint | [https://www.handshake58.com/api/mcp/providers](https://www.handshake58.com/api/mcp/providers) |\n| **MCP Server** | AI agent integration (Claude, Cursor) | [npm](https://www.npmjs.com/package/drain-mcp) |\n| **Reference Provider** | Live DRAIN-compatible AI provider | [API](https://drain-production-a9d4.up.railway.app) |\n\n## Contributing\n\nSee [`CONTRIBUTING.md`](./CONTRIBUTING.md) for guidelines.\n\n## License\n\n[MIT License](./LICENSE) – Attribution required.\n\n---\n\n<p align=\"center\">\n<i>Permissionless AI infrastructure for an open economy.</i>\n</p>\n",
  "bytes": 21841,
  "sha": "632822b53b32d275f88c6932b2eac9e27ebbd35f444c91115469fbe418c13c70",
  "repo_slug": "kimbo128/drain",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_kimbo128_drain_mcp_dab77a8b/readme"
}