The premier agent-to-agent payment protocol and foundational framework to empower the agent economy.
ATP (Agent Trade Protocol) is the premier agent-to-agent payment protocol that will be the foundational framework to empower the agent economy. Designed to overcome x402's issues and make agent-to-agent payments dynamic and simple, ATP enables automatic payment processing for agent services on the Solana blockchain. The protocol provides a middleware layer that automatically deducts payments from user wallets based on token usage, ensuring secure and transparent transactions.
- Security: Response encryption ensures users cannot access output until payment is confirmed on-chain
- Automation: Zero-configuration payment processing through middleware integration
- Decentralization: All payments executed on Solana blockchain with full transaction visibility
- Format Flexibility: Supports multiple usage formats (OpenAI, Anthropic, Google, etc.) automatically
- Transparency: Automatic payment splitting between treasury and recipient wallets
ATP Protocol operates through three main components:
- Settlement Service (Facilitator): Centralized service handling all settlement logic, usage parsing, payment calculation, and blockchain transaction execution
- Middleware: FastAPI middleware that intercepts API responses, extracts usage data, encrypts responses, executes payments, and decrypts responses only after payment confirmation
- Client: User-facing client that simplifies making requests to ATP-protected endpoints and interacting with the settlement service
sequenceDiagram
participant Client
participant Server
participant Middleware
participant SettlementService
participant Solana
Client->>Server: POST /v1/chat<br/>(with wallet key)
Server->>Server: Process request
Server->>Middleware: Response with usage data
Middleware->>Middleware: Encrypt response
Middleware->>SettlementService: Parse usage & calculate payment
SettlementService->>SettlementService: Calculate payment amount
SettlementService->>Solana: Create & sign transaction
Solana-->>SettlementService: Transaction confirmed
SettlementService-->>Middleware: Payment confirmed (tx signature)
Middleware->>Middleware: Decrypt response
Middleware->>Client: Return decrypted response<br/>(with settlement details)
pip install atp-protocolAdd ATP middleware to your FastAPI server:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from atp.middleware import ATPSettlementMiddleware
from atp.schemas import PaymentToken
app = FastAPI(title="My ATP-Protected API")
# Add ATP Settlement Middleware
app.add_middleware(
ATPSettlementMiddleware,
allowed_endpoints=["/v1/chat", "/v1/completions"],
input_cost_per_million_usd=10.0, # $10 per million input tokens
output_cost_per_million_usd=30.0, # $30 per million output tokens
recipient_pubkey="YourSolanaWalletPublicKeyHere", # Your wallet
payment_token=PaymentToken.SOL, # SOL or USDC
wallet_private_key_header="x-wallet-private-key",
require_wallet=True,
)
@app.post("/v1/chat")
async def chat(request: dict):
"""Agent endpoint with automatic payment processing."""
message = request.get("message", "")
# Agent logic implementation
response_text = "Agent response here"
# Return response with usage data
# Middleware handles payment processing automatically
return JSONResponse(content={
"response": response_text,
"usage": {
"input_tokens": 100,
"output_tokens": 50,
"total_tokens": 150
}
})from atp.client import ATPClient
# Initialize client with wallet
client = ATPClient(
wallet_private_key="[1,2,3,...]", # Your wallet private key
settlement_service_url="https://facilitator.swarms.world"
)
# Make request with automatic payment processing
response = await client.post(
url="https://api.example.com/v1/chat",
json={"message": "Hello!"}
)
print(response["response"]) # Agent output
print(response["atp_settlement"]) # Payment detailsBelow is a comprehensive table of example integrations and usage:
| Category | Example Link | Description |
|---|---|---|
| Framework Integration | Swarms Framework | Enterprise multi-agent orchestration |
| Framework Integration | LangChain | Popular Python LLM framework |
| Framework Integration | AutoGen | Microsoft's multi-agent framework |
| Framework Integration | CrewAI | Multi-agent orchestration |
| Framework Integration | Anthropic | Claude API integration |
| Category | Example Link | Description |
|---|---|---|
| Client Example | Health Check | Check settlement service status |
| Client Example | Parse Usage | Parse usage from various formats |
| Client Example | Calculate Payment | Calculate payment without executing |
| Client Example | Execute Settlement | Direct settlement execution |
| Client Example | Make Request | Request ATP-protected endpoints |
| Server Example | Basic Example | Simple middleware setup |
| Server Example | Full Flow | Complete payment flow |
| Server Example | Settlement Service | Direct service usage |
See examples/README.md for complete documentation.
| Feature | Description |
|---|---|
| Response Encryption | Agent responses are encrypted before payment verification, ensuring users cannot see output until payment is confirmed on-chain. |
| Payment Verification | Responses are only decrypted after successful blockchain transaction confirmation (status="paid" with valid transaction signature). |
| Error Handling | Failed payments result in encrypted responses with error details, preventing unauthorized access to agent output. |
Payments are automatically split between:
- Treasury: Receives processing fee (default 5%, configured on settlement service)
- Recipient: Receives remainder (95% by default) - your wallet specified via
recipient_pubkey
- SOL (Solana native token)
- USDC (USD Coin on Solana)
The middleware automatically supports multiple usage formats:
{
"usage": {
"prompt_tokens": 100,
"completion_tokens": 50,
"total_tokens": 150
}
}{
"usage": {
"input_tokens": 100,
"output_tokens": 50
}
}{
"usageMetadata": {
"promptTokenCount": 100,
"candidatesTokenCount": 50,
"totalTokenCount": 150
}
}The settlement service automatically detects and parses these formats, so you can use any format your agent API returns.
# Settlement Service
ATP_SETTLEMENT_URL="https://facilitator.swarms.world" # Default
ATP_SETTLEMENT_TIMEOUT=300.0 # 5 minutes (default)
# Encryption (optional - generates new key if not set)
ATP_ENCRYPTION_KEY="base64-encoded-fernet-key"app.add_middleware(
ATPSettlementMiddleware,
allowed_endpoints=["/v1/chat"], # Endpoints to protect
input_cost_per_million_usd=10.0, # Pricing
output_cost_per_million_usd=30.0,
recipient_pubkey="YourWalletPublicKey", # Required
payment_token=PaymentToken.SOL, # SOL or USDC
wallet_private_key_header="x-wallet-private-key",
require_wallet=True, # Require wallet for payment
settlement_service_url="https://facilitator.swarms.world",
settlement_timeout=300.0,
fail_on_settlement_error=False, # Graceful error handling
)The ATPSettlementMiddleware class provides automatic payment processing for FastAPI endpoints.
Key Features:
- Automatic usage parsing from multiple formats
- Response encryption before payment
- Payment execution via settlement service
- Response decryption after payment confirmation
See Middleware Documentation for complete API reference.
The ATPClient class provides a simple interface for:
- Making requests to ATP-protected endpoints
- Interacting with the settlement service directly
- Parsing usage data
- Calculating payments
- Executing settlements
See Client Documentation for complete API reference.
The settlement service (facilitator) handles:
- Usage parsing from various formats
- Payment calculation
- Blockchain transaction creation and execution
- Transaction confirmation
See Settlement Service Documentation for complete API reference.
If wallet private key is missing and require_wallet=True:
{
"detail": "Missing wallet private key in header: x-wallet-private-key"
}Status: 401 Unauthorized
If payment fails and fail_on_settlement_error=False (default):
{
"response": "encrypted_data_here",
"response_encrypted": true,
"atp_settlement": {
"error": "Settlement failed",
"detail": "Insufficient funds",
"status_code": 400
},
"atp_settlement_status": "failed",
"atp_message": "Agent response is encrypted. Payment required to decrypt."
}The response remains encrypted until payment succeeds.
-
Wallet Security: Never log or persist wallet private keys. Use them only in-memory for transaction signing.
-
Error Handling: Use
fail_on_settlement_error=Falsefor graceful degradation. Checkatp_settlement_statusin responses to handle payment failures appropriately. -
Timeout Configuration: Increase
settlement_timeoutif you experience timeout errors. Blockchain confirmation can take time depending on network conditions. -
Usage Data: Always include accurate token counts in your responses. Middleware skips settlement if usage data cannot be parsed.
-
Testing: Use testnet wallets and small amounts for testing. Verify transactions on Solana explorer before production deployment.
-
Monitoring: Monitor
atp_settlement_statusin responses to track payment success rates and identify potential issues.
| Resource | Description |
|---|---|
| Full Documentation | Complete API documentation |
| Settlement Service API | Facilitator API reference |
| Middleware Reference | Middleware configuration |
| Client Reference | Client API reference |
| ATP Vision | Protocol vision and roadmap |
Contributions are welcome. Please read our contributing guidelines and submit pull requests for review.
- Python 3.10+
- FastAPI (for middleware)
- Solana wallet (for payments)
git clone https://github.com/The-Swarm-Corporation/ATP-Protocol.git
cd ATP-Protocol
pip install -e .pytest tests/# Format code
black .
# Lint code
ruff check .This project is licensed under the MIT License. See the LICENSE file for details.
If you use ATP (Agent Trade Protocol) in your research or software, please cite The Swarm Corporation:
@software{atp_protocol,
title = {ATP: Agent Trade Protocol},
author = {{The Swarm Corporation}},
year = {2025},
url = {https://github.com/The-Swarm-Corporation/ATP-Protocol},
note = {Agent-to-agent payment protocol for the agent economy}
}The Swarm Corporation. ATP: Agent Trade Protocol. https://github.com/The-Swarm-Corporation/ATP-Protocol
Built by The Swarm Corporation to enable agent-to-agent commerce on the blockchain.
For additional information, see the examples directory or the complete documentation.