Solana Pay

repository·main·Indexed 23 days ago

https://github.com/solana-foundation/pay

A payment layer for HTTP that handles 402 (Payment Required) challenges using Solana-based stablecoin signing. It includes a CLI for wrapping commands (curl, claude, codex), a built-in Model Context Protocol (MCP) server for AI agents, and the @solana/pay library for implementing merchant and wallet payment flows.

Tokens
83.5K
Snippets
134
Records
475
Agent score
82%

What's inside solana-foundation/pay

  1. Use the Payment Debugger to visualize Solana payment flows

    main

    The Payment Debugger is a real-time tool that groups HTTP 402 challenge-response cycles into single payment flows and visualizes them using sequence diagrams. This allows developers to inspect exactly what happens at each step of a payment transaction.

    It supports two protocols:

    • MPP (Monetized Payment Protocol): Uses www-authenticate and payment-receipt headers.
    • x402: Uses the X-PAYMENT header with facilitator verify/settle logic.

    The debugger runs against the Solana Payment Sandbox, meaning no real funds are required for testing.

  2. Monetize APIs with Pay

    main

    Pay allows developers to put an API behind a payment gateway. It handles HTTP 402 (Payment Required) challenges, verifies payments, and then either proxies the request to an upstream API or responds directly.

    There are two primary components:

    1. pay gate api <paywall.yml>: Runs the payment gateway process.
    2. pay-skills provider markdown: A file used to list your API in the public registry so AI agents (like Claude or Codex) can discover and use it.

    To begin, you can scaffold a new configuration using:

    pay server scaffold paywall.yml
  3. Use Pay MCP tools for paid API access

    main

    The pay toolset (also known as pay-cli or pay.sh) provides agents with user-authorized, paid HTTP/API access without requiring manual API key management. It handles the '402 Payment Required' challenge by preparing a payment and requesting local user approval (e.g., Touch ID on macOS) before funds move.

    Key characteristics:

    • Settlement: Uses stablecoins (USDC, USDT, or CASH) as the underlying rail.
    • No SOL required: The user's account does not need SOL for network fees; server-side fee payers handle transaction costs.
    • Security: Keys stay in secure local storage, and every payment requires local user authentication.
    • Usage Pattern: Use Pay for deliberate, user-directed API calls rather than autonomous browsing.
  4. Use cases for Solana Pay transaction requests

    main

    Developers can use transaction requests to implement several advanced payment and engagement patterns:

    • Atomic Multi-Action Transactions: Merchants can mint NFTs or transfer loyalty tokens simultaneously with the payment at the point of sale.
    • Composable DeFi at POS: Enable complex transactions involving swaps, borrowing, escrow, or yield generation during a purchase. This can support features like refunds, chargebacks, or buy-now-pay-later.
    • Reduced User Friction: Merchants can pay for transaction fees, token account creation, or NFT minting on behalf of the customer, allowing users to transact without needing SOL in their wallets.
    • Permissioned Payments: Merchants can decline to respond to a request, which can be used to enforce authentication or compliance requirements.
    • Dynamic Brand Experiences: Beyond simple commerce, brands can use requests to send tokens, invitations, or gifts to customers (e.g., minting 1:1 NFTs for event attendees).
  5. Follow provider selection and cost optimization rules

    main

    To ensure efficient and cost-effective use of Pay providers, follow these rules:

    Provider Selection Rules

    • Hard-filter mismatches: Do not pay if there is a wrong network, wrong currency, unusable endpoint shape, incompatible method/body, or if the price exceeds the user's limit.
    • Prefer exact task ownership:
      • Influencer search $\rightarrow$ social data or influencer provider.
      • Wallet balances/history $\rightarrow$ blockchain analytics.
      • Stablecoin/token volume $\rightarrow$ blockchain analytics or BigQuery.
      • Raw Solana RPC $\rightarrow$ RPC provider.
      • Image/video generation $\rightarrow$ media generation.
      • SQL over public datasets $\rightarrow$ BigQuery.
    • Tie-breaking: If multiple providers match, resolve ties in this order: exact endpoint fit, supported network/currency, usable request shape, likely result quality/freshness, and total estimated price.
    • Endpoint Type: Prefer simple synchronous endpoints for small one-shot tasks. Use async or batch endpoints only if they materially reduce cost or are required by the task.
    • Uncertainty: If price, schema, network support, or quality is unclear after running search_catalog and get_catalog_entry, ask the user instead of guessing.
    • Failure Handling: If a paid call fails with 404, unsupported network, invalid payment challenge, or unusable schema, do not retry random providers. Try at most one clear fallback or ask the user.

    Cost Optimization Patterns

    • Check usage notes: Use provider usage notes from get_catalog_entry to find ways to avoid wasted calls.
    • Batching: Batch records when an endpoint supports arrays.
    • Minimize Scope: Use the smallest limit, date window, media duration, or result fields necessary.
    • Skip Discovery: Skip schema/model/list/discovery calls if the user has already provided identifiers.
    • Poll, don't retrigger: Keep track of async job IDs, JWTs, and operation names to poll them rather than paying to retrigger the same work.
  6. Use the `openapi:` form for registry registration

    main

    If your gateway serves an /openapi.json file, it is recommended to use the openapi: key in your registry markdown instead of listing endpoints: manually. This allows pay skills build to automatically resolve pricing and protocol metadata by probing the live 402 challenges.

    Supported Forms:

    1. Fully-qualified URL (Recommended): Use a https:// URL. The registry validator requires this because the registry is consumed remotely.
      openapi:
        url: https://my-api.example.com/openapi.json
    2. Inline JSON: Use a YAML literal block for small, static specs.
      openapi:
        content: |
          {
            "openapi": "3.0.0",
            ...
          }

    Note: openapi: { path: ... } is not valid in the registry; path: is reserved for local filesystem use with the pay gate api --openapi <file> command.

    ---
    name: my-api
    title: "My API"
    description: "..."
    use_case: "..."
    category: data
    service_url: https://my-api.example.com
    openapi:
      url: https://my-api.example.com/openapi.json
    ---
  7. Secure Payment Flow Best Practices

    main

    To prevent client-side manipulation of payment amounts, follow this secure integration pattern:

    1. Initiation: Customer visits the payment page.
    2. Order Creation: Merchant frontend sends order info to the backend.
    3. Session Setup: Merchant backend generates a unique reference public key and stores it in a database along with the expected amount for that specific checkout session.
    4. Redirection: Merchant backend redirects the user to a confirmation page using the generated reference public key.
    5. Completion: The confirmation page redirects the user back to the merchant with the transaction signature.
    6. Verification: Merchant backend validates the transaction signature against the reference and amount stored in step 3 to ensure the correct amount was paid for the correct session.
  8. How `pay curl` handles metered endpoints

    main

    When using pay curl <url> to access metered endpoints, the CLI follows a specific workflow to handle 402 Payment Required responses:

    1. The request is sent and returns a 402 status.
    2. pay curl prepares the necessary payment.
    3. The CLI prompts for local signing approval.
    4. Once approved, the CLI retries the request, including the payment proof in the headers.

    Free endpoints are passed through normally without requiring payment.

  9. Transaction Serialization and Signing Rules

    main

    When building a Solana Pay application, follow these rules for transaction construction to ensure wallet compatibility:

    If the transaction has no signatures:

    • The application should set the feePayer to the account provided in the POST request, or the zero value (11111111111111111111111111111111).
    • The application should set the recentBlockhash to the latest blockhash, or the zero value.
    • Note: The wallet will ignore the feePayer and recentBlockhash in the transaction and overwrite them with the account from the request and the latest blockhash respectively.

    If the transaction already has signatures:

    • The application must set the feePayer to the public key of the first signature.
    • The application must set the recentBlockhash to the latest blockhash.
    • The application must serialize and deserialize the transaction before signing to ensure consistent account key ordering.
    • The wallet will verify existing signatures and only sign with the account provided in the request.
  10. Understand Solana Pay Request Types

    main

    Solana Pay uses a token transfer URL scheme to standardize how payment requests are created and interpreted. There are two primary types of requests:

    1. Transaction Requests: An interactive request for any Solana transaction. The URL parameters allow a wallet to make an HTTP request to compose a transaction.
    2. Transfer Requests: A non-interactive request for a SOL or SPL Token transfer. The URL parameters allow a wallet to directly compose the transaction.
  11. Solana Pay Transfer Request URL Format

    main

    A Solana Pay transfer request URL is a standard protocol used to encode non-interactive requests for SOL or SPL Token transfers. These URLs can be shared via QR codes, NFC tags, or direct links. The URL follows a specific structure where the solana: scheme is followed by a recipient pathname and optional query parameters.

    URL Structure:

    solana:<recipient>
          ?amount=<amount>
          &spl-token=<spl-token>
          &reference=<reference>
          &label=<label>
          &message=<message>
          &memo=<memo>
  12. Solana Pay Transfer Request URL Specification

    main

    A Solana Pay transfer request URL is a standard protocol used to encode non-interactive requests for SOL or SPL Token transfers. These URLs can be encoded in QR codes, NFC tags, or sent directly between users and applications. Wallets use the parameters in these URLs to automatically compose a transaction for the user.

    URL Structure

    solana:<recipient>
          ?amount=<amount>
          &spl-token=<spl-token>
          &reference=<reference>
          &label=<label>
          &message=<message>
          &memo=<memo>