# Batch pay to users via email Source: https://docs.snack.money/api-reference/email/batch-pay-to-users-via-email https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/email/batch-pay # Pay to user via email Source: https://docs.snack.money/api-reference/email/pay-to-user-via-email https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/email/pay # Batch pay to farcaster users Source: https://docs.snack.money/api-reference/farcaster/batch-pay-to-farcaster-users https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/farcaster/batch-pay # Pay to farcaster user Source: https://docs.snack.money/api-reference/farcaster/pay-to-farcaster-user https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/farcaster/pay # Batch pay to users via github users Source: https://docs.snack.money/api-reference/github/batch-pay-to-users-via-github-users https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/github/batch-pay # Pay to github user Source: https://docs.snack.money/api-reference/github/pay-to-github-user https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/github/pay # Snack Money API Source: https://docs.snack.money/api-reference/introduction The Snack Money API enables seamless microtransaction and reward distribution for social networks and other platforms. It is designed for scenarios where you need to send small amounts of USDC to individual users or groups, validate payments, and automate content-based reward payouts. ## Features * **Single Payments** – Send USDC payments directly to recipients via platform-specific endpoints. * **Batch Payments** – Send USDC to multiple recipients in one request via batch payment endpoints. * **Payment Validation** – Validate payment status and details using `/payments/validate`. * **Reward Distribution** – Create and confirm reward distribution orders based on content engagement. * **Supports Multiple Identities** – Payments can be made to recipients identified via: * Farcaster (`/payments/farcaster/pay`) * X/Twitter (`/payments/x/pay`) * Email (`/payments/email/pay`) * Domain names (`/payments/web/pay`) * **X402-Compliant** – Payment-required responses include full X-PAYMENT header details for compliance. *** ## Authentication Some endpoints require the `X-PAYMENT` header for processing.\ The header contains payment details that comply with the [X402 payment protocol](https://x402.org/). *** ## Error Handling The API returns standardized error responses: * **400** – Validation errors * **402** – Payment required * **500** – Internal server errors *** ## Main Endpoints ### Payment Endpoints * `POST /payments/farcaster/pay` - Pay to Farcaster user * `POST /payments/x/pay` - Pay to X user * `POST /payments/email/pay` - Pay to user via email * `POST /payments/web/pay` - Pay to user via domain name/URL * `POST /payments/farcaster/batch-pay` - Batch pay to Farcaster users * `POST /payments/x/batch-pay` - Batch pay to X users * `POST /payments/email/batch-pay` - Batch pay to users via email * `GET /payments/validate` - Validate payment ### Reward Distribution Endpoints * `POST /rewards/farcaster/create-distribution` - Create reward distribution for Farcaster content * `POST /rewards/farcaster/confirm-distribution` - Confirm reward distribution for Farcaster content *** ## Example Use Cases * Reward social media users for likes, comments, or reposts. * Facilitate tipping between content creators and followers. * Batch transfer funds to multiple recipients with one API call. # Validate payment Source: https://docs.snack.money/api-reference/payments/validate-payment https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web get /payments/validate # Batch pay to users via domain names Source: https://docs.snack.money/api-reference/web/batch-pay-to-users-via-domain-names https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/web/batch-pay # Pay to user via domain name/url Source: https://docs.snack.money/api-reference/web/pay-to-user-via-domain-nameurl https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/web/pay # Batch pay to X users Source: https://docs.snack.money/api-reference/x/batch-pay-to-x-users https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/x/batch-pay # Pay to X user Source: https://docs.snack.money/api-reference/x/pay-to-x-user https://api.snack.money/openapi.json?tags=Payments&group_by=Farcaster,X,Github,Email,Web post /payments/x/pay # batch-send Command Source: https://docs.snack.money/cli/batch-send Send USDC to multiple users at once The `batch-send` command allows you to send USDC to multiple users in a single operation. This is ideal for airdrops, bulk payments, or rewarding multiple contributors. ## Syntax ```bash theme={null} snackmoney batch-send [options] ``` ## Input Formats The `batch-send` command supports multiple input formats for flexibility: ### 1. Comma-Separated Format ```bash theme={null} snackmoney batch-send ``` ### 2. JSON File ```bash theme={null} snackmoney batch-send ./payments.json snackmoney batch-send file:./payments.json ``` ### 3. URL ```bash theme={null} snackmoney batch-send https://example.com/payments.json ``` ### 4. Inline JSON ```bash theme={null} snackmoney batch-send '{"platform":"x","payments":[...]}' ``` ## Options ### --network Specify which blockchain network to use: ```bash theme={null} snackmoney batch-send input --network base snackmoney batch-send input --network solana ``` ## Examples ### Comma-Separated Format Send to multiple users on the same platform: ```bash theme={null} # Solana network snackmoney batch-send x/aeyakovenko:7¢,0xMert_:3¢,0xmesuthere:5¢ --network solana # Base network snackmoney batch-send x/MurrLincoln:2¢,kleffew94:9¢,jessepollak:4¢ --network base # With domain extensions snackmoney batch-send twitter.com/user1:1¢,user2:$0.5 # Farcaster users snackmoney batch-send farcaster.xyz/toly:50¢,mesut:25¢ # GitHub users snackmoney batch-send github/user1:$1,user2:$2,user3:$3 # Email addresses snackmoney batch-send email/user1@example.com:$0.25,user2@example.com:$0.50 # Web domains snackmoney batch-send web/site1.com:0.5,site2.com:1 ``` ### JSON File Format Create a `payments.json` file: ```json theme={null} { "platform": "x", "payments": [ { "receiver": "aeyakovenko", "amount": "7¢" }, { "receiver": "0xMert_", "amount": "3¢" }, { "receiver": "0xmesuthere", "amount": "5¢" } ] } ``` Then run: ```bash theme={null} snackmoney batch-send ./payments.json ``` **Platform-specific examples:** **X (Twitter)** - `payments-x.json`: ```json theme={null} { "platform": "x", "payments": [ { "receiver": "user1", "amount": "1¢" }, { "receiver": "user2", "amount": "$0.50" }, { "receiver": "user3", "amount": "0.25" } ] } ``` **Farcaster** - `payments-farcaster.json`: ```json theme={null} { "platform": "farcaster", "payments": [ { "receiver": "toly", "amount": "$1" }, { "receiver": "mesut", "amount": "50¢" } ] } ``` **GitHub** - `payments-github.json`: ```json theme={null} { "platform": "github", "payments": [ { "receiver": "octocat", "amount": "$5" }, { "receiver": "torvalds", "amount": "$10" } ] } ``` **Email** - `payments-email.json`: ```json theme={null} { "platform": "email", "payments": [ { "receiver": "user1@example.com", "amount": "$0.25" }, { "receiver": "user2@example.com", "amount": "$0.50" } ] } ``` **Web** - `payments-web.json`: ```json theme={null} { "platform": "web", "payments": [ { "receiver": "site1.com", "amount": "$0.50" }, { "receiver": "site2.com", "amount": "$1" } ] } ``` ### From URL Host your payment file and reference it by URL: ```bash theme={null} snackmoney batch-send https://example.com/payments.json snackmoney batch-send http://localhost:3000/team-rewards.json ``` ### Inline JSON Pass JSON directly as a command argument: ```bash theme={null} snackmoney batch-send '{"platform":"x","payments":[{"receiver":"aeyakovenko","amount":"1¢"}]}' ``` ## Supported Platforms | Platform | Format in JSON | Comma-separated Format | | --------------- | ------------------------- | --------------------------- | | **X (Twitter)** | `"platform": "x"` | `x/username:amount` | | **Farcaster** | `"platform": "farcaster"` | `farcaster/username:amount` | | **GitHub** | `"platform": "github"` | `github/username:amount` | | **Email** | `"platform": "email"` | `email/address:amount` | | **Web** | `"platform": "web"` | `web/domain:amount` | ## Amount Formats All the same amount formats from the `send` command work: * **Cents**: `1¢`, `50¢`, `99¢` * **Dollars**: `$0.01`, `$0.50`, `$1` * **Decimal**: `0.01`, `0.50`, `1` ## Output The command processes payments sequentially and shows progress: ``` 🚀 Processing batch payment... [1/3] Sending 0.07 USDC to @aeyakovenko on X... ✅ Success - txn: 0xabc... [2/3] Sending 0.03 USDC to @0xMert_ on X... ✅ Success - txn: 0xdef... [3/3] Sending 0.05 USDC to @0xmesuthere on X... ✅ Success - txn: 0xghi... 📊 Batch Summary: Total payments: 3 Successful: 3 Failed: 0 Total sent: 0.15 USDC Network: Solana 🧾 All receipts: https://snack.money/x/aeyakovenko?txn=... https://snack.money/x/0xMert_?txn=... https://snack.money/x/0xmesuthere?txn=... ``` ## Use Cases ### Airdrop Rewards Distribute tokens to community members: ```json theme={null} { "platform": "x", "payments": [ { "receiver": "community_member1", "amount": "$5" }, { "receiver": "community_member2", "amount": "$5" }, { "receiver": "community_member3", "amount": "$5" } ] } ``` ### Team Payments Pay multiple team members: ```json theme={null} { "platform": "farcaster", "payments": [ { "receiver": "designer", "amount": "$100" }, { "receiver": "developer", "amount": "$150" }, { "receiver": "marketer", "amount": "$75" } ] } ``` ### Open Source Contributions Reward GitHub contributors: ```json theme={null} { "platform": "github", "payments": [ { "receiver": "contributor1", "amount": "$25" }, { "receiver": "contributor2", "amount": "$50" }, { "receiver": "contributor3", "amount": "$25" } ] } ``` ### Contest Winners Distribute prizes: ```bash theme={null} snackmoney batch-send x/winner1:$100,winner2:$50,winner3:$25 ``` ## Prerequisites 1. **Set private key**: ```bash theme={null} export EVM_PRIVATE_KEY="0x..." # For Base # OR export SVM_PRIVATE_KEY="..." # For Solana ``` 2. **Sufficient USDC balance**: Ensure your wallet has enough USDC for all payments plus network fees. 3. **Valid recipients**: All usernames must exist on the specified platform. ## Error Handling If a payment fails, the command continues with remaining payments: ``` [2/5] Sending 0.05 USDC to @invalid_user on X... ❌ Failed - User not found [3/5] Sending 0.10 USDC to @valid_user on X... ✅ Success - txn: 0xabc... ``` The final summary shows success/failure counts. ## Limits * **Minimum per payment**: 0.01 USDC (1¢) * **Recommended batch size**: Up to 100 payments per batch * **Rate limits**: May apply for very large batches ## Tips 1. **Test first**: Start with a small batch to test your setup 2. **Check balance**: Calculate total amount + fees before running 3. **Validate JSON**: Ensure JSON files are properly formatted 4. **Save receipts**: Keep the receipt URLs for records 5. **Use files**: For large batches, JSON files are more manageable than comma-separated ## Related Commands * [**send**](/cli/send) - Send to a single user * [**ai-agent**](/cli/ai-agent) - Use natural language for batch payments ## Getting Help ```bash theme={null} snackmoney batch-send --help ``` ## Example Files View example payment files on GitHub: * [payments-solana.json](https://github.com/snack-money/snackmoney-cli/blob/main/examples/payments-solana.json) * [payments-base.json](https://github.com/snack-money/snackmoney-cli/blob/main/examples/payments-base.json) ## Additional Resources * [CLI Overview](/cli/overview) - All CLI features * [Quick Start](/cli/quick-start) - Getting started * [GitHub Repository](https://github.com/snack-money/snackmoney-cli) - Source code and examples # Installation Source: https://docs.snack.money/cli/installation Install the Snack Money CLI The Snack Money CLI can be installed in multiple ways. Choose the method that works best for your workflow. ## npx (Recommended) The simplest way to use the CLI is with **npx** - no installation required: ```bash theme={null} npx snackmoney --help ``` This automatically downloads and runs the latest version. Perfect for: * One-time usage * Quick testing * CI/CD pipelines * Avoiding global installs ### Example Usage ```bash theme={null} # Send a payment npx snackmoney send x/username 0.01 # View help npx snackmoney --help # Check version npx snackmoney --version ``` ## npm Global Installation Install globally with npm to use the `snackmoney` command directly: ```bash theme={null} npm install -g snackmoney ``` After installation, you can run commands without `npx`: ```bash theme={null} snackmoney send x/username 0.01 snackmoney batch-send ./payments.json snackmoney --help ``` ### Updating Keep the CLI up to date: ```bash theme={null} npm update -g snackmoney ``` ### Uninstalling Remove the global installation: ```bash theme={null} npm uninstall -g snackmoney ``` ## Homebrew (macOS/Linux) Install via Homebrew for system-level package management: ```bash theme={null} # Add the Snack Money tap brew tap snack-money/tap # Install the CLI brew install snackmoney ``` After installation: ```bash theme={null} snackmoney --help ``` ### Updating ```bash theme={null} brew update brew upgrade snackmoney ``` ### Uninstalling ```bash theme={null} brew uninstall snackmoney brew untap snack-money/tap ``` ## Prerequisites Regardless of installation method, you need: ### 1. Node.js * **Version**: Node.js 20 or higher * **Check version**: `node --version` * **Install**: [nodejs.org](https://nodejs.org/) or use [nvm](https://github.com/nvm-sh/nvm) ### 2. Private Key You need a private key for the blockchain network you want to use: **For Base (EVM):** ```bash theme={null} export EVM_PRIVATE_KEY="0x..." ``` **For Solana (SVM):** ```bash theme={null} export SVM_PRIVATE_KEY="your_base58_private_key" ``` **Important Security Notes:** * Never commit private keys to version control * Use environment variables or `.env` files * Keep your keys secure and backed up * Only fund with amounts you're willing to use ### 3. USDC Balance Ensure your wallet has sufficient USDC on the network you're using: * **Base**: USDC on Base mainnet * **Solana**: USDC on Solana mainnet You can check your balance at: * Base: [BaseScan](https://basescan.org/) * Solana: [Solana Explorer](https://explorer.solana.com/) ## Environment Setup Create a `.env` file in your project directory: ```bash theme={null} # For Base network EVM_PRIVATE_KEY=0x1234567890abcdef... # For Solana network SVM_PRIVATE_KEY=5Jx7Ry8... # Optional: AI features (Anthropic or OpenAI) ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-... ``` The CLI will automatically load variables from `.env` files in the current directory. ## Verifying Installation Test your installation: ```bash theme={null} # Check version npx snackmoney --version # View help npx snackmoney --help # List available commands npx snackmoney ``` Expected output: ``` Commands: send Send USDC to a single user batch-send Send USDC to multiple users ai-agent AI-powered payment agent Options: --version Show version number --help Show help ``` ## Troubleshooting ### "command not found: snackmoney" If using global installation, ensure npm global bin is in your PATH: ```bash theme={null} # Check npm global bin location npm bin -g # Add to PATH (add to ~/.bashrc or ~/.zshrc) export PATH="$(npm bin -g):$PATH" ``` ### Permission Errors (macOS/Linux) If you encounter permission errors with global npm install: ```bash theme={null} # Option 1: Use npx instead (recommended) npx snackmoney # Option 2: Fix npm permissions mkdir ~/.npm-global npm config set prefix '~/.npm-global' echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc ``` ### Node Version Issues If you have an older Node.js version: ```bash theme={null} # Using nvm (recommended) nvm install 20 nvm use 20 # Verify node --version ``` ## Next Steps Now that you have the CLI installed: 1. [**Quick Start**](/cli/quick-start) - Send your first payment 2. [**Commands**](/cli/send) - Learn all available commands 3. [**View on GitHub**](https://github.com/snack-money/snackmoney-cli) - Source code and examples # CLI Overview Source: https://docs.snack.money/cli/overview Command-line tool for sending USDC payments The **Snack Money CLI** is a command-line tool for sending USDC payments to users on **X (Twitter)**, **Farcaster**, **GitHub**, **Email**, and **Web** using the x402 protocol. ## Key Features * **No wallet addresses needed** - Send to social usernames directly * **Multi-chain support** - Works on Base and Solana networks * **Batch payments** - Send to multiple users at once * **AI agent mode** - Use natural language for payments * **Simple installation** - No setup required with npx ## Supported Platforms Send USDC payments to users on these platforms: | Platform | Formats | Example | | --------------- | -------------------------------------------------------------- | ------------------------- | | **X (Twitter)** | `x/username`
`x.com/username`
`twitter.com/username` | `x/aeyakovenko` | | **Farcaster** | `farcaster/username`
`farcaster.xyz/username` | `farcaster/toly` | | **GitHub** | `github/username`
`github.com/username` | `github/octocat` | | **Email** | `email/address` | `email/mesut@snack.money` | | **Web** | `web/domain` | `web/snack.money` | ## Supported Networks * **Base** - EVM-compatible chain (requires `EVM_PRIVATE_KEY`) * **Solana** - SVM chain (requires `SVM_PRIVATE_KEY`) The CLI automatically detects which network to use based on your configured private key. ## Available Commands ### `send` - Single Payment Send USDC to a single user: ```bash theme={null} npx snackmoney send x/aeyakovenko 1¢ npx snackmoney send farcaster/toly $0.5 npx snackmoney send github/octocat 0.01 npx snackmoney send email/mesut@snack.money $0.25 npx snackmoney send web/snack.money 0.5 ``` [Learn more →](/cli/send) ### `batch-send` - Batch Payments Send to multiple users at once: ```bash theme={null} npx snackmoney batch-send x/user1:1¢,user2:2¢,user3:3¢ npx snackmoney batch-send ./payments.json ``` [Learn more →](/cli/batch-send) ### `ai-agent` - AI-Powered Payments Use natural language to describe payments: ```bash theme={null} npx snackmoney ai-agent --prompt "Send 1 USDC to @toly on Farcaster" ``` [Learn more →](/cli/ai-agent) ## Amount Formats The CLI supports flexible amount formats: * **Cents**: `1¢`, `50¢`, `99¢` * **Dollars**: `$0.01`, `$0.5`, `$1` * **Decimal**: `0.01`, `0.5`, `1` All amounts are processed as USDC. ## Quick Start Get started in 3 steps: 1. **Set your private key**: ```bash theme={null} export EVM_PRIVATE_KEY="your_private_key" # For Base # OR export SVM_PRIVATE_KEY="your_private_key" # For Solana ``` 2. **Run a payment**: ```bash theme={null} npx snackmoney send x/username 0.01 ``` 3. **Check the receipt**: The CLI returns a receipt URL to view your payment. [See detailed quick start guide →](/cli/quick-start) ## Installation Options Choose your preferred installation method: ### npx (Recommended) No installation required: ```bash theme={null} npx snackmoney --help ``` ### npm Global Install globally: ```bash theme={null} npm install -g snackmoney snackmoney --help ``` ### Homebrew For macOS/Linux: ```bash theme={null} brew tap snack-money/tap brew install snackmoney ``` [See all installation options →](/cli/installation) ## Why Use the CLI? * **Quick testing** - Test the API without writing code * **Scripting** - Automate payments in shell scripts * **Batch operations** - Process multiple payments efficiently * **No dependencies** - Works standalone with npx * **Developer-friendly** - Simple, intuitive commands ## Next Steps * [Installation Guide](/cli/installation) - Install the CLI * [Quick Start](/cli/quick-start) - Send your first payment * [Commands Reference](/cli/send) - Detailed command documentation * [View on GitHub](https://github.com/snack-money/snackmoney-cli) - Source code and examples # Quick Start Source: https://docs.snack.money/cli/quick-start Send your first payment with the Snack Money CLI This guide will walk you through sending your first USDC payment using the Snack Money CLI in just a few minutes. ## Prerequisites Before you begin, ensure you have: * **Node.js 20+** installed ([Download](https://nodejs.org/)) * **USDC balance** on Base or Solana network * **Private key** for your wallet ## Step 1: Set Your Private Key The CLI needs your private key to sign transactions. Set it as an environment variable: ### For Base Network (EVM) ```bash theme={null} export EVM_PRIVATE_KEY="0x..." ``` ### For Solana Network (SVM) ```bash theme={null} export SVM_PRIVATE_KEY="your_base58_private_key" ``` **Security Note**: Never commit your private key to version control. Use environment variables or a `.env` file. ### Using a .env File (Optional) Create a `.env` file in your project directory: ```bash theme={null} # .env EVM_PRIVATE_KEY=0x1234567890abcdef... ``` The CLI will automatically load it. ## Step 2: Send Your First Payment Now you're ready to send USDC! Use the `send` command: ### Send to an X (Twitter) User ```bash theme={null} npx snackmoney send x/aeyakovenko 1¢ ``` ### Send to a Farcaster User ```bash theme={null} npx snackmoney send farcaster/toly $0.5 ``` ### Send to a GitHub User ```bash theme={null} npx snackmoney send github/octocat 0.01 ``` ### Send to an Email Address ```bash theme={null} npx snackmoney send email/mesut@snack.money $0.25 ``` ### Send to a Web Domain ```bash theme={null} npx snackmoney send web/snack.money 0.5 ``` ## Step 3: Review the Output After running the command, you'll see: ``` 🚀 Sending payment... ✅ Payment successful! 📊 Transaction Details: Amount: 0.01 USDC Receiver: @username Platform: X (Twitter) Network: Base 🧾 Receipt: https://snack.money/x/username?txn=... ``` Click the receipt link to view your payment on Snack Money. ## Understanding the Command The basic syntax for sending a payment is: ```bash theme={null} npx snackmoney send ``` ### Platform Formats | Platform | Supported Formats | Example | | --------------- | ------------------------------------------ | ------------------------- | | **X (Twitter)** | `x/`, `x.com/`, `twitter/`, `twitter.com/` | `x/aeyakovenko` | | **Farcaster** | `farcaster/`, `farcaster.xyz/` | `farcaster/toly` | | **GitHub** | `github/`, `github.com/` | `github/octocat` | | **Email** | `email/` | `email/mesut@snack.money` | | **Web** | `web/` | `web/snack.money` | ### Amount Formats You can specify amounts in multiple formats: * **Cents**: `1¢`, `50¢`, `99¢` * **Dollars**: `$0.01`, `$0.5`, `$1` * **Decimal**: `0.01`, `0.5`, `1` All amounts are processed as USDC. ## Specifying the Network By default, the CLI auto-detects the network based on which private key you've set. You can explicitly specify the network with the `--network` flag: ```bash theme={null} # Force Base network npx snackmoney send x/username 0.01 --network base # Force Solana network npx snackmoney send x/username 0.01 --network solana ``` ## Examples Here are some practical examples: ### Example 1: Tip a Tweet ```bash theme={null} npx snackmoney send x/0xmesuthere 5¢ ``` ### Example 2: Support a Farcaster Creator ```bash theme={null} npx snackmoney send farcaster/mesut $1 ``` ### Example 3: Thank an Open Source Developer ```bash theme={null} npx snackmoney send github/octocat 0.50 ``` ## Next Steps Now that you've sent your first payment, explore more features: ### Send to Multiple Users Use batch payments to send to multiple users at once: ```bash theme={null} npx snackmoney batch-send x/user1:1¢,user2:2¢,user3:3¢ ``` [Learn more about batch payments →](/cli/batch-send) ### Use AI Agent Describe payments in natural language: ```bash theme={null} npx snackmoney ai-agent --prompt "Send 1 USDC to @toly on Farcaster" ``` [Learn more about AI agent →](/cli/ai-agent) ## Troubleshooting ### "Insufficient USDC balance" Ensure your wallet has enough USDC on the network you're using. Check your balance: * **Base**: [BaseScan](https://basescan.org/) * **Solana**: [Solana Explorer](https://explorer.solana.com/) ### "Invalid private key" Make sure your private key is correctly formatted: * **Base**: Should start with `0x` (66 characters total) * **Solana**: Base58 encoded string ### "User not found" The username may not exist on the specified platform. Verify: * The username is correct * The user has an account on the platform * You're using the correct platform prefix ## Additional Resources * [**CLI Overview**](/cli/overview) - Full feature overview * [**Installation Guide**](/cli/installation) - Detailed installation instructions * [**Send Command**](/cli/send) - Complete send command reference * [**GitHub Repository**](https://github.com/snack-money/snackmoney-cli) - Source code and examples ## Getting Help Need help? Here are your options: ```bash theme={null} # View general help npx snackmoney --help # View help for a specific command npx snackmoney send --help npx snackmoney batch-send --help ``` Or visit our [GitHub repository](https://github.com/snack-money/snackmoney-cli) to: * Report issues * Request features * View examples * Contribute # send Command Source: https://docs.snack.money/cli/send Send USDC to a single user The `send` command allows you to send USDC to a single user on X (Twitter), Farcaster, GitHub, Email, or Web. ## Syntax ```bash theme={null} snackmoney send [options] ``` ## Parameters ### platform/username The recipient's platform and username in the format `platform/username`. **Supported platforms:** | Platform | Formats | Example | | --------------- | -------------------------------------------------------------------------------------- | ------------------------- | | **X (Twitter)** | `x/username`
`x.com/username`
`twitter/username`
`twitter.com/username` | `x/aeyakovenko` | | **Farcaster** | `farcaster/username`
`farcaster.xyz/username` | `farcaster/toly` | | **GitHub** | `github/username`
`github.com/username` | `github/octocat` | | **Email** | `email/address` | `email/mesut@snack.money` | | **Web** | `web/domain` | `web/snack.money` | Username should be provided without the `@` symbol. ### amount The amount of USDC to send. Supports multiple formats: * **Cents notation**: `1¢`, `50¢`, `99¢` * **Dollar notation**: `$0.01`, `$0.50`, `$1` * **Decimal notation**: `0.01`, `0.50`, `1` ## Options ### --network Specify which blockchain network to use: * `base` - Use Base network (EVM) * `solana` - Use Solana network (SVM) If not specified, the CLI auto-detects based on which private key is configured. ```bash theme={null} snackmoney send x/username 0.01 --network base snackmoney send x/username 0.01 --network solana ``` ## Examples ### Send to X (Twitter) Users ```bash theme={null} # Using different platform formats snackmoney send x/aeyakovenko 1¢ snackmoney send x.com/jessepollak $0.5 snackmoney send twitter.com/0xmesuthere 50¢ # Different amount formats snackmoney send x/username 1¢ # Cents snackmoney send x/username $0.01 # Dollars snackmoney send x/username 0.01 # Decimal ``` ### Send to Farcaster Users ```bash theme={null} # Using different formats snackmoney send farcaster/toly $1 snackmoney send farcaster.xyz/mesut 0.50 ``` ### Send to GitHub Users ```bash theme={null} # Support open source developers snackmoney send github/octocat 5¢ snackmoney send github.com/torvalds $1 ``` ### Send to Email ```bash theme={null} # Send to email address snackmoney send email/mesut@snack.money $0.25 ``` ### Send to Web Domain ```bash theme={null} # Send to web domain snackmoney send web/snack.money 0.5 ``` ### Specify Network ```bash theme={null} # Force Base network snackmoney send x/username 0.01 --network base # Force Solana network snackmoney send x/username 0.01 --network solana ``` ## Output After sending a payment, you'll see: ``` 🚀 Sending payment... ✅ Payment successful! 📊 Transaction Details: Amount: 0.01 USDC Receiver: @username Platform: X (Twitter) Network: Base Transaction: 0xabc...def 🧾 Receipt: https://snack.money/x/username?txn=... ``` The output includes: * **Amount**: USDC amount sent * **Receiver**: Username and platform * **Network**: Blockchain used (Base or Solana) * **Transaction**: On-chain transaction hash * **Receipt**: Link to view payment details ## Prerequisites Before using the `send` command: 1. **Set your private key**: For Base: ```bash theme={null} export EVM_PRIVATE_KEY="0x..." ``` For Solana: ```bash theme={null} export SVM_PRIVATE_KEY="your_base58_key" ``` 2. **Ensure USDC balance**: Your wallet must have sufficient USDC on the network you're using. ## Use Cases ### Tipping Content Creators ```bash theme={null} # Tip a great tweet snackmoney send x/creator 10¢ # Support a Farcaster post snackmoney send farcaster/artist $0.50 ``` ### Supporting Open Source ```bash theme={null} # Thank a maintainer snackmoney send github/maintainer $5 # Fund a contributor snackmoney send github/contributor $2 ``` ### Quick Payments ```bash theme={null} # Pay for a service snackmoney send x/freelancer $10 # Send a quick refund snackmoney send farcaster/customer $3.50 ``` ## Error Handling ### Common Errors **"Insufficient USDC balance"** ``` Your wallet doesn't have enough USDC. Check your balance and add funds. ``` **"User not found"** ``` The username doesn't exist on the specified platform. Verify the username. ``` **"Invalid private key"** ``` Check that your private key is correctly set and formatted. ``` **"Network error"** ``` Check your internet connection and try again. ``` ## Limits and Fees * **Minimum amount**: 0.01 USDC (1¢) * **Maximum amount**: No hard limit (subject to wallet balance) * **Network fees**: Standard blockchain fees apply * Base: Low gas fees (\~$0.001-$0.01) * Solana: Very low fees (\~\$0.00025) ## Security * Your private key never leaves your machine * All transactions are signed locally * Payments are non-reversible (blockchain transactions) * Always verify the recipient before sending ## Related Commands * [**batch-send**](/cli/batch-send) - Send to multiple users at once * [**ai-agent**](/cli/ai-agent) - Use natural language for payments * [**Quick Start**](/cli/quick-start) - Getting started guide ## Getting Help View command-specific help: ```bash theme={null} snackmoney send --help ``` ## Additional Resources * [CLI Overview](/cli/overview) - All CLI features * [Installation](/cli/installation) - Install the CLI * [GitHub Repository](https://github.com/snack-money/snackmoney-cli) - Source code and examples # A2A Source: https://docs.snack.money/examples/a2a Agent-to-Agent protocol integration examples This guide demonstrates how to integrate Snack Money's A2A (Agent-to-Agent) protocol with X402 extension for cryptocurrency payments. ## Installation Clone the example repository: ```bash theme={null} git clone https://github.com/snack-money/snack-money.git cd snack-money/snack-money-examples/a2a yarn install ``` ## Configuration Create a `.env` file with your configuration: ### For Base Network ```env theme={null} EVM_PRIVATE_KEY=0x...your-private-key RECEIVER=username AMOUNT=0.01 PLATFORM=twitter ``` ### For Solana Network ```env theme={null} SVM_PRIVATE_KEY=your-solana-private-key-base58 RECEIVER=username AMOUNT=0.01 PLATFORM=twitter ``` ## Available Scripts ### Discover Agent Capabilities View Snack Money's A2A capabilities: ```bash theme={null} yarn agent-card ``` This displays: * Agent information and skills * Available payment methods * Input schemas and requirements * X402 extension support ### Send Payment via Base ```bash theme={null} yarn base ``` ### Send Payment via Solana ```bash theme={null} yarn solana ``` ## Implementation Examples ### Base Network Payment ```typescript theme={null} import axios from "axios"; import { privateKeyToAccount } from "viem/accounts"; import { x402Client } from "@x402/core/client"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; import { encodePaymentSignatureHeader } from "@x402/core/http"; // Setup const account = privateKeyToAccount(evmPrivateKey); const x402 = new x402Client(); registerExactEvmScheme(x402, { signer: account }); // Phase 1: Request payment requirements const initialRequest = { jsonrpc: "2.0", id: 1, method: "snack-money.pay.twitter", params: { receiver: "username", amount: 0.01, description: "Payment via A2A" } }; const response = await axios.post( "https://api.snack.money/a2a", initialRequest, { headers: { "Content-Type": "application/json", "X-A2A-Extensions": "https://a2a.dev/spec/extensions/x402/v0" } } ); // Phase 2: Execute on-chain payment const { taskId, payment } = response.data.result; const paymentReceipt = await x402.payment.execute(payment); // Phase 3: Submit payment proof const proofRequest = { jsonrpc: "2.0", id: 2, method: "snack-money.pay.twitter", params: { receiver: "username", amount: 0.01, taskId, payment: { network: payment.network, transactionHash: paymentReceipt.hash } } }; const finalResponse = await axios.post( "https://api.snack.money/a2a", proofRequest, { headers: { "Content-Type": "application/json", "X-A2A-Extensions": "https://a2a.dev/spec/extensions/x402/v0", "x-payment-signature": encodePaymentSignatureHeader( paymentReceipt.signature ) } } ); ``` ### Solana Network Payment ```typescript theme={null} import { Connection, PublicKey, Transaction } from "@solana/web3.js"; import { createTransferInstruction, getAssociatedTokenAddress } from "@solana/spl-token"; import bs58 from "bs58"; // Setup Solana connection and wallet const connection = new Connection("https://api.mainnet-beta.solana.com"); const keypair = Keypair.fromSecretKey(bs58.decode(svmPrivateKey)); // Phase 1: Request payment requirements (same as Base) const response = await axios.post( "https://api.snack.money/a2a", initialRequest, { headers: { "Content-Type": "application/json", "X-A2A-Extensions": "https://a2a.dev/spec/extensions/x402/v0" } } ); // Phase 2: Execute Solana USDC transfer const { taskId, payment } = response.data.result; const usdcMint = new PublicKey(payment.token); const recipientPubkey = new PublicKey(payment.recipient); // Create and send transaction const transaction = new Transaction().add( createTransferInstruction( await getAssociatedTokenAddress(usdcMint, keypair.publicKey), await getAssociatedTokenAddress(usdcMint, recipientPubkey), keypair.publicKey, BigInt(payment.amount) ) ); const signature = await connection.sendTransaction(transaction, [keypair]); await connection.confirmTransaction(signature); // Phase 3: Submit payment proof const proofRequest = { jsonrpc: "2.0", id: 2, method: "snack-money.pay.twitter", params: { receiver: "username", amount: 0.01, taskId, payment: { network: "solana:mainnet", transactionHash: signature } } }; ``` ## Batch Payments A2A also supports batch payments to multiple recipients: ```typescript theme={null} const batchRequest = { jsonrpc: "2.0", id: 1, method: "snack-money.batch-pay.twitter", params: { receivers: [ { receiver: "user1", amount: 0.01 }, { receiver: "user2", amount: 0.02 }, { receiver: "user3", amount: 0.03 } ], description: "Batch payment via A2A" } }; ``` ## Response Handling ### Success Response ```json theme={null} { "jsonrpc": "2.0", "id": 2, "result": { "taskId": "task_abc123", "status": "PAYMENT_CONFIRMED", "metadata": { "x402:transactionId": "1234567890", "x402:receipt": "https://snack.money/x/username?txn=1234567890" } } } ``` ### Error Response ```json theme={null} { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Invalid params", "data": { "field": "receiver", "reason": "User not found" } } } ``` ## Testing Start with small amounts (0.01 USDC = 1¢) to test the integration: ```bash theme={null} # Test Base network AMOUNT=0.01 RECEIVER=your-username yarn base # Test Solana network AMOUNT=0.01 RECEIVER=your-username yarn solana ``` ## Supported Platforms The A2A protocol supports payments to these platforms: * `twitter` - Twitter/X usernames * `farcaster` - Farcaster usernames * `github` - GitHub usernames * `email` - Email addresses * `web` - Web domains * `instagram` - Instagram usernames ## Example Output ``` 🚀 Starting Snack Money A2A Payment Example (Base Network) 🔧 Creating Base signer... ✅ Base signer created: 0x... 🎯 Using skill: snack-money.pay.twitter 💸 Sending 0.01 USDC to @username on twitter... 📋 Phase 1: Requesting payment requirements... ✅ Payment requirements received Task ID: task_1234567890 Network: eip155:8453 Amount: 10000 USDC (atomic units) 🔐 Phase 2: Executing on-chain payment... ✅ Payment sent: 0x... Waiting for confirmation... ✅ Payment confirmed! 📨 Phase 3: Submitting payment proof... ✅ Payment processed successfully! 🧾 Transaction ID: 1234567890 🔗 Receipt: https://snack.money/x/username?txn=1234567890 ``` ## Complete Example Repository The full working examples are available at: [github.com/snack-money/snack-money/tree/main/snack-money-examples/a2a](https://github.com/snack-money/snack-money/tree/main/snack-money-examples/a2a) ## Next Steps * Review the [A2A Protocol](/introduction/a2a) documentation * Learn about the [X402 Protocol](/introduction/x402) * Explore other [SDK Examples](/examples/overview) * Check the [API Reference](/api-reference/introduction) # x402-axios Source: https://docs.snack.money/examples/axios Simplest integration with axios and x402 v2 payment client This example demonstrates the simplest way to integrate Snack Money payments using **axios** with the **x402 v2 payment client**. Perfect for most web applications. ## Overview **@x402/axios v2** wraps the popular axios HTTP client with automatic x402 payment negotiation. When the API returns `402 Payment Required`, the client handles the payment flow automatically. ## Features * ✅ **Base (EVM) and Solana (SVM) network** support * ✅ **Automatic payment negotiation** * ✅ **Simple axios-based API** * ✅ **Type-safe TypeScript** * ✅ **Minimal setup** ## Prerequisites * Node.js 18+ * USDC balance on Base or Solana network * EVM private key (for Base) or SVM private key (for Solana) ## Installation ```bash theme={null} npm install axios @x402/axios @x402/evm @x402/svm viem ``` ## Quick Start ### 1. Set Up Environment Create a `.env` file: ```bash theme={null} # For Base network EVM_PRIVATE_KEY=0x... # For Solana network SVM_PRIVATE_KEY=base58_key... # Common RECEIVER=your_x_username AMOUNT=0.01 ``` **Important**: Use your own X (Twitter) account as the receiver to test the integration safely. ### 2. Implement Base (EVM) Payment Create `base-send.ts`: ```typescript theme={null} import axios from "axios"; import { privateKeyToAccount } from "viem/accounts"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader, } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; // Load environment variables const evmPrivateKey = process.env.EVM_PRIVATE_KEY as `0x${string}`; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment example with x402-axios v2\n"); console.log("ℹ️ Network: Base (EVM)\n"); // Create Base signer const evmAccount = privateKeyToAccount(evmPrivateKey); console.log("✅ Base signer created:", evmAccount.address); // Create x402 client and register EVM scheme const client = new x402Client(); registerExactEvmScheme(client, { signer: evmAccount }); console.log("✅ Registered EVM payment scheme\n"); // Create axios instance with x402 payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Base...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via x402-axios v2 (Base)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); // Decode and display payment response header (v2 uses payment-response) const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 3. Implement Solana (SVM) Payment Create `solana-send.ts`: ```typescript theme={null} import axios from "axios"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader, } from "@x402/axios"; import { registerExactSvmScheme } from "@x402/svm/exact/client"; import { createKeyPairSignerFromBytes } from "@solana/kit"; import bs58 from "bs58"; // Load environment variables const svmPrivateKey = process.env.SVM_PRIVATE_KEY as string; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment example with x402-axios v2\n"); console.log("ℹ️ Network: Solana (SVM)\n"); // Create Solana signer console.log("🔧 Creating Solana signer..."); const privateKeyBytes = bs58.decode(svmPrivateKey); const solanaSigner = await createKeyPairSignerFromBytes(privateKeyBytes); console.log("✅ Solana signer created:", solanaSigner.address); // Create x402 client and register Solana scheme const client = new x402Client(); registerExactSvmScheme(client, { signer: solanaSigner }); console.log("✅ Registered Solana payment scheme\n"); // Create axios instance with x402 payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Solana...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via x402-axios v2 (Solana)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); // Decode and display payment response header const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 4. Run the Example For Base network: ```bash theme={null} npm run base # or npx tsx base-send.ts ``` For Solana network: ```bash theme={null} npm run solana # or npx tsx solana-send.ts ``` ## Expected Output ``` 🚀 Starting Snack Money payment example with x402-axios ✅ Base signer created 💸 Sending 0.01 USDC to @username on X... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "0xabc...def", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## How It Works 1. **Create Signer**: Generate account from your private key (EVM or SVM) 2. **Create x402 Client**: Initialize the x402 client 3. **Register Scheme**: Register the appropriate payment scheme (EVM or SVM) 4. **Wrap Axios**: Add x402 payment wrapper 5. **Make Request**: POST to `/payments/x/pay` 6. **Auto Payment**: Client handles 402 response automatically 7. **Retry**: Request retries with payment proof 8. **Success**: Receive confirmation and receipt ## Supported Endpoints ### X (Twitter) Payments ```typescript theme={null} await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username", description: "Payment description" }); ``` ### Farcaster Payments ```typescript theme={null} await api.post("/payments/farcaster/pay", { amount: 0.5, currency: "USDC", receiver: "username", description: "Payment description" }); ``` ### GitHub Payments ```typescript theme={null} await api.post("/payments/github/pay", { amount: 1.0, currency: "USDC", receiver: "username", description: "Payment description" }); ``` ## Configuration Options ### Custom Axios Instance ```typescript theme={null} const api = withPaymentInterceptor( axios.create({ baseURL: "https://api.snack.money", timeout: 30000, headers: { "Content-Type": "application/json" } }), account as never ); ``` ### Request Options ```typescript theme={null} const response = await api.post( "/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username", description: "Payment description" }, { timeout: 60000 // Custom timeout for this request } ); ``` ## Error Handling ```typescript theme={null} try { const response = await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username" }); console.log("Payment successful:", response.data); } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 402) { console.error("Payment required but failed to process"); } else if (error.response?.status === 404) { console.error("User not found"); } else { console.error("API error:", error.response?.data); } } else { console.error("Unexpected error:", error); } } ``` ## Common Errors **Insufficient USDC Balance** ``` Ensure your wallet has enough USDC on Base network. Check balance at: https://basescan.org/ ``` **Invalid Private Key** ``` Private key must be a valid hex string starting with 0x Format: 0x followed by 64 hex characters ``` **User Not Found** ``` The receiver username doesn't exist on the platform. Verify the username is correct. ``` ## Testing Tips 1. **Start small**: Use 0.01 USDC for initial tests 2. **Test on yourself**: Send to your own X account 3. **Check balance**: Verify USDC balance before sending 4. **Save receipts**: Keep receipt URLs for records ## Full Example Repository View the complete example with configuration files: [View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/axios) The repository includes: * Complete TypeScript implementation * Environment configuration template * package.json with all dependencies * Detailed README ## Next Steps * [**Try CDP SDK**](/examples/cdp-sdk) - MPC-based key management * [**Try fetch**](/examples/fetch) - Minimal dependencies * [**API Reference**](/api-reference/introduction) - Full API documentation * [**x402 Protocol**](/introduction/x402) - Understanding the protocol ## Dependencies ```json theme={null} { "dependencies": { "axios": "^1.7.9", "@x402/axios": "^2.0.0", "@x402/evm": "^2.0.0", "@x402/svm": "^2.0.0", "viem": "^2.39.3", "bs58": "^6.0.0", "dotenv": "^16.4.7" }, "devDependencies": { "@types/bs58": "^5.0.0", "@types/node": "^22.0.0", "typescript": "^5.9.0" } } ``` ## Learn More * [@x402/axios Documentation](https://www.npmjs.com/package/@x402/axios) * [x402 Protocol Specification](https://github.com/coinbase/x402) * [Axios Documentation](https://axios-http.com/) * [Viem Documentation](https://viem.sh/) * [Solana Kit Documentation](https://www.npmjs.com/package/@solana/kit) # Coinbase CDP SDK Source: https://docs.snack.money/examples/cdp-sdk Server-side wallet management with MPC security and x402 v2 This example demonstrates integration using the **Coinbase Developer Platform (CDP) SDK** with MPC-based key management and **x402 v2**. Perfect for backend applications requiring enterprise-grade security. ## Overview The CDP SDK provides server-side wallet management without exposing private keys. Keys are secured with Multi-Party Computation (MPC) technology. This example works with x402 v2 for both Base and Solana networks. ## Features * ✅ **MPC-based key management** - No private keys in your code * ✅ **Base (EVM) and Solana (SVM) network** support * ✅ **Enterprise security** - Built by Coinbase * ✅ **Server-side wallets** - Perfect for backends * ✅ **Type-safe TypeScript** ## Prerequisites * Node.js 18+ * Coinbase CDP API credentials ([Get them here](https://portal.cdp.coinbase.com/)) * USDC balance on Base or Solana * Existing CDP wallet address (Base) or Solana account ## Installation ```bash theme={null} npm install @coinbase/cdp-sdk axios @x402/axios @x402/evm @x402/svm viem bs58 ``` ## Quick Start ### 1. Get CDP Credentials 1. Visit [Coinbase Developer Platform](https://portal.cdp.coinbase.com/) 2. Create an API key 3. Save your API Key ID and Secret 4. Create a wallet and fund it with USDC on Base ### 2. Set Up Environment Create a `.env` file: ```bash theme={null} CDP_API_KEY_ID=your_api_key_id CDP_API_KEY_SECRET=your_api_key_secret CDP_WALLET_SECRET=your_wallet_secret # For Base network WALLET_ADDRESS=your_wallet_address # For Solana network SOLANA_ADDRESS=your_solana_address # Common RECEIVER=your_x_username AMOUNT=0.01 ``` ### 3. Implement Base (EVM) Payment Create `base-send.ts`: ```typescript theme={null} import { CdpClient } from "@coinbase/cdp-sdk"; import axios from "axios"; import { privateKeyToAccount } from "viem/accounts"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; const apiKeyId = process.env.CDP_API_KEY_ID as string; const apiKeySecret = process.env.CDP_API_KEY_SECRET as string; const walletSecret = process.env.CDP_WALLET_SECRET as string; const walletAddress = process.env.WALLET_ADDRESS as string; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment with CDP SDK (Base)\n"); // Initialize CDP client const cdpClient = new CdpClient({ apiKeyId, apiKeySecret, walletSecret, }); console.log("✅ Initialized CDP client\n"); // Export private key from CDP for x402 signing console.log("🔐 Exporting private key from CDP...\n"); const privateKey = await cdpClient.evm.exportAccount({ address: walletAddress }); // Create viem account from private key const account = privateKeyToAccount(`0x${privateKey}`); console.log(`✅ Base signer created: ${account.address}\n`); // Create x402 client and register EVM scheme const x402 = new x402Client(); registerExactEvmScheme(x402, { signer: account }); console.log("✅ Registered EVM payment scheme\n"); // Wrap axios with payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), x402 ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Base...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via CDP SDK (Base)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 4. Implement Solana (SVM) Payment Create `solana-send.ts`: ```typescript theme={null} import { CdpClient } from "@coinbase/cdp-sdk"; import axios from "axios"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader } from "@x402/axios"; import { registerExactSvmScheme } from "@x402/svm/exact/client"; import { createKeyPairSignerFromBytes } from "@solana/kit"; import bs58 from "bs58"; const apiKeyId = process.env.CDP_API_KEY_ID as string; const apiKeySecret = process.env.CDP_API_KEY_SECRET as string; const walletSecret = process.env.CDP_WALLET_SECRET as string; const solanaAddress = process.env.SOLANA_ADDRESS as string; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment with CDP SDK (Solana)\n"); // Initialize CDP client const cdpClient = new CdpClient({ apiKeyId, apiKeySecret, walletSecret, }); console.log("✅ Initialized CDP client\n"); if (!solanaAddress) { console.error("❌ Missing SOLANA_ADDRESS in .env file!"); console.log("\n💡 Run the create-solana-account.ts script first:"); console.log(" npm run create-solana-account"); process.exit(1); } console.log(`✅ Using CDP Solana account: ${solanaAddress}\n`); // Export private key from CDP for x402 signing console.log("🔐 Exporting private key from CDP...\n"); const privateKeyBase58 = await cdpClient.solana.exportAccount({ address: solanaAddress }); // Create Solana signer from private key const privateKeyBytes = bs58.decode(privateKeyBase58); const solanaSigner = await createKeyPairSignerFromBytes(privateKeyBytes); console.log(`✅ Solana signer created: ${solanaSigner.address}\n`); // Create x402 client and register Solana scheme const client = new x402Client(); registerExactSvmScheme(client, { signer: solanaSigner }); console.log("✅ Registered Solana payment scheme\n"); // Wrap axios with payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Solana...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via CDP SDK (Solana)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 5. Run the Example For Base network: ```bash theme={null} npm run base # or npx tsx base-send.ts ``` For Solana network: ```bash theme={null} npm run solana # or npx tsx solana-send.ts ``` ## Expected Output ``` 🚀 Starting Snack Money payment with CDP SDK ✅ Initialized CDP client ✅ Retrieved CDP wallet 💸 Sending 0.01 USDC to @username on X... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "0xabc...def", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## How It Works 1. **Initialize CDP**: Create CDP client with API credentials 2. **Get Wallet**: Retrieve existing wallet by address 3. **Export Key**: Export private key for transaction signing 4. **Create Account**: Convert to viem account format 5. **Wrap Axios**: Add x402 payment interceptor 6. **Send Payment**: Make payment request ## Why CDP SDK? ### Security Benefits * **No Private Key Management**: Keys secured with MPC * **Enterprise Grade**: Built by Coinbase * **Compliance**: Meets regulatory requirements * **Audit Trail**: Complete transaction history ### Best For * Backend applications * Enterprise deployments * High-value transactions * Compliance-focused apps ## Supported Platforms Send payments to: ```typescript theme={null} // X (Twitter) await api.post("/payments/x/pay", { amount, receiver, currency: "USDC" }); // Farcaster await api.post("/payments/farcaster/pay", { amount, receiver, currency: "USDC" }); // GitHub await api.post("/payments/github/pay", { amount, receiver, currency: "USDC" }); ``` ## Error Handling ```typescript theme={null} try { const response = await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username" }); console.log("Success:", response.data); } catch (error) { console.error("Payment failed:", error); // Handle CDP-specific errors if (error.message.includes("wallet not found")) { console.error("CDP wallet not found. Check WALLET_ADDRESS"); } } ``` ## CDP Wallet Management ### Creating a Wallet ```typescript theme={null} const wallet = await coinbase.createWallet({ networkId: "base-mainnet" }); console.log("Wallet address:", wallet.getDefaultAddress()); ``` ### Funding the Wallet Transfer USDC to your wallet address on Base network before making payments. ## Full Example Repository [View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/cdp-sdk) Includes: * Complete implementation * Environment setup * Configuration examples * Detailed README ## Next Steps * [**Try x402-fetch**](/examples/fetch) - Minimal dependencies * [**Try thirdweb**](/examples/thirdweb) - Managed infrastructure * [**CDP Documentation**](https://docs.cdp.coinbase.com/) - Learn more about CDP ## Dependencies ```json theme={null} { "dependencies": { "@coinbase/coinbase-sdk": "latest", "axios": "^1.6.0", "x402-axios": "latest", "viem": "^2.0.0" } } ``` ## Learn More * [Coinbase CDP SDK Documentation](https://docs.cdp.coinbase.com/) * [x402 Protocol](https://github.com/coinbase/x402) * [API Reference](/api-reference/introduction) # Crossmint Source: https://docs.snack.money/examples/crossmint Smart contract wallets with x402 v2 protocol This example demonstrates integration using **Crossmint Smart Wallets** with **x402 v2**. Perfect for applications needing smart wallet features and account abstraction. ## Overview Integrate Snack Money payments using Crossmint's smart wallet infrastructure with x402 v2, using Crossmint's API for signing operations. ## Features * ✅ **Base network** support * ✅ **Smart wallet infrastructure** - Account abstraction * ✅ **API-based signing** - Secure signature requests * ✅ **Developer-controlled signing** - Full control * ✅ **x402 v2 integration** - Latest protocol ## Prerequisites * Node.js 18+ * Crossmint account ([Sign up](https://www.crossmint.com/)) * Crossmint API key * Smart wallet with USDC balance on Base ## Installation ```bash theme={null} npm install axios @x402/axios @x402/evm viem dotenv ``` ## Quick Start ### 1. Get Crossmint Credentials 1. Visit [Crossmint Console](https://www.crossmint.com/console) 2. Create a project 3. Get your API key 4. Create a smart wallet ### 2. Set Up Environment Create a `.env` file: ```bash theme={null} CROSSMINT_API_KEY=your_api_key WALLET_LOCATOR=your_wallet_locator SMART_WALLET_ADDRESS=your_smart_wallet_address RECEIVER=your_x_username AMOUNT=0.01 ``` **Important**: The `SMART_WALLET_ADDRESS` should have USDC balance on Base network. ### 3. Implement Payment Create `base-send.ts`: ```typescript theme={null} import axios from "axios"; import { config } from "dotenv"; import { type Hex, type Address, type SignableMessage } from "viem"; import { toAccount } from "viem/accounts"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; config(); const crossmintApiKey = process.env.CROSSMINT_API_KEY as string; const walletLocator = process.env.WALLET_LOCATOR as string; const smartWalletAddress = process.env.SMART_WALLET_ADDRESS as string; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); // Helper to request signatures from Crossmint API async function requestCrossmintSignature( walletLocator: string, apiKey: string, signatureRequest: any ): Promise { const createResponse = await axios.post( `https://www.crossmint.com/api/2022-06-09/wallets/${walletLocator}/signatures`, signatureRequest, { headers: { "X-API-KEY": apiKey, "Content-Type": "application/json" } } ); const signatureId = createResponse.data.id; // Poll for signature let signature: string | null = null; let attempts = 0; const maxAttempts = 20; while (!signature && attempts < maxAttempts) { attempts++; const statusResponse = await axios.get( `https://www.crossmint.com/api/2022-06-09/wallets/${walletLocator}/signatures/${signatureId}`, { headers: { "X-API-KEY": apiKey } } ); signature = statusResponse.data.outputSignature; if (signature) return signature as Hex; if (statusResponse.data.status === 'failed') { throw new Error(`Signature failed: ${JSON.stringify(statusResponse.data)}`); } await new Promise(resolve => setTimeout(resolve, 1000)); } throw new Error(`Signature did not complete after ${maxAttempts} attempts`); } // Create a viem account that uses Crossmint's signature API function createCrossmintAccount( address: Address, walletLocator: string, apiKey: string ) { const account = toAccount({ address, async signMessage({ message }: { message: SignableMessage }): Promise { const messageStr = typeof message === 'string' ? message : (message as any).raw || JSON.stringify(message); return requestCrossmintSignature(walletLocator, apiKey, { type: "evm-message", params: { message: messageStr, chain: "base" } }); }, signTransaction: async () => { throw new Error("Transaction signing not supported - use Crossmint transaction API"); }, signTypedData: async (typedData: any): Promise => { return requestCrossmintSignature(walletLocator, apiKey, { type: "evm-typed-data", params: { typedData, chain: "base" } }); } }); return { ...account, sign: async ({ hash }: { hash: Hex }): Promise => { return account.signMessage({ message: { raw: hash } as any }); } } as any; } async function sendPayment() { console.log("🚀 Starting Snack Money payment with Crossmint Smart Wallet\n"); console.log("ℹ️ Network: Base (EVM)\n"); console.log(`✅ Smart Wallet Address: ${smartWalletAddress}`); console.log(`💡 Check balance: https://basescan.org/address/${smartWalletAddress}\n`); // Create Crossmint account const crossmintAccount = createCrossmintAccount( smartWalletAddress as Address, walletLocator, crossmintApiKey ); // Create x402 client and register EVM scheme const client = new x402Client(); registerExactEvmScheme(client, { signer: crossmintAccount }); // Wrap axios with payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Base...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via Crossmint Smart Wallet (Base)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } if (response.data.data?.receipt) { console.log(`\n🧾 Receipt: ${response.data.data.receipt}`); } } catch (error: any) { console.error("❌ Payment failed:", error.response?.data || error.message); process.exit(1); } } sendPayment(); ``` ### 4. Run the Example ```bash theme={null} npm run base # or npx tsx base-send.ts ``` ## Expected Output ``` 🚀 Starting Snack Money payment with Crossmint Smart Wallet ℹ️ Network: Base (EVM) ✅ Smart Wallet Address: 0x... 💡 Check balance: https://basescan.org/address/0x... 🔐 Creating Crossmint account... 💸 Sending 0.01 USDC to @username on X via Base... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "...", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## How It Works 1. **Create Crossmint Account**: Build a viem-compatible account that uses Crossmint's signature API 2. **Register x402 EVM Scheme**: Configure x402 client with the Crossmint signer 3. **Wrap Axios**: Add x402 payment interceptor 4. **Send Payment**: Make payment request 5. **Auto Signatures**: Crossmint API handles message and typed data signing 6. **Success**: Receive confirmation and receipt ## Why Crossmint? ### Benefits * **Smart Wallets**: Advanced wallet capabilities * **Account Abstraction**: Gasless transactions, batching * **Viem Compatible**: Standard interface * **Developer Controlled**: Full control over signing * **Easy Integration**: Simple SDK ### Best For * Apps needing smart wallet features * Account abstraction requirements * Gasless transactions * Advanced wallet operations ## Smart Wallet Features ### Gasless Transactions ```typescript theme={null} const wallet = await CrossmintSmartWallet.build({ config: { chain: "base", apiKey: process.env.CROSSMINT_API_KEY!, gasless: true, // Enable gasless transactions }, signer: { type: "DEVELOPER_CONTROLLED", secret: process.env.CROSSMINT_SIGNER_SECRET!, }, }); ``` ### Transaction Batching ```typescript theme={null} // Batch multiple operations await wallet.sendBatchTransaction([ { to: address1, data: "0x..." }, { to: address2, data: "0x..." }, ]); ``` ## Supported Platforms ```typescript theme={null} // X (Twitter) await api.post("/payments/x/pay", { amount: 0.01, receiver: "username", currency: "USDC" }); // Farcaster await api.post("/payments/farcaster/pay", { amount: 0.5, receiver: "username", currency: "USDC" }); // GitHub await api.post("/payments/github/pay", { amount: 1.0, receiver: "username", currency: "USDC" }); ``` ## Error Handling ```typescript theme={null} try { const response = await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username" }); console.log("Success:", response.data); } catch (error) { console.error("Payment failed:", error); // Handle Crossmint-specific errors if (error.message.includes("insufficient funds")) { console.error("Smart wallet needs more USDC"); } } ``` ## Wallet Management ### Check Balance ```typescript theme={null} const balance = await wallet.getBalance(); console.log("Wallet balance:", balance); ``` ### Get Wallet Info ```typescript theme={null} console.log("Address:", wallet.address); console.log("Chain:", wallet.chain); ``` ## Full Example Repository [View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/crossmint) Includes: * Complete implementation * Smart wallet setup * Configuration guide * Detailed README ## Next Steps * [**Try axios**](/examples/axios) - Simplest integration * [**Crossmint Docs**](https://docs.crossmint.com/) - Learn more * [**API Reference**](/api-reference/introduction) - Complete API docs ## Dependencies ```json theme={null} { "dependencies": { "axios": "^1.7.9", "@x402/axios": "^2.0.0", "@x402/evm": "^2.0.0", "viem": "^2.39.3", "dotenv": "^16.4.7" }, "devDependencies": { "@types/node": "^22.0.0", "typescript": "^5.9.0" } } ``` ## Learn More * [Crossmint Documentation](https://docs.crossmint.com/) * [Smart Wallets Guide](https://docs.crossmint.com/wallets/smart-wallets) * [@x402/axios Documentation](https://www.npmjs.com/package/@x402/axios) * [x402 Protocol Specification](https://github.com/coinbase/x402) * [Viem Documentation](https://viem.sh/) # x402-fetch Source: https://docs.snack.money/examples/fetch Minimal x402 v2 integration with axios This example demonstrates a minimal integration using **x402 v2** with axios. Despite the name "fetch", this example uses the @x402/axios package for consistency and simplicity. Perfect for Node.js applications with minimal setup. ## Overview **@x402/axios v2** provides a minimal integration with automatic x402 payment handling, with support for both EVM and SVM networks. ## Features * ✅ **Base (EVM) and Solana (SVM)** network support * ✅ **Minimal setup** - Quick integration * ✅ **Minimal dependencies** * ✅ **Type-safe TypeScript** * ✅ **Simple pattern** ## Prerequisites * Node.js 18+ * USDC balance on Base or Solana * EVM private key (for Base) or SVM private key (for Solana) ## Installation ```bash theme={null} npm install axios @x402/axios @x402/evm @x402/svm viem bs58 ``` ## Quick Start ### 1. Set Up Environment Create a `.env` file: ```bash theme={null} # For Base network EVM_PRIVATE_KEY=0x... # For Solana network SVM_PRIVATE_KEY=base58_key... # Common RECEIVER=your_x_username AMOUNT=0.01 ``` ### 2. Implement Base (EVM) Payment Create `base-send.ts`: ```typescript theme={null} import axios from "axios"; import { privateKeyToAccount } from "viem/accounts"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader, } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; const evmPrivateKey = process.env.EVM_PRIVATE_KEY as `0x${string}`; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment with x402 v2\n"); console.log("ℹ️ Network: Base (EVM)\n"); // Create Base signer const evmAccount = privateKeyToAccount(evmPrivateKey); console.log("✅ Base signer created:", evmAccount.address); // Create x402 client and register EVM scheme const client = new x402Client(); registerExactEvmScheme(client, { signer: evmAccount }); console.log("✅ Registered EVM payment scheme\n"); // Wrap axios with payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Base...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via x402 v2 (Base)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 3. Implement Solana (SVM) Payment Create `solana-send.ts`: ```typescript theme={null} import axios from "axios"; import { x402Client, wrapAxiosWithPayment, decodePaymentResponseHeader, } from "@x402/axios"; import { registerExactSvmScheme } from "@x402/svm/exact/client"; import { createKeyPairSignerFromBytes } from "@solana/kit"; import bs58 from "bs58"; const svmPrivateKey = process.env.SVM_PRIVATE_KEY as string; const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); async function sendPayment() { console.log("🚀 Starting Snack Money payment with x402 v2\n"); console.log("ℹ️ Network: Solana (SVM)\n"); // Create Solana signer const privateKeyBytes = bs58.decode(svmPrivateKey); const solanaSigner = await createKeyPairSignerFromBytes(privateKeyBytes); console.log("✅ Solana signer created:", solanaSigner.address); // Create x402 client and register Solana scheme const client = new x402Client(); registerExactSvmScheme(client, { signer: solanaSigner }); console.log("✅ Registered Solana payment scheme\n"); // Wrap axios with payment interceptor const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); console.log(`💸 Sending ${amount} USDC to @${receiver} on X via Solana...\n`); try { const response = await api.post("/payments/x/pay", { amount, currency: "USDC", receiver, description: "Payment via x402 v2 (Solana)" }); console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(response.data, null, 2)); const paymentResponseHeader = response.headers["payment-response"]; if (paymentResponseHeader) { const paymentResponse = decodePaymentResponseHeader(paymentResponseHeader); console.log("\n🔐 Payment Response Details:", JSON.stringify(paymentResponse, null, 2)); } } catch (error) { console.error("❌ Payment failed:", error); throw error; } } sendPayment(); ``` ### 4. Run the Example For Base network: ```bash theme={null} npm run base # or npx tsx base-send.ts ``` For Solana network: ```bash theme={null} npm run solana # or npx tsx solana-send.ts ``` ## Expected Output ``` 🚀 Starting Snack Money payment with x402-fetch (BASE) ✅ Created Base signer 💸 Sending 0.01 USDC to @username on X... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "0xabc...def", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## Network Support ### Base (EVM) ```typescript theme={null} import { privateKeyToAccount } from "viem/accounts"; const signer = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const client = withPayment(fetch, signer); ``` ### Solana (SVM) ```typescript theme={null} import { Keypair } from "@solana/web3.js"; import bs58 from "bs58"; const keypair = Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY)); const client = withPayment(fetch, keypair); ``` ## Switching Networks Simply change the `NETWORK` environment variable: ```bash theme={null} # Use Base NETWORK=base PRIVATE_KEY=0x... npm run dev # Use Solana NETWORK=solana PRIVATE_KEY=... npm run dev ``` ## Supported Platforms ```typescript theme={null} // X (Twitter) await client("https://api.snack.money/payments/x/pay", { method: "POST", body: JSON.stringify({ amount: 0.01, receiver: "username", currency: "USDC" }) }); // Farcaster await client("https://api.snack.money/payments/farcaster/pay", { method: "POST", body: JSON.stringify({ amount: 0.5, receiver: "username", currency: "USDC" }) }); // GitHub await client("https://api.snack.money/payments/github/pay", { method: "POST", body: JSON.stringify({ amount: 1.0, receiver: "username", currency: "USDC" }) }); ``` ## Error Handling ```typescript theme={null} try { const response = await client("https://api.snack.money/payments/x/pay", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ amount: 0.01, receiver: "username", currency: "USDC" }) }); if (!response.ok) { const error = await response.json(); console.error("Payment failed:", error); return; } const data = await response.json(); console.log("Success:", data); } catch (error) { console.error("Network error:", error); } ``` ## Why x402-fetch? ### Advantages * **Minimal Dependencies**: Uses native fetch * **Multi-Chain**: Supports Base and Solana * **Lightweight**: Small bundle size * **Familiar API**: Standard fetch interface ### Best For * Node.js applications * Minimal dependency requirements * Multi-chain support needed * Backend services ## Full Example Repository [View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/fetch) Includes: * Base and Solana implementations * Environment templates * Complete setup guide ## Next Steps * [**Try axios**](/examples/axios) - More features, familiar API * [**Try CDP SDK**](/examples/cdp-sdk) - Enterprise security * [**API Reference**](/api-reference/introduction) - Complete documentation ## Dependencies ```json theme={null} { "dependencies": { "axios": "^1.7.9", "@x402/axios": "^2.0.0", "@x402/evm": "^2.0.0", "@x402/svm": "^2.0.0", "viem": "^2.39.3", "bs58": "^6.0.0", "dotenv": "^16.4.7" }, "devDependencies": { "@types/node": "^20.0.0", "typescript": "^5.0.0" } } ``` ## Learn More * [@x402/axios Documentation](https://www.npmjs.com/package/@x402/axios) * [x402 Protocol Specification](https://github.com/coinbase/x402) * [Axios Documentation](https://axios-http.com/) * [Viem Documentation](https://viem.sh/) * [Solana Kit Documentation](https://www.npmjs.com/package/@solana/kit) # MCP Source: https://docs.snack.money/examples/mcp Model Context Protocol implementation with x402 payments ## Overview This example demonstrates how to use the Model Context Protocol (MCP) with x402 payments to enable AI agents to make paid API calls to Snack Money. ## Features * JSON-RPC 2.0 protocol implementation * x402 payment integration * Support for Base (EVM) and Solana networks * Tool discovery and invocation * Automatic payment handling ## Installation Clone the example repository: ```bash theme={null} git clone https://github.com/snack-money/snack-money-examples.git cd snack-money-examples/mcp yarn install ``` ## Configuration Create a `.env` file with your credentials: ```env theme={null} # For Base (EVM) network EVM_PRIVATE_KEY=0x... # For Solana network SVM_PRIVATE_KEY=...base58... # Common settings RECEIVER=username AMOUNT=0.01 PLATFORM=twitter # twitter, farcaster, email, github, web API_URL=https://api.snack.money ``` ## Usage ### List Available Tools Discover all available MCP tools: ```bash theme={null} yarn list-tools ``` Output: ```json theme={null} { "tools": [ { "name": "pay_twitter", "description": "Send USDC to a Twitter/X user", "inputSchema": { ... } }, { "name": "pay_farcaster", "description": "Send USDC to a Farcaster user", "inputSchema": { ... } }, // ... more tools ] } ``` ### Send Payment via Base Network ```bash theme={null} yarn base ``` This will: 1. Call the MCP endpoint to send payment 2. Receive payment requirements (error -32402) 3. Sign the payment with x402 EVM client 4. Retry with signed payment 5. Display transaction receipt ### Send Payment via Solana Network ```bash theme={null} yarn solana ``` Similar flow to Base, but using Solana blockchain. ## Code Example Here's a simplified example of making an MCP call with payment: ```typescript theme={null} import { X402 } from '@x402/core'; import { createEvmClient } from '@x402/evm'; // Initialize x402 client const x402 = createEvmClient({ privateKey: process.env.EVM_PRIVATE_KEY, chainId: 8453 // Base mainnet }); // Make MCP call async function callMcpTool(toolName: string, args: any) { // First attempt - will require payment const response = await fetch(`${API_URL}/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: toolName, arguments: args }, id: 1 }) }); const result = await response.json(); // Check if payment required if (result.error?.code === -32402) { const { taskId, paymentRequired } = result.error.data; // Sign payment const signedPayment = await x402.createPaymentPayload( paymentRequired ); // Retry with payment const paidResponse = await fetch(`${API_URL}/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: toolName, arguments: args, _meta: { taskId, x402Payment: signedPayment } }, id: 2 }) }); return paidResponse.json(); } return result; } // Use the function const result = await callMcpTool('pay_twitter', { receiver: 'alice', amount: 0.01, description: 'Thanks for the help!' }); console.log('Payment sent:', result.result); ``` ## Protocol Flow The MCP payment flow follows this sequence: 1. **Initial Call** - Client calls MCP tool without payment 2. **Payment Required** - Server returns error -32402 with: * `taskId` - Unique identifier for this task * `paymentRequired` - x402 payment requirements 3. **Sign Payment** - Client signs payment using x402 client 4. **Retry with Payment** - Client retries with: * Original parameters * `_meta.taskId` - Task identifier * `_meta.x402Payment` - Signed payment proof 5. **Success** - Server returns result with receipt ## Error Handling Common error codes: | Code | Description | Action | | ------ | ---------------- | --------------------------- | | -32402 | Payment required | Sign and retry with payment | | -32600 | Invalid request | Check request format | | -32601 | Method not found | Verify method name | | -32602 | Invalid params | Check parameter format | | -32603 | Internal error | Retry or contact support | ## Supported Networks * **Base (Chain ID: 8453)** - USDC on Base mainnet * **Base Sepolia (Chain ID: 84532)** - USDC on Base testnet * **Solana** - USDC on Solana mainnet * **Solana Devnet** - USDC on Solana devnet ## Integration with AI Agents This MCP implementation is compatible with: * [Coinbase CDP Payments MCP](https://docs.cdp.coinbase.com/payments-mcp/welcome) * Claude Desktop MCP tools * Custom AI agents using MCP protocol ## Full Example View the complete working example: [GitHub: snack-money-examples/mcp](https://github.com/snack-money/snack-money-examples/tree/main/mcp) ## Related Examples * [A2A Example](/examples/a2a) - Agent-to-Agent protocol * [Axios Example](/examples/axios) - HTTP interceptor for x402 * [CDP SDK Example](/examples/cdp-sdk) - Coinbase Developer Platform integration # Overview Source: https://docs.snack.money/examples/overview Production-ready integration examples with various x402 v2 clients Explore different ways to integrate Snack Money's x402 v2 payment API into your application. Each example demonstrates a complete implementation with a different SDK or infrastructure provider. ## Available Examples ### MCP Protocol Model Context Protocol with x402 payments for AI tool calling. * **Best for**: AI agents and LLMs with tool calling capabilities * **Networks**: Base (EVM), Solana (SVM) * **Complexity**: Simple * **Features**: JSON-RPC 2.0, tool discovery, automatic payment handling ```typescript theme={null} // Discover available tools POST https://api.snack.money/mcp { "jsonrpc": "2.0", "method": "tools/list", "id": 1 } // Call a tool with payment POST https://api.snack.money/mcp { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "pay_twitter", "arguments": { "receiver": "username", "amount": 0.01 } } } ``` [View full example →](/examples/mcp) ### A2A Protocol Agent-to-Agent protocol implementation with X402 extension. * **Best for**: AI agents and autonomous systems * **Networks**: Base (EVM), Solana (SVM) * **Complexity**: Simple * **Features**: Agent discovery, JSON-RPC 2.0, async payments ```typescript theme={null} // Discover agent capabilities GET https://api.snack.money/a2a/.well-known/agent-card // Send payment via JSON-RPC POST https://api.snack.money/a2a { "jsonrpc": "2.0", "method": "snack-money.pay.twitter", "params": { "receiver": "username", "amount": 0.01 } } ``` [View full example →](/examples/a2a) ### x402-axios (v2) The simplest integration using axios with x402 v2 payment client. * **Best for**: Most web applications * **Networks**: Base (EVM), Solana (SVM) * **Complexity**: Simple * **Dependencies**: Minimal ```typescript theme={null} import { x402Client, wrapAxiosWithPayment } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; const client = new x402Client(); registerExactEvmScheme(client, { signer: account }); const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username" }); ``` [View full example →](/examples/axios) ### Coinbase CDP SDK Server-side wallet management with MPC security. * **Best for**: Backend applications, enterprises * **Networks**: Base (EVM), Solana (SVM) * **Complexity**: Moderate * **Key management**: MPC-based, no private keys needed ```typescript theme={null} const privateKey = await cdpClient.evm.exportAccount({ address: walletAddress }); const account = privateKeyToAccount(`0x${privateKey}`); const client = new x402Client(); registerExactEvmScheme(client, { signer: account }); const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); ``` [View full example →](/examples/cdp-sdk) ### x402-fetch (v2) Minimal integration using x402 v2 with axios under the hood. * **Best for**: Node.js apps, minimal footprint * **Networks**: Base (EVM), Solana (SVM) * **Complexity**: Simple * **Dependencies**: Minimal ```typescript theme={null} import { x402Client, wrapAxiosWithPayment } from "@x402/axios"; import { registerExactEvmScheme } from "@x402/evm/exact/client"; const client = new x402Client(); registerExactEvmScheme(client, { signer: account }); const api = wrapAxiosWithPayment( axios.create({ baseURL: "https://api.snack.money" }), client ); ``` [View full example →](/examples/fetch) ### thirdweb Managed infrastructure with thirdweb's payment API. * **Best for**: Apps using thirdweb ecosystem * **Network**: Base (EVM) * **Complexity**: Moderate * **Key management**: Managed by thirdweb ```typescript theme={null} const wallet = new PrivateKeyWallet({ client, privateKey: process.env.THIRDWEB_PRIVATE_KEY }); // Use with x402 wrapper ``` [View full example →](/examples/thirdweb) ### Crossmint Smart Wallets Smart contract wallets with account abstraction. * **Best for**: Apps needing smart wallet features * **Network**: Base (EVM) * **Complexity**: Moderate * **Features**: Account abstraction, smart wallets ```typescript theme={null} const wallet = CrossmintSmartWallet.build({ config: { chain: "base" }, signer: { type: "DEVELOPER_CONTROLLED" } }); // Use with viem-compatible interface ``` [View full example →](/examples/crossmint) ## Comparison Matrix | Example | Network(s) | Private Keys | Complexity | Best For | | ------------- | ------------ | ------------ | ----------- | --------------- | | **MCP** | Base, Solana | Direct | ⭐ Simple | AI tool calling | | **A2A** | Base, Solana | Direct | ⭐ Simple | AI agents | | **axios** | Base, Solana | Direct | ⭐ Simple | Most apps | | **CDP SDK** | Base, Solana | MPC managed | ⭐⭐ Moderate | Enterprises | | **fetch** | Base, Solana | Direct | ⭐ Simple | Node.js apps | | **thirdweb** | Base | Managed | ⭐⭐ Moderate | thirdweb users | | **Crossmint** | Base | Smart wallet | ⭐⭐ Moderate | Smart wallets | ## Quick Start Each example follows the same structure: 1. **Clone or copy** the example code 2. **Install dependencies**: `npm install` 3. **Configure environment**: Copy `.env.example` to `.env` 4. **Add credentials**: Private key and receiver username 5. **Run**: `npm run dev` ## Common Prerequisites All examples require: * **Node.js 18+** * **USDC balance** on the target network * **Receiver username**: Use your own X account for testing ## Supported Platforms All examples support sending payments to: * **X (Twitter)** - `/payments/x/pay` * **Farcaster** - `/payments/farcaster/pay` * **GitHub** - `/payments/github/pay` ## Network Support | Network | MCP | A2A | axios | CDP SDK | fetch | thirdweb | Crossmint | | ---------- | --- | --- | ----- | ------- | ----- | -------- | --------- | | **Base** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **Solana** | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ## Choosing the Right Example ### Use **MCP** if you're: * Building AI agents with tool calling * Integrating with Claude, GPT, or other LLMs * Need standardized tool discovery * Want automatic payment handling in AI workflows ### Use **A2A** if you're: * Building AI agents or autonomous systems * Need agent discovery capabilities * Want JSON-RPC based communication * Implementing agent-to-agent payments ### Use **axios** if you want: * Simplest integration * Familiar HTTP client * Minimal setup * Both Base and Solana support ### Use **CDP SDK** if you want: * Enterprise-grade security * No direct private key management * Server-side wallets * Both Base and Solana support ### Use **fetch** if you want: * Minimal dependencies * Simple integration * Both Base and Solana support ### Use **thirdweb** if you're: * Already using thirdweb * Building on their infrastructure * Need their ecosystem tools ### Use **Crossmint** if you need: * Smart contract wallets * Account abstraction * Advanced wallet features ## Integration Steps ### 1. Choose Your Example Pick the example that matches your stack and requirements. ### 2. Set Up Environment All examples use environment variables for configuration: ```bash theme={null} # For EVM networks (Base) EVM_PRIVATE_KEY=0x... RECEIVER=your_x_username AMOUNT=0.01 # For Solana network (SVM) SVM_PRIVATE_KEY=base58_key... # Additional keys for specific examples ANTHROPIC_API_KEY=sk-ant-... # For AI features CDP_API_KEY_ID=... # For CDP SDK THIRDWEB_SECRET_KEY=... # For thirdweb CROSSMINT_API_KEY=... # For Crossmint ``` ### 3. Install Dependencies ```bash theme={null} cd examples/ npm install ``` ### 4. Run the Example ```bash theme={null} npm run dev ``` ## Testing Tips 1. **Start small**: Use 0.01 USDC (1 cent) for initial tests 2. **Test on yourself**: Send to your own X account 3. **Check balance**: Ensure sufficient USDC + gas fees 4. **Verify receipt**: Click the receipt URL to confirm payment ## Example Output All examples produce similar output: ``` 🚀 Starting Snack Money payment example ✅ Signer/wallet created 💸 Sending 0.01 USDC to @username on X... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "...", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## Source Code All example source code is available on GitHub: [View examples repository →](https://github.com/snack-money/snack-money-examples) Each example includes: * Complete TypeScript implementation * Environment configuration * README with setup instructions * package.json with dependencies ## Next Steps 1. **Choose an example** that fits your needs 2. **Follow the guide** for that specific example 3. **Integrate** into your application 4. **Refer to API docs** for advanced usage ## Additional Resources * [**Getting Started**](/introduction/getting-started) - Quick API overview * [**x402 Protocol**](/introduction/x402) - Understanding x402 * [**API Reference**](/api-reference/introduction) - Complete API docs * [**CLI Tool**](/cli/overview) - Command-line interface ## Getting Help * **GitHub Issues**: Report bugs or request features * **Documentation**: Comprehensive guides for each example * **API Support**: Contact via [snack.money](https://snack.money) # thirdweb Source: https://docs.snack.money/examples/thirdweb Managed infrastructure with thirdweb's x402 payment wrapper This example demonstrates integration using **thirdweb's x402 payment wrapper API**. Perfect for applications already using the thirdweb ecosystem. ## Overview Integrate Snack Money payments using thirdweb's x402 fetch wrapper, which handles payment negotiation through thirdweb's managed infrastructure. ## Features * ✅ **Base network** support * ✅ **Managed infrastructure** - thirdweb handles x402 flow * ✅ **x402 wrapper via API** - Automatic payment negotiation * ✅ **Server-side wallet** - Secure key management * ✅ **thirdweb ecosystem** - Works with other thirdweb tools ## Prerequisites * Node.js 18+ * thirdweb account ([Sign up](https://thirdweb.com/)) * thirdweb Secret Key * thirdweb server wallet with USDC balance on Base ## Installation ```bash theme={null} npm install dotenv ``` ## Quick Start ### 1. Get thirdweb Credentials 1. Visit [thirdweb Dashboard](https://thirdweb.com/dashboard) 2. Create a new project 3. Get your Client ID and Secret Key 4. Create a wallet and fund with USDC ### 2. Set Up Environment Create a `.env` file: ```bash theme={null} THIRDWEB_SECRET_KEY=your_secret_key WALLET_ADDRESS=your_thirdweb_server_wallet_address RECEIVER=your_x_username AMOUNT=0.01 ``` **Important**: The `WALLET_ADDRESS` should be your thirdweb server wallet address that has USDC on Base network. ### 3. Implement Payment Create `base-send.ts`: ```typescript theme={null} import { config } from "dotenv"; config(); async function sendPayment() { const receiver = process.env.RECEIVER as string; const amount = parseFloat(process.env.AMOUNT || "0.01"); const secretKey = process.env.THIRDWEB_SECRET_KEY as string; const walletAddress = process.env.WALLET_ADDRESS as string; if (!receiver || !secretKey || !walletAddress) { console.error("Missing required environment variables: RECEIVER, THIRDWEB_SECRET_KEY, and WALLET_ADDRESS"); process.exit(1); } console.log("🚀 Starting Snack Money payment with thirdweb\n"); console.log(`📍 Wallet Address: ${walletAddress}`); console.log(`💡 Check balance: https://basescan.org/address/${walletAddress}\n`); const url = "https://api.snack.money/payments/x/pay"; const encodedUrl = encodeURIComponent(url); const usdcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base const chainId = 8453; // Base network const maxValue = 1000000; // 1 USDC in smallest units (6 decimals) console.log(`💸 Sending ${amount} USDC to @${receiver} on X...\n`); // Use thirdweb's x402 fetch wrapper const response = await fetch( `https://api.thirdweb.com/v1/payments/x402/fetch?from=${walletAddress}&url=${encodedUrl}&method=POST&chainId=${chainId}&maxValue=${maxValue}&asset=${usdcAddress}`, { method: "POST", headers: { "x-secret-key": secretKey, "Content-Type": "application/json" }, body: JSON.stringify({ amount, currency: "USDC", receiver, description: "Payment via thirdweb x402 wrapper" }) } ); const data = await response.json(); if (response.status === 200) { console.log("✅ Payment successful!"); console.log("\n📊 Response:", JSON.stringify(data, null, 2)); } else { console.error("❌ Payment failed"); console.error("Status:", response.status); console.error("Response:", JSON.stringify(data, null, 2)); } } sendPayment(); ``` ### 4. Run the Example ```bash theme={null} npm run base # or npx tsx base-send.ts ``` ## Expected Output ``` 🚀 Starting Snack Money payment with thirdweb ✅ Initialized thirdweb client 💸 Sending 0.01 USDC to @username on X... ✅ Payment successful! 📊 Response: { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "0xabc...def", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## How It Works 1. **Initialize thirdweb**: Create client with API credentials 2. **Create Wallet**: Load wallet from private key 3. **Convert Account**: Convert to viem format for x402 4. **Wrap Axios**: Add payment interceptor 5. **Send Payment**: Make payment request ## Why thirdweb? ### Benefits * **Managed Infrastructure**: thirdweb handles blockchain complexity * **Ecosystem Integration**: Works with other thirdweb services * **Developer Experience**: Simple, consistent APIs * **Multi-Chain Support**: Easy to extend to other chains ### Best For * Apps already using thirdweb * Need thirdweb ecosystem features * Want managed infrastructure * Building multi-chain apps ## Supported Platforms ```typescript theme={null} // X (Twitter) await api.post("/payments/x/pay", { amount: 0.01, receiver: "username", currency: "USDC" }); // Farcaster await api.post("/payments/farcaster/pay", { amount: 0.5, receiver: "username", currency: "USDC" }); // GitHub await api.post("/payments/github/pay", { amount: 1.0, receiver: "username", currency: "USDC" }); ``` ## thirdweb Features ### Using thirdweb Wallets ```typescript theme={null} import { inAppWallet } from "thirdweb/wallets"; // Create in-app wallet for users const wallet = inAppWallet(); await wallet.connect({ client, strategy: "email", email: "user@example.com" }); ``` ### Smart Wallets ```typescript theme={null} import { smartWallet } from "thirdweb/wallets"; const wallet = smartWallet({ chain: base, gasless: true }); ``` ## Error Handling ```typescript theme={null} try { const response = await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "username" }); console.log("Success:", response.data); } catch (error) { console.error("Payment failed:", error); } ``` ## Full Example Repository [View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/thirdweb) Includes: * Complete implementation * thirdweb configuration * Environment setup * Detailed README ## Next Steps * [**Try Crossmint**](/examples/crossmint) - Smart wallet features * [**thirdweb Docs**](https://portal.thirdweb.com/) - Learn more about thirdweb * [**API Reference**](/api-reference/introduction) - Complete API docs ## Dependencies ```json theme={null} { "dependencies": { "thirdweb": "^5.0.0", "axios": "^1.6.0", "x402-axios": "latest", "viem": "^2.0.0" } } ``` ## Learn More * [thirdweb Documentation](https://portal.thirdweb.com/) * [x402 Protocol](https://github.com/coinbase/x402) * [thirdweb SDK Reference](https://portal.thirdweb.com/typescript/v5) # A2A Protocol Source: https://docs.snack.money/introduction/a2a Agent-to-Agent protocol integration with Snack Money ## What is A2A? **A2A (Agent-to-Agent)** is a JSON-RPC 2.0 based protocol that enables AI agents to discover and communicate with each other. Snack Money implements A2A with the **X402 extension**, combining agent discovery with cryptocurrency payments. ## Key Features * **Agent Discovery** - Automatic service discovery via agent cards * **JSON-RPC 2.0** - Standard protocol for agent communication * **X402 Extension** - Integrated crypto payment capabilities * **Multi-Network** - Support for both Base and Solana networks * **Task-Based Flow** - Asynchronous payment processing * **6 Payment Platforms** - Twitter, Farcaster, GitHub, Email, Web, Instagram ## How A2A Works with Snack Money ### 1. Discovery Phase Agents discover Snack Money's capabilities through the agent card: ```bash theme={null} GET https://api.snack.money/a2a/.well-known/agent-card ``` The agent card describes: * Available payment skills (e.g., `snack-money.pay.twitter`) * Required parameters and schemas * Supported X402 extension ### 2. Payment Request Agents send JSON-RPC requests to initiate payments: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "snack-money.pay.twitter", "params": { "receiver": "username", "amount": 0.01, "description": "Payment via A2A", "meta": { "agent_name": "my-agent" } } } ``` ### 3. Payment Requirements Snack Money responds with payment requirements: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": { "taskId": "task_abc123", "status": "PAYMENT_REQUIRED", "payment": { "network": "eip155:8453", "amount": "10000", "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "recipient": "0x..." } } } ``` ### 4. On-Chain Payment The agent executes the USDC transfer on the specified network (Base or Solana). ### 5. Payment Proof Submission After blockchain confirmation, the agent resubmits with proof: ```json theme={null} { "jsonrpc": "2.0", "id": 2, "method": "snack-money.pay.twitter", "params": { "receiver": "username", "amount": 0.01, "taskId": "task_abc123", "payment": { "network": "eip155:8453", "transactionHash": "0x..." } } } ``` ### 6. Completion Snack Money verifies the payment and returns success: ```json theme={null} { "jsonrpc": "2.0", "id": 2, "result": { "taskId": "task_abc123", "status": "PAYMENT_CONFIRMED", "metadata": { "x402:transactionId": "1234567890", "x402:receipt": "https://snack.money/x/username?txn=1234567890" } } } ``` ## Available Skills Snack Money exposes the following A2A skills: ### Single Payments * `snack-money.pay.twitter` - Send to Twitter/X users * `snack-money.pay.farcaster` - Send to Farcaster users * `snack-money.pay.github` - Send to GitHub users * `snack-money.pay.email` - Send to email addresses * `snack-money.pay.web` - Send to web domains * `snack-money.pay.instagram` - Send to Instagram users ### Batch Payments * `snack-money.batch-pay.twitter` - Batch payments to Twitter users * `snack-money.batch-pay.farcaster` - Batch payments to Farcaster users * `snack-money.batch-pay.github` - Batch payments to GitHub users * `snack-money.batch-pay.email` - Batch payments to email addresses * `snack-money.batch-pay.web` - Batch payments to web domains * `snack-money.batch-pay.instagram` - Batch payments to Instagram users ## Required Headers When making A2A requests, include: ```http theme={null} Content-Type: application/json X-A2A-Extensions: https://a2a.dev/spec/extensions/x402/v0 ``` ## Network Support ### Base (EVM) * Network ID: `eip155:8453` * Token: USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`) * Use EVM private key for signing ### Solana (SVM) * Network ID: `solana:mainnet` * Token: USDC SPL token * Use Solana private key for signing ## Integration Example For complete working examples, see the [A2A Examples](/examples/a2a) page or check out the [snack-money-examples/a2a](https://github.com/snack-money/snack-money-examples/tree/main/a2a) repository. ## Why A2A + X402? The combination of A2A and X402 protocols provides: 1. **Agent Interoperability** - Agents can discover and use services automatically 2. **Payment Integration** - Native crypto payments without manual setup 3. **Standardized Communication** - JSON-RPC 2.0 ensures compatibility 4. **Decentralized** - No central authority or intermediary required 5. **Multi-Chain** - Support for different blockchain networks ## Learn More * [A2A Protocol Specification](https://a2a-protocol.org/) * [X402 Protocol](/introduction/x402) - Payment protocol details * [A2A Examples](/examples/a2a) - Implementation examples * [Agent Card API](https://api.snack.money/a2a/.well-known/agent-card) - Live agent card # Getting Started Source: https://docs.snack.money/introduction/getting-started Send your first payment with Snack Money API This guide will help you send your first USDC payment to an X (Twitter) user using the simplest integration method: **x402-axios**. ## Quick Example Send USDC to any X user with just a few lines of code: ```typescript theme={null} import axios from "axios"; import { withPaymentInterceptor } from "x402-axios"; import { privateKeyToAccount } from "viem/accounts"; // Create a signer from your private key const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY); // Wrap axios with x402 payment interceptor const api = withPaymentInterceptor( axios.create({ baseURL: "https://api.snack.money" }), account as never ); // Send payment - x402 handles the payment flow automatically const response = await api.post("/payments/x/pay", { amount: 0.01, currency: "USDC", receiver: "0xmesuthere", description: "Payment via x402" }); console.log("Payment successful!", response.data); // { // "code": 200, // "msg": "0.01 USDC sent successfully", // "data": { // "txn_id": "...", // "amount": 0.01, // "receipt": "https://snack.money/x/0xmesuthere?txn=..." // } // } ``` ## How It Works 1. **Initial Request**: Your app makes a payment request to Snack Money API 2. **402 Response**: API returns payment requirements (amount, recipient, chain) 3. **Auto Payment**: x402-axios automatically executes the on-chain USDC transfer 4. **Retry with Proof**: Request is retried with payment proof 5. **Success**: API processes the payment and returns confirmation Learn more about the [x402 protocol](/introduction/x402). ## Prerequisites * **Node.js 18+** * **USDC balance** on Base or Solana network * **Private key** for signing transactions ## Installation ```bash theme={null} npm install axios x402-axios viem ``` ## Environment Setup Create a `.env` file: ```bash theme={null} # For Base network (EVM) EVM_PRIVATE_KEY=0x... # For Solana network SVM_PRIVATE_KEY=your_solana_private_key_base58 ``` ## Supported Platforms Send payments to users on: * **X (Twitter)** - `/payments/x/pay` * **Farcaster** - `/payments/farcaster/pay` * **GitHub** - `/payments/github/pay` ## Next Steps * [**Explore SDK Examples**](/examples/overview) - See all integration options * [**Use the CLI**](/cli/overview) - Send payments from command line * [**API Reference**](/api-reference/introduction) - Full API documentation # Model Context Protocol (MCP) Source: https://docs.snack.money/introduction/mcp Use MCP protocol with x402 payments for AI agent tool calling ## What is MCP? The **Model Context Protocol (MCP)** is an open protocol that standardizes how AI systems interact with external tools and data sources. Snack Money implements MCP with x402 payment support, enabling AI agents to make paid API calls seamlessly. ## How It Works MCP uses JSON-RPC 2.0 for communication. When an AI agent calls a Snack Money tool through MCP: 1. **Tool Discovery** - Agent queries available tools via `tools/list` 2. **Tool Invocation** - Agent calls a tool with `tools/call` 3. **Payment Required** - Server returns error code `-32402` with payment requirements 4. **Payment Signing** - Agent signs the payment using x402 protocol 5. **Retry with Payment** - Agent retries with payment proof 6. **Success** - Server processes the payment and returns results ## MCP Payment Flow ``` Client Snack Money API | | |-------- tools/call --------> | | (no payment) | | | |<------ Error -32402 -------- | | (payment required) | | | |-- Sign with x402 client --> | | | |-------- tools/call --------> | | (with payment proof) | | | |<-------- Success ---------- | | (with receipt) | ``` ## Available Tools Snack Money provides the following MCP tools, each requiring x402 payment: | Tool | Description | Parameters | | --------------- | -------------------------------- | ----------------------------------- | | `pay_farcaster` | Send USDC to a Farcaster user | `receiver`, `amount`, `description` | | `pay_twitter` | Send USDC to a Twitter/X user | `receiver`, `amount`, `description` | | `pay_email` | Send USDC to an email address | `receiver`, `amount`, `description` | | `pay_web` | Send USDC to a web domain owner | `receiver`, `amount`, `description` | | `pay_github` | Send USDC to a GitHub user | `receiver`, `amount`, `description` | | `batch_pay` | Send USDC to multiple recipients | `payments[]` | ## Quick Start ### 1. Install Dependencies ```bash npm theme={null} npm install @x402/core @x402/evm @x402/svm ``` ```bash yarn theme={null} yarn add @x402/core @x402/evm @x402/svm ``` ### 2. Initialize MCP Session ```javascript theme={null} const response = await fetch('https://api.snack.money/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'initialize', params: { protocolVersion: '0.1.0', clientInfo: { name: 'my-agent', version: '1.0.0' } }, id: 1 }) }); ``` ### 3. List Available Tools ```javascript theme={null} const response = await fetch('https://api.snack.money/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/list', id: 2 }) }); const { result } = await response.json(); console.log('Available tools:', result.tools); ``` ### 4. Call a Tool with Payment ```javascript theme={null} import { X402 } from '@x402/core'; import { createEvmClient } from '@x402/evm'; // Initialize x402 client const x402Client = createEvmClient({ privateKey: process.env.EVM_PRIVATE_KEY, chainId: 8453 // Base mainnet }); // First call - will require payment const firstCall = await fetch('https://api.snack.money/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'pay_twitter', arguments: { receiver: 'alice', amount: 0.01, description: 'Thanks for the help!' } }, id: 3 }) }); const response = await firstCall.json(); // Check if payment is required if (response.error?.code === -32402) { const { taskId, paymentRequired } = response.error.data; // Sign payment const signedPayment = await x402Client.createPaymentPayload( paymentRequired ); // Retry with payment const paidCall = await fetch('https://api.snack.money/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'pay_twitter', arguments: { receiver: 'alice', amount: 0.01, description: 'Thanks for the help!' }, _meta: { taskId, x402Payment: signedPayment } }, id: 4 }) }); const result = await paidCall.json(); console.log('Payment successful:', result.result); } ``` ## Full Example Check out the complete [MCP example](https://github.com/snack-money/snack-money-examples/tree/main/mcp) in our GitHub repository for: * Base (EVM) network implementation * Solana network implementation * Tool listing and discovery * Batch payment support * Error handling ## Integration with AI Agents ### Coinbase CDP Payments MCP Snack Money's MCP implementation is compatible with [Coinbase CDP Payments MCP](https://docs.cdp.coinbase.com/payments-mcp/welcome), allowing you to: * Use Snack Money as a payment provider in CDP-powered AI agents * Send payments to social media users through CDP's MCP interface * Integrate with Coinbase's wallet infrastructure * Leverage CDP's security and compliance features For detailed integration instructions, see the [CDP Payments MCP documentation](https://docs.cdp.coinbase.com/payments-mcp/welcome). ### Other AI Development Tools Popular AI development tools that support MCP include: * **Claude Desktop** - Native MCP support for tool calling * **Continue.dev** - VS Code extension with MCP support * **Cline** - Command-line interface for MCP tools * **Custom Agents** - Build your own using the MCP SDK ## Security Considerations * All payments require cryptographic signatures via x402 * Task IDs prevent replay attacks * Payments are verified on-chain before processing * Rate limiting applies to prevent abuse ## Related Documentation * [x402 Protocol](/introduction/x402) - Learn about the payment protocol * [A2A Protocol](/introduction/a2a) - Agent-to-Agent communication * [API Reference](/api-reference/introduction) - Full API documentation # Overview Source: https://docs.snack.money/introduction/overview What is Snack Money API? Snack Money is an **x402-enabled micropayment API** that allows applications and AI agents to integrate **permissionless payments** tied to **social identities**. ## Key Features * **USDC on Base and Solana** for instant settlements * Support for **X (Twitter)**, **Farcaster**, **GitHub**, **Email**, **Web**, and **Instagram** payments * **x402 protocol** for standardized HTTP payment flows * **A2A protocol** for agent-to-agent communication and payments * **CLI tool** for command-line payments * **Multiple SDKs** for easy integration ## What is x402? The x402 protocol standardizes HTTP `402 Payment Required` flows, enabling: * Automatic payment negotiation * Tokenized access with proof of payment * Seamless web-native monetization Learn more in our [x402 guide](/introduction/x402). ## What is A2A? The A2A (Agent-to-Agent) protocol enables AI agents to discover and communicate with each other. Snack Money implements A2A with the X402 extension for integrated payments. Learn more in our [A2A guide](/introduction/a2a). ## Getting Started Choose your preferred integration method: ### For Developers * [**Quick Start**](/introduction/getting-started) - Simplest API integration with axios * [**SDK Examples**](/examples/overview) - Production-ready integrations with various SDKs * [**API Reference**](/api-reference/introduction) - Complete API documentation ### For Command Line * [**CLI Tool**](/cli/overview) - Send payments directly from your terminal * [**CLI Quick Start**](/cli/quick-start) - Get started in minutes # x402 Protocol Source: https://docs.snack.money/introduction/x402 Understanding the x402 payment protocol The **x402 protocol** is an HTTP-based payment standard that enables seamless micropayments on the web. It extends the HTTP `402 Payment Required` status code to create a standardized payment negotiation flow. ## What is x402? x402 solves the problem of web monetization by providing a standard way for clients and servers to negotiate and complete payments automatically, without manual intervention. ### Key Benefits * **Automatic Payment Negotiation** - No manual payment flows * **Multi-Chain Support** - Works with Base, Solana, and other chains * **Standard HTTP Flow** - Uses familiar HTTP patterns * **Proof of Payment** - Cryptographic verification of transactions * **Developer Friendly** - Simple integration with existing tools ## How x402 Works The x402 protocol follows a simple 4-step flow: ### 1. Initial Request Your application makes a standard HTTP request to a payment-required endpoint: ```typescript theme={null} POST /payments/x/pay { "amount": 0.01, "currency": "USDC", "receiver": "username" } ``` ### 2. Payment Challenge (402 Response) The server responds with `402 Payment Required` and includes payment details in the response headers: ```http theme={null} HTTP/1.1 402 Payment Required x-payment-request: ``` The payment request contains: * Payment amount and currency * Recipient address * Blockchain network * Transaction details ### 3. Payment Execution Your x402 client automatically: 1. Decodes the payment requirements 2. Creates and signs a blockchain transaction 3. Submits the transaction to the network 4. Waits for confirmation ### 4. Retry with Proof After payment confirmation, the client retries the original request with proof of payment: ```http theme={null} POST /payments/x/pay x-payment-response: { "amount": 0.01, "currency": "USDC", "receiver": "username" } ``` The server verifies the payment and returns success: ```json theme={null} { "code": 200, "msg": "0.01 USDC sent successfully", "data": { "txn_id": "...", "amount": 0.01, "receipt": "https://snack.money/x/username?txn=..." } } ``` ## Implementation Options ### Using x402 Clients The easiest way to integrate x402 is using a pre-built client library: **x402-axios** (Recommended for most applications) ```bash theme={null} npm install x402-axios ``` **x402-fetch** (For minimal dependencies) ```bash theme={null} npm install x402-fetch ``` See our [SDK Examples](/examples/overview) for implementation guides. ### Using the CLI For command-line usage, use the Snack Money CLI: ```bash theme={null} npx snackmoney send x/username 0.01 ``` Learn more in the [CLI documentation](/cli/overview). ## Supported Networks Snack Money's x402 implementation supports: * **Base** (EVM) - USDC payments on Base mainnet * **Solana** (SVM) - USDC payments on Solana mainnet ## Security x402 provides strong security guarantees: * **Cryptographic Proofs** - All payments are verified on-chain * **No Custody** - You maintain control of your private keys * **Transparent** - All transactions are publicly verifiable * **Standard Protocol** - Open specification, no vendor lock-in ## Learn More * [Getting Started Guide](/introduction/getting-started) - Send your first payment * [SDK Examples](/examples/overview) - Integration examples * [x402 Specification](https://github.com/coinbase/x402) - Full protocol documentation