# DeFi Copilot [![npm version](https://img.shields.io/npm/v/defi-copilot-mcp.svg)](https://www.npmjs.com/package/defi-copilot-mcp) [![npm downloads](https://img.shields.io/npm/dm/defi-copilot-mcp.svg)](https://www.npmjs.com/package/defi-copilot-mcp) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org) [![Stellar](https://img.shields.io/badge/Stellar-mainnet-blue.svg)](https://stellar.org) Pay-per-decision DeFi intelligence for AI agents on Stellar. Built with x402 protocol — agents buy decisions, not subscriptions. ## Overview DeFi Copilot is a Stellar-native DeFi intelligence layer that allows AI agents to autonomously query DeFi data, execute swaps, and interact with DeFi protocols — paying per request using the x402 protocol. No API keys. No subscriptions. No human approval required. **Two ways to use:** - **MCP Server** — install in Claude Desktop or any MCP-compatible AI, agents query and pay automatically - **REST API** — standard HTTP with x402 payment protocol, works with any HTTP client **Live backend:** `https://api.fxjrin.com` --- ## How It Works ``` User / AI Agent | | (natural language or direct API call) v MCP Server (defi-copilot-mcp) | | GET /defi/yield/best v Backend API (port 3000) | | 402 Payment Required v Agent builds + signs Stellar USDC tx | | x-payment header v Facilitator verifies + settles (port 4022) | | on-chain settlement on Stellar v Return DeFi intelligence ``` --- ## Project Structure ``` defi-copilot/ src/ server.ts # Express server routes/ yield.ts # GET /defi/yield/best swap.ts # GET /defi/swap/best services/ scorer.ts # Market data + Blend on-chain APY + DEX quotes utils/ x402-middleware.ts # x402 payment verification network.ts # Network config (testnet/mainnet) http.ts # IPv4-forced HTTP client (undici) init.ts # Server wallet setup script facilitator/ index.ts # Local x402 facilitator (port 4022) agent/ client.ts # Agent payment client with auto-create wallet demo.ts # Demo script mcp-server/ src/ index.ts # MCP tools + auto-create wallet network.ts # Network config for MCP http.ts # IPv4-forced HTTP client (undici) ``` --- ## Prerequisites - Node.js v18+ - npm v9+ - Git --- ## Installation ### 1. Clone the repository ```bash git clone https://github.com/fxjrin/defi-copilot.git cd defi-copilot ``` ### 2. Install backend dependencies ```bash npm install ``` ### 3. Install MCP server dependencies ```bash cd mcp-server npm install cd .. ``` --- ## Configuration ### Backend `.env` The `.env` file is generated automatically by `npm run init`. If you prefer to set it up manually, create `.env` in the `defi-copilot/` root: ```env # Stellar network: testnet or mainnet STELLAR_NETWORK=testnet # Server wallet — receives x402 payments # Generated automatically by: npm run init SERVER_SECRET_KEY= SERVER_PUBLIC_KEY= PORT=3000 ``` --- ## Quick Start ### Step 1 — Initialize server wallet Run the setup script to automatically generate and fund a server wallet: ```bash npm run init ``` This will: 1. Generate a new Stellar keypair for the server 2. Fund with XLM via Friendbot (testnet only) 3. Set up USDC trustline 4. Save credentials to `.env` Expected output: ``` DeFi Copilot — Initial Setup Network: testnet Generating server wallet... Public key : GXXXX... Secret key : SXXX*...XXXX (saved to .env) Credentials saved to .env Funding via Friendbot... XLM funded successfully Waiting for account activation... Setting up USDC trustline... USDC trustline created Final balances: USDC: 0.0000 XLM: 10000.0000 Setup complete! Run: npm start ``` ### Step 2 — Start the server ```bash npm start ``` This starts both the API server (port 3000) and the x402 facilitator (port 4022) simultaneously. Expected output: ``` [api] 🚀 DeFi Copilot API running on port 3000 [api] Network : testnet [api] Wallet : GXXXX... [facilitator] ⚡ Local x402 Facilitator running on port 4022 ``` ### Step 3 — Run the demo Make sure `npm start` is running in another terminal, then: ```bash npm run demo ``` The demo agent will auto-create its own wallet, fund it with USDC, and make payments automatically. Expected output: ``` DeFi Copilot Agent Demo Initializing agent wallet... No wallet found — creating new agent wallet on Stellar testnet... Funding with XLM via Friendbot... XLM funded successfully Setting up USDC trustline... Swapping XLM to USDC... USDC funded successfully Agent wallet ready: GXXXX... DEMO 1: Where should I put my USDC? Agent requesting: http://localhost:3000/defi/yield/best Payment required: 0.0010 USDC Payment accepted! Strategy : Deposit to Fixed V2 on Blend Finance APY : 9.47% (live on-chain) Risk : low Confidence : 95% DEMO 2: Best route to swap 500 XLM to USDC? Agent requesting: http://localhost:3000/defi/swap/best Payment accepted! Route : SDEX Orderbook Expected output: 75.88 USDC Slippage : 0.005% Confidence : 99% ``` --- ## API Reference ### GET /health Free. Returns server status. ```json { "status": "ok", "network": "testnet", "server_wallet": "GXXXX..." } ``` ### GET /defi/yield/best **Cost: 0.001 USDC via x402** Query params: - `asset` — `USDC` or `XLM` (default: `USDC`) - `amount` — number (default: `1000`) Response: ```json { "strategy": "Deposit to Fixed V2 on Blend Finance", "protocol": "Blend Finance", "apy": "9.47%", "risk": "low", "reasoning": "Live Blend Finance on-chain APY. Pool comparison: Fixed V2: USDC 9.47% | YieldBlox V2: USDC 0.07%", "confidence": 0.95, "marketData": { "xlmPrice": "0.1518 USDC", "spread": "0.3945%", "volume24h": "4531.6K XLM", "source": "Blend Finance (on-chain Soroban) + Stellar mainnet DEX" }, "alternatives": [...] } ``` ### GET /defi/swap/best **Cost: 0.001 USDC via x402** Query params: - `from` — source asset (default: `XLM`) - `to` — target asset (default: `USDC`) - `amount` — number (default: `100`) Response: ```json { "from": "XLM", "to": "USDC", "amount": 500, "route": ["SDEX Orderbook"], "expectedOutput": "75.88 USDC", "slippage": "0.005%", "priceImpact": "low", "marketPrice": "1 XLM = 0.1518 USDC", "confidence": 0.99, "reasoning": "DEX comparison: SDEX Orderbook: 75.88 USDC | Stellar DEX: 75.80 USDC | Stellar AMM: 75.70 USDC" } ``` ### x402 Payment Flow ``` 1. Client → GET /defi/yield/best 2. Server ← 402 Payment Required { "x402Version": 1, "accepts": [{ "scheme": "exact", "network": "stellar-testnet", "maxAmountRequired": "10000", "asset": "CBIELTK6...", "payTo": "GXXXX..." }] } 3. Client builds + signs Stellar USDC payment tx 4. Client → GET /defi/yield/best x-payment: 5. Facilitator verifies transaction 6. Facilitator settles on Stellar 7. Server → 200 OK with DeFi intelligence ``` --- ## MCP Server The MCP server allows AI agents (Claude, Cursor, etc.) to use DeFi Copilot tools directly in conversation, with automatic payment handling. ### Install via Claude Code ```bash claude mcp add defi-copilot -- npx -y defi-copilot-mcp ``` ### Install via Claude Desktop config Add to your `claude_desktop_config.json`: **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json` **Windows:** `%APPDATA%\Claude\claude_desktop_config.json` **Linux:** `~/.config/Claude/claude_desktop_config.json` ```json { "mcpServers": { "defi-copilot": { "command": "npx", "args": ["-y", "defi-copilot-mcp"], "env": { "STELLAR_NETWORK": "testnet" } } } } ``` **Note:** `DEFI_COPILOT_API` defaults to `https://api.fxjrin.com` — no need to set it unless you run your own backend. ### Available Tools | Tool | Cost | Description | |------|------|-------------| | `get_best_yield` | 0.001 USDC | Best yield strategy — live from Blend Finance on-chain (Soroban) | | `get_best_swap` | 0.001 USDC | Optimal swap route — compares SDEX Orderbook, Stellar DEX, AMM | | `execute_swap` | FREE | Execute real swap on Stellar DEX | | `deposit_blend` | FREE | Deposit USDC to Blend Finance to earn yield (mainnet) | | `withdraw_blend` | FREE | Withdraw USDC + interest from Blend Finance (mainnet) | | `get_blend_position` | FREE | Check your Blend Finance deposit + interest earned (mainnet) | | `transfer` | FREE | Send XLM or USDC to any Stellar address | | `get_market_data` | FREE | Live XLM price, volume, spread from Stellar mainnet DEX | | `get_agent_wallet` | FREE | Check or create agent wallet | | `fund_wallet` | FREE | Show wallet address + QR code URL for funding | | `set_network` | FREE | Switch between testnet and mainnet | | `get_transaction_history` | FREE | View recent wallet transaction history | | `get_api_info` | FREE | API info and pricing | ### Agent Wallet Behavior On first use, the MCP server automatically: 1. Generates a new Stellar keypair 2. Funds with XLM via Friendbot (testnet only) 3. Sets up USDC trustline 4. Swaps 50 XLM to USDC for payment capability 5. Saves wallet to `~/.defi-copilot/wallet-testnet.json` Each user's wallet is stored locally on their own machine. Private keys never leave the user's device. On mainnet, the wallet is created but not auto-funded — users must deposit XLM manually. This is intentional: mainnet uses real funds. ### Network Switching Switch networks within a conversation: ``` User: "Switch to mainnet" Claude: calls set_network(network="mainnet") User: "Deposit 10 USDC to Blend Finance" Claude: calls deposit_blend(amount=10, confirmed=true) ``` Or set via environment variable (persists across sessions): ```json "env": { "STELLAR_NETWORK": "mainnet" } ``` --- ## Data Sources | Data | Source | Network | |------|--------|---------| | Yield APY | Blend Finance smart contracts (Soroban) | Mainnet (on-chain) | | Swap quotes | SDEX Orderbook + Stellar DEX pathfinder + AMM pool | Mainnet (real quotes) | | XLM price | Stellar Horizon trade aggregations | Mainnet (real prices) | | Orderbook spread | Stellar Horizon order book | Mainnet | | 24h volume | Stellar Horizon trade aggregations | Mainnet | | Payments | x402 protocol | Testnet or Mainnet | All price and yield data comes directly from Stellar mainnet for accuracy, regardless of which network is used for payments. --- ## Environment Variables ### Backend (`defi-copilot/.env`) | Variable | Required | Description | |----------|----------|-------------| | `STELLAR_NETWORK` | No | `testnet` or `mainnet` (default: `testnet`) | | `SERVER_SECRET_KEY` | Yes | Secret key for server wallet (receives payments) | | `SERVER_PUBLIC_KEY` | Yes | Public key for server wallet | | `PORT` | No | Server port (default: `3000`) | ### MCP Server (via config or shell env) | Variable | Required | Description | |----------|----------|-------------| | `STELLAR_NETWORK` | No | `testnet` or `mainnet` (default: `testnet`) | | `DEFI_COPILOT_API` | No | Backend API URL (default: `https://api.fxjrin.com`) | --- ## npm Scripts ### Backend (`defi-copilot/`) ```bash npm run init # Generate and fund server wallet npm start # Start API + facilitator together npm run dev # Start API only (port 3000) npm run facilitator # Start facilitator only (port 4022) npm run demo # Run agent payment demo npm run build # Compile TypeScript ``` ### MCP Server (`defi-copilot/mcp-server/`) ```bash npm run build # Compile TypeScript npm run dev # Run without compiling (tsx) ``` --- ## Deployment ### Backend on VPS ```bash git clone https://github.com/fxjrin/defi-copilot.git cd defi-copilot npm install # Initialize server wallet npm run init # Install pm2 for process management npm install -g pm2 # Start both api and facilitator pm2 start npm --name defi-copilot -- start pm2 save pm2 startup ``` After deploying, nginx reverse proxy + SSL via certbot is recommended: ```bash apt install -y nginx certbot python3-certbot-nginx # configure nginx to proxy port 3000 certbot --nginx -d your-domain.com ``` --- ## License MIT