phdargen 45d7d19250
Batch-settlement TS sdk (#2061)
* spec + sdk

* add auto recover and topUp; add filestorage

* add session manager

* fix nonce reset

* add cooperativeWithdraw to spec/contract

* add cooperative withdraw to sdk

* update sdk to match spec v1.2

* change to auto-generated getters

* improve server devx

* improve client devx

* added concurrent request example

* minor fixes

* add cas

* add streaming example

* rename files to batched*

* updated scheme name deferred -> batched

* update to new contracts

* align paymentresponse.extra for all payloads

* fix recovery after refund

* fix withdraw -> refund flag

* fix channel manager

* rename to batch-settlement

* align with cloudflare specs

* remove claim/refund without sign

* add tx sim

* improve specs

* specs ready

* add unit/integration tests

* fix tests

* improve typing, remove dead code

* add readmes

* add e2e tests

* fix fileStorage

* increase depositMultiplier for streaming

* refund without paid request

* refactor convertToTokenAmount

* refactor scheme

* fix recovery for refund flow

* refactor client scheme

* rename session -> channel

* remove chargedCumulativeAmount from deposit payload

* scheme hook adapters

* add enrichSettlementPayload/enrichSettlementResponse hooks

* move batch-settlement scheme to scheme hook adapters and enrichSettlementResponse

* refactor refund and other payloads

* add client hook adapters

* align payment-response shapes

* move corrective 402 info from errorDetails to requirements.extra.channelState

* fix corrective deposit flow

* update to latest deployment and change channelId computation to EIP-712

* add hook to handle route handler failures

* add atomic channel update and request context primitives

* guard channels with pending reservations

* fix concurrent claim/settle

* skip facilitator and verify locally if onchain state fresh

* add redis storage

* add fullstack next example with redis and fix settlementOverride for next package

* align payment-response for all payloads

* add permit2 support and fix extra enrichment for nested objects

* fix DEPOSIT_WITNESS_TYPE_STRING

* test client state-loss recovery scenario in e2e

* fix recovery for axios

* improve channel manager

* update client deposit policy

* clean up examples

* add to testnet facilitator

* update READMEs

* for the culture

* add changesets

* update to latest deployment

* align error codes

* remove receiverAuthorizer fallback
2026-05-04 16:43:57 -04:00
..
2026-04-16 12:38:54 -07:00
2026-03-27 18:19:18 -07:00

E2E Test Server: Echo (Go)

This server demonstrates and tests the x402 Echo middleware with both EVM and SVM payment protection.

What It Tests

Core Functionality

  • ✅ V2 Protocol - Modern x402 server middleware
  • ✅ Payment Protection - Middleware protecting specific routes
  • ✅ Multi-chain Support - EVM and SVM payment acceptance
  • ✅ Facilitator Integration - HTTP communication with facilitator
  • ✅ Extension Support - Bazaar discovery metadata
  • ✅ Settlement Handling - Payment verification and confirmation

Protected Endpoints

  • ✅ GET /protected - Requires EVM payment (USDC on Base Sepolia)
  • ✅ GET /protected-svm - Requires SVM payment (USDC on Solana Devnet)

What It Demonstrates

Server Setup

import (
    x402 "github.com/x402-foundation/x402/go"
    x402http "github.com/x402-foundation/x402/go/http"
    echomw "github.com/x402-foundation/x402/go/http/echo"
    evm "github.com/x402-foundation/x402/go/mechanisms/evm/exact/server"
    svm "github.com/x402-foundation/x402/go/mechanisms/svm/exact/server"
    "github.com/x402-foundation/x402/go/extensions/bazaar"
    "github.com/labstack/echo/v4"
)

// Create Echo instance
e := echo.New()

// Define payment routes
routes := x402http.RoutesConfig{
    "GET /protected": {
        Accepts: x402http.PaymentOptions{
            {
                Scheme:  "exact",
                Network: "eip155:84532",
                PayTo:   evmPayeeAddress,
                Price:   "$0.001",
            },
        },
        Extensions: map[string]interface{}{
            "bazaar": discoveryExtension,
        },
    },
    "GET /protected-svm": {
        Accepts: x402http.PaymentOptions{
            {
                Scheme:  "exact",
                Network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
                PayTo:   svmPayeeAddress,
                Price:   "$0.001",
            },
        },
        Extensions: map[string]interface{}{
            "bazaar": discoveryExtension,
        },
    },
}

// Apply payment middleware
e.Use(echomw.X402Payment(echomw.Config{
    Routes:      routes,
    Facilitator: facilitatorClient,
    Schemes: []echomw.SchemeConfig{
        {Network: "eip155:84532", Server: evm.NewExactEvmScheme()},
        {Network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", Server: svm.NewExactSvmScheme()},
    },
    Timeout: 30 * time.Second,
}))

// Define protected endpoints
e.GET("/protected", func(c echo.Context) error {
    return c.JSON(200, map[string]string{"message": "EVM payment successful!"})
})

e.GET("/protected-svm", func(c echo.Context) error {
    return c.JSON(200, map[string]string{"message": "SVM payment successful!"})
})

Key Concepts Shown

  1. Route Configuration - Map of route → payment requirements
  2. Multi-Chain Services - Different services for EVM vs SVM
  3. Facilitator Client - HTTP client for verification/settlement
  4. Middleware Options - Functional options pattern
  5. Extension Integration - Bazaar discovery declarations
  6. Automatic Initialization - Service initialization on startup

Test Scenarios

This server is tested with:

  • Clients: TypeScript Fetch, Go HTTP
  • Facilitators: TypeScript, Go
  • Payment Types: EVM (Base Sepolia), SVM (Solana Devnet)
  • Protocols: V2 (primary), V1 (via client negotiation)

Request Flow

  1. Client makes initial request (no payment)
  2. Middleware returns 402 with PAYMENT-REQUIRED header
  3. Client creates payment payload
  4. Client retries with PAYMENT-SIGNATURE header
  5. Middleware forwards to facilitator for verification
  6. Middleware returns protected content + PAYMENT-RESPONSE header

Running

# Via e2e test suite
cd e2e
pnpm test --server=echo

# Direct execution
cd e2e/servers/echo
export FACILITATOR_URL="http://localhost:4024"
export EVM_PAYEE_ADDRESS="0x..."
export SVM_PAYEE_ADDRESS="..."
export PORT=4023
./echo

Environment Variables

  • PORT - HTTP server port (default: 4021)
  • FACILITATOR_URL - Facilitator endpoint URL
  • EVM_PAYEE_ADDRESS - Ethereum address to receive payments
  • SVM_PAYEE_ADDRESS - Solana address to receive payments
  • EVM_NETWORK - EVM network (default: eip155:84532)
  • SVM_NETWORK - SVM network (default: solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1)

Response Examples

402 Payment Required

HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <base64-encoded-requirements>
Content-Type: application/json

{
  "error": "Payment required",
  "x402Version": 2,
  "accepts": [...],
  "resource": {...},
  "extensions": {
    "bazaar": {
      "method": "GET",
      "outputExample": {...}
    }
  }
}

200 Success (After Payment)

HTTP/1.1 200 OK
PAYMENT-RESPONSE: <base64-encoded-settlement>
Content-Type: application/json

{
  "message": "Protected endpoint accessed successfully",
  "timestamp": "2024-01-01T00:00:00Z"
}

Dependencies

  • github.com/x402-foundation/x402/go - Core x402
  • github.com/x402-foundation/x402/go/http - HTTP integration
  • github.com/x402-foundation/x402/go/http/echo - Echo middleware
  • github.com/x402-foundation/x402/go/mechanisms/evm - EVM server
  • github.com/x402-foundation/x402/go/mechanisms/svm - SVM server
  • github.com/x402-foundation/x402/go/extensions/bazaar - Discovery extension
  • github.com/labstack/echo/v4 - HTTP framework

Implementation Highlights

Middleware Features

  • Route Matching - Pattern-based route configuration
  • Payment Requirement Building - Automatic 402 response generation
  • Facilitator Communication - HTTP client for verification
  • Settlement Callbacks - Optional handlers for payment events
  • Extension Support - Bazaar metadata in responses
  • Timeout Handling - Configurable facilitator timeouts

Service Integration

  • EVM Server - Base Sepolia USDC
  • SVM Server - Solana Devnet USDC
  • Initialization - Fetches supported kinds from facilitator
  • Price Parsing - Dollar strings → token amounts

Bazaar Extension

  • Method Declaration - GET with output schema
  • Example Output - Response structure preview
  • Schema Definition - JSON Schema for validation