ATPClient is a user-facing client for the ATP Protocol that provides a simple, high-level interface for calling the facilitator (settlement service) directly and making requests to services protected by ATP middleware.
Overview
The ATP client simplifies:- Calling the facilitator (settlement service) for payment operations
- Making requests to ATP-protected endpoints with automatic wallet handling
- Parsing usage data and calculating payments
- Handling encrypted responses from ATP middleware
Installation
Basic Usage
Initialization
Constructor
Parameters
wallet_private_key
- Type:
Optional[str] - Default:
None - Description: Wallet private key for authentication and payments. Can be in JSON array format (e.g.,
"[1,2,3,...]") or base58 string format. If not provided, must be passed per-request.
settlement_service_url
- Type:
Optional[str] - Default:
None(usesATP_SETTLEMENT_URLenvironment variable or"https://facilitator.swarms.world") - Description: Base URL of the settlement service.
settlement_timeout
- Type:
Optional[float] - Default:
None(usesATP_SETTLEMENT_TIMEOUTenvironment variable or300.0) - Description: Timeout for settlement operations in seconds. Settlement operations may take longer due to blockchain confirmation times.
wallet_private_key_header
- Type:
str - Default:
"x-wallet-private-key" - Description: HTTP header name for wallet private key. Should match the middleware configuration.
verbose
- Type:
bool - Default:
False - Description: If
True, enables detailed logging with tracebacks for debugging.
Methods
parse_usage(usage_data: Dict[str, Any]) -> Dict[str, Optional[int]]
Parse usage tokens from various API formats.
This method uses the facilitator to parse usage data from any supported format (OpenAI, Anthropic, Google, etc.) and normalize it to a standard format.
Parameters
usage_data: Usage data in any supported format. Can be the entire response body or just the usage portion.
Returns
Dict with normalized keys:input_tokens(Optional[int]): Number of input/prompt tokensoutput_tokens(Optional[int]): Number of output/completion tokenstotal_tokens(Optional[int]): Total number of tokens
Raises
SettlementServiceError: If the facilitator returns an error.
Example
calculate_payment(usage, input_cost_per_million_usd, output_cost_per_million_usd, payment_token) -> Dict[str, Any]
Calculate payment amounts from usage data.
This method uses the facilitator to calculate payment amounts based on token usage and pricing rates. It does not execute any payment.
Parameters
usage: Usage data containing token counts. Supports same formats asparse_usagemethod.input_cost_per_million_usd: Cost per million input tokens in USD.output_cost_per_million_usd: Cost per million output tokens in USD.payment_token: Token to use for payment. Must be"SOL"or"USDC". Can bePaymentToken.SOLenum or string. Default:PaymentToken.SOL.
Returns
Dict with payment calculation details:status(str):"calculated"or"skipped"(if zero cost)pricing(dict): Pricing information with token counts and costspayment_amounts(dict, optional): Payment amounts in token unitstoken_price_usd(float, optional): Current token price in USD
Raises
SettlementServiceError: If the facilitator returns an error.
Example
settle(usage, input_cost_per_million_usd, output_cost_per_million_usd, recipient_pubkey, payment_token, skip_preflight, commitment, wallet_private_key) -> Dict[str, Any]
Execute a settlement payment on Solana blockchain.
This method uses the facilitator to execute a complete settlement: parse usage, calculate payment, fetch token prices, create and sign transaction, send to Solana, and wait for confirmation.
Parameters
usage: Usage data containing token counts. Supports same formats asparse_usagemethod.input_cost_per_million_usd: Cost per million input tokens in USD.output_cost_per_million_usd: Cost per million output tokens in USD.recipient_pubkey: Solana public key of the recipient wallet (base58 encoded). This wallet receives the net payment after fees.payment_token: Token to use for payment. Currently only"SOL"is supported for automatic settlement. Can bePaymentToken.SOLenum or string. Default:PaymentToken.SOL.skip_preflight: Whether to skip preflight simulation. Default:False.commitment: Solana commitment level for transaction confirmation:"processed": Fastest, but may be rolled back"confirmed": Recommended default, confirmed by cluster"finalized": Slowest, but cannot be rolled back Default:"confirmed".
wallet_private_key: Wallet private key to use for payment. If not provided, uses the client’s defaultwallet_private_key.
Returns
Dict with payment details:status(str):"paid"if successful,"skipped"if zero costtransaction_signature(str, optional): Solana transaction signaturepricing(dict): Complete cost breakdownpayment(dict, optional): Payment details including amounts and splits
Raises
SettlementServiceError: If the facilitator returns an error.ValueError: Ifwallet_private_keyis not provided.
Example
health_check() -> Dict[str, Any]
Check if the facilitator (settlement service) is healthy.
Returns
Dict with health status information, typically including:status(str): Service status (e.g.,"healthy")service(str): Service nameversion(str): Service version
Raises
SettlementServiceError: If the facilitator is unreachable or returns an error.
Example
request(method, url, wallet_private_key, auto_decrypt, **kwargs) -> Dict[str, Any]
Make an HTTP request to an ATP-protected endpoint.
This method automatically:
- Adds wallet authentication headers
- Handles encrypted responses from ATP middleware
- Decrypts response data if encrypted
Parameters
method: HTTP method (GET, POST, PUT, DELETE, etc.).url: Full URL of the endpoint.wallet_private_key: Wallet private key to use. If not provided, uses the client’s defaultwallet_private_key.auto_decrypt: Whether to automatically decrypt encrypted responses. Default:True.**kwargs: Additional arguments to pass to httpx (e.g.,json,data,params,headers, etc.).
Returns
Dict containing the response data. If the response was encrypted, it will be automatically decrypted ifauto_decrypt=True.
Raises
httpx.HTTPError: If the HTTP request fails.ValueError: Ifwallet_private_keyis required but not provided.
Example
post(url, wallet_private_key, auto_decrypt, **kwargs) -> Dict[str, Any]
Make a POST request to an ATP-protected endpoint.
Convenience method for POST requests. See request method for details.
Parameters
url: Full URL of the endpoint.wallet_private_key: Wallet private key to use. If not provided, uses the client’s defaultwallet_private_key.auto_decrypt: Whether to automatically decrypt encrypted responses. Default:True.**kwargs: Additional arguments to pass to httpx (e.g.,json,data,params,headers, etc.).
Returns
Dict containing the response data.Example
get(url, wallet_private_key, auto_decrypt, **kwargs) -> Dict[str, Any]
Make a GET request to an ATP-protected endpoint.
Convenience method for GET requests. See request method for details.
Parameters
url: Full URL of the endpoint.wallet_private_key: Wallet private key to use. If not provided, uses the client’s defaultwallet_private_key.auto_decrypt: Whether to automatically decrypt encrypted responses. Default:True.**kwargs: Additional arguments to pass to httpx (e.g.,params,headers, etc.).
Returns
Dict containing the response data.Example
Usage Examples
Basic Client Setup
Making Requests to ATP-Protected Endpoints
Parsing Usage Data
Calculating Payments
Executing Settlements
Per-Request Wallet Key
Custom Headers
Disabling Auto-Decryption
Error Handling
Response Handling
Successful Payment Response
Failed Payment Response
Error Types
SettlementServiceError
Exception raised when settlement service returns an error.
Attributes:
status_code(Optional[int]): HTTP status code from the settlement service responseerror_detail(Optional[str]): Detailed error message from the serviceerror_type(Optional[str]): Type/category of the errorresponse_body(Optional[Dict[str, Any]]): Full response body if available
to_dict() -> Dict[str, Any]: Convert error to dictionary for API responses
ValueError
Raised when required parameters are missing (e.g., wallet_private_key not provided).
httpx.HTTPError
Raised when HTTP requests fail (network errors, timeouts, etc.).
Best Practices
- Wallet Security: Never log or persist wallet private keys. They should only be used in-memory for transaction signing.
-
Error Handling: Always handle
SettlementServiceErrorexceptions. Checkatp_settlement_statusin responses to handle payment failures. -
Timeout Configuration: Increase
settlement_timeoutif you experience timeout errors even when payments succeed. Blockchain confirmation can take 30-60 seconds or more. -
Verbose Logging: Enable
verbose=Trueduring development for detailed debugging information. -
Response Validation: Always check
atp_settlement_statusbefore accessing agent output. Failed payments result in encrypted responses. -
Per-Request Keys: Use per-request
wallet_private_keyparameter for multi-user applications instead of storing keys in client instances. -
Health Checks: Use
health_check()to verify settlement service availability before making requests.
Troubleshooting
Missing Wallet Key Error
Problem:ValueError: wallet_private_key must be provided
Solution: Provide wallet private key in client initialization or per-request:
Encrypted Response Not Decrypting
Problem: Response remains encrypted even after successful payment. Solution: Checkatp_settlement_status. If status is not "paid", payment may have failed. Check atp_settlement for error details.
Timeout Errors
Problem: Requests timeout even when payments succeed. Solution: Increasesettlement_timeout:
Connection Errors
Problem: Cannot connect to settlement service. Solution:- Verify
settlement_service_urlis correct - Check network connectivity
- Use
health_check()to verify service availability
API Reference
Class: ATPClient
Attributes
wallet_private_key: Wallet private key for authentication and paymentssettlement_service_url: Base URL of the settlement servicesettlement_timeout: Timeout for settlement operations in secondswallet_private_key_header: HTTP header name for wallet keysettlement_client: InternalSettlementServiceClientinstanceencryptor: InternalResponseEncryptorinstance