atp-protocol 1.2.0__py3-none-any.whl → 1.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ Metadata-Version: 2.3
2
+ Name: atp-protocol
3
+ Version: 1.4.0
4
+ Summary: ATP Protocol - Agentic Trade Protocol. The easiest way to enable agent-to-agent payments powered by Solana.
5
+ License: MIT
6
+ Keywords: atp,atp-protocol,solana,blockchain,cryptocurrency,payment-gated,agent-to-agent,agent payments,agent execution,payment settlement,solana payments,usdc,sol,fastapi,agent api,payment gateway,settlement service,agent marketplace,decentralized payments,web3,crypto payments,agent infrastructure,payment middleware,automated settlement
7
+ Author: The Swarm Corporation
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
18
+ Classifier: Topic :: Office/Business :: Financial
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Dist: cryptography
21
+ Requires-Dist: fastapi
22
+ Requires-Dist: httpx
23
+ Requires-Dist: loguru
24
+ Requires-Dist: pydantic
25
+ Requires-Dist: python-dotenv
26
+ Requires-Dist: setuptools
27
+ Requires-Dist: starlette
28
+ Requires-Dist: swarms
29
+ Project-URL: Documentation, https://github.com/The-Swarm-Corporation/ATP-Protocol
30
+ Project-URL: Homepage, https://github.com/The-Swarm-Corporation/ATP-Protocol
31
+ Project-URL: Repository, https://github.com/The-Swarm-Corporation/ATP-Protocol
32
+ Description-Content-Type: text/markdown
33
+
34
+ # ATP: Agent Trade Protocol
35
+
36
+ > The premier agent-to-agent payment protocol and foundational framework to empower the agent economy.
37
+
38
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
39
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
40
+ [![Documentation](https://img.shields.io/badge/docs-swarms.ai-blue)](https://docs.swarms.ai/docs/atp/overview)
41
+
42
+ ## Overview
43
+
44
+ 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.
45
+
46
+ ### Key Features
47
+
48
+ - **Security**: Response encryption ensures users cannot access output until payment is confirmed on-chain
49
+ - **Automation**: Zero-configuration payment processing through middleware integration
50
+ - **Decentralization**: All payments executed on Solana blockchain with full transaction visibility
51
+ - **Format Flexibility**: Supports multiple usage formats (OpenAI, Anthropic, Google, etc.) automatically
52
+ - **Transparency**: Automatic payment splitting between treasury and recipient wallets
53
+
54
+ ## Architecture
55
+
56
+ ATP Protocol operates through three main components:
57
+
58
+ 1. **Settlement Service (Facilitator)**: Centralized service handling all settlement logic, usage parsing, payment calculation, and blockchain transaction execution
59
+ 2. **Middleware**: FastAPI middleware that intercepts API responses, extracts usage data, encrypts responses, executes payments, and decrypts responses only after payment confirmation
60
+ 3. **Client**: User-facing client that simplifies making requests to ATP-protected endpoints and interacting with the settlement service
61
+
62
+ ### Request Flow
63
+
64
+ ```mermaid
65
+ sequenceDiagram
66
+ participant Client
67
+ participant Server
68
+ participant Middleware
69
+ participant SettlementService
70
+ participant Solana
71
+
72
+ Client->>Server: POST /v1/chat<br/>(with wallet key)
73
+ Server->>Server: Process request
74
+ Server->>Middleware: Response with usage data
75
+ Middleware->>Middleware: Encrypt response
76
+ Middleware->>SettlementService: Parse usage & calculate payment
77
+ SettlementService->>SettlementService: Calculate payment amount
78
+ SettlementService->>Solana: Create & sign transaction
79
+ Solana-->>SettlementService: Transaction confirmed
80
+ SettlementService-->>Middleware: Payment confirmed (tx signature)
81
+ Middleware->>Middleware: Decrypt response
82
+ Middleware->>Client: Return decrypted response<br/>(with settlement details)
83
+ ```
84
+
85
+ ## Quick Start
86
+
87
+ ### Installation
88
+
89
+ ```bash
90
+ pip install atp-protocol
91
+ ```
92
+
93
+ ### Server Setup (5 minutes)
94
+
95
+ Add ATP middleware to your FastAPI server:
96
+
97
+ ```python
98
+ from fastapi import FastAPI
99
+ from fastapi.responses import JSONResponse
100
+ from atp.middleware import ATPSettlementMiddleware
101
+ from atp.schemas import PaymentToken
102
+
103
+ app = FastAPI(title="My ATP-Protected API")
104
+
105
+ # Add ATP Settlement Middleware
106
+ app.add_middleware(
107
+ ATPSettlementMiddleware,
108
+ allowed_endpoints=["/v1/chat", "/v1/completions"],
109
+ input_cost_per_million_usd=10.0, # $10 per million input tokens
110
+ output_cost_per_million_usd=30.0, # $30 per million output tokens
111
+ recipient_pubkey="YourSolanaWalletPublicKeyHere", # Your wallet
112
+ payment_token=PaymentToken.SOL, # SOL or USDC
113
+ wallet_private_key_header="x-wallet-private-key",
114
+ require_wallet=True,
115
+ )
116
+
117
+ @app.post("/v1/chat")
118
+ async def chat(request: dict):
119
+ """Agent endpoint with automatic payment processing."""
120
+ message = request.get("message", "")
121
+
122
+ # Agent logic implementation
123
+ response_text = "Agent response here"
124
+
125
+ # Return response with usage data
126
+ # Middleware handles payment processing automatically
127
+ return JSONResponse(content={
128
+ "response": response_text,
129
+ "usage": {
130
+ "input_tokens": 100,
131
+ "output_tokens": 50,
132
+ "total_tokens": 150
133
+ }
134
+ })
135
+ ```
136
+
137
+ ### Client Usage
138
+
139
+ ```python
140
+ from atp.client import ATPClient
141
+
142
+ # Initialize client with wallet
143
+ client = ATPClient(
144
+ wallet_private_key="[1,2,3,...]", # Your wallet private key
145
+ settlement_service_url="https://facilitator.swarms.world"
146
+ )
147
+
148
+ # Make request with automatic payment processing
149
+ response = await client.post(
150
+ url="https://api.example.com/v1/chat",
151
+ json={"message": "Hello!"}
152
+ )
153
+
154
+ print(response["response"]) # Agent output
155
+ print(response["atp_settlement"]) # Payment details
156
+ ```
157
+
158
+ ## Examples
159
+
160
+ Below is a comprehensive table of example integrations and usage:
161
+
162
+ ### Framework Integrations
163
+
164
+ | Category | Example Link | Description |
165
+ |---------------------------|---------------------------------------------------------|----------------------------------------|
166
+ | **Framework Integration** | [Swarms Framework](./examples/tutorials/swarms/) | Enterprise multi-agent orchestration |
167
+ | **Framework Integration** | [LangChain](./examples/tutorials/langchain/) | Popular Python LLM framework |
168
+ | **Framework Integration** | [AutoGen](./examples/tutorials/autogen/) | Microsoft's multi-agent framework |
169
+ | **Framework Integration** | [CrewAI](./examples/tutorials/crewai/) | Multi-agent orchestration |
170
+ | **Framework Integration** | [Anthropic](./examples/tutorials/anthropic/) | Claude API integration |
171
+
172
+ ### Client & Server Example Scripts
173
+
174
+ | Category | Example Link | Description |
175
+ |----------------------|---------------------------------------------------------------------|--------------------------------------------|
176
+ | **Client Example** | [Health Check](./examples/client/example_health_check.py) | Check settlement service status |
177
+ | **Client Example** | [Parse Usage](./examples/client/example_parse_usage.py) | Parse usage from various formats |
178
+ | **Client Example** | [Calculate Payment](./examples/client/example_calculate_payment.py) | Calculate payment without executing |
179
+ | **Client Example** | [Execute Settlement](./examples/client/example_settle.py) | Direct settlement execution |
180
+ | **Client Example** | [Make Request](./examples/client/example_request.py) | Request ATP-protected endpoints |
181
+ | **Server Example** | [Basic Example](./examples/server/example.py) | Simple middleware setup |
182
+ | **Server Example** | [Full Flow](./examples/server/full_flow_example.py) | Complete payment flow |
183
+ | **Server Example** | [Settlement Service](./examples/server/settlement_service_example.py) | Direct service usage |
184
+
185
+ See [examples/README.md](./examples/README.md) for complete documentation.
186
+
187
+
188
+ ## Security Features
189
+
190
+ | Feature | Description |
191
+ |------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
192
+ | **Response Encryption** | Agent responses are **encrypted before payment verification**, ensuring users cannot see output until payment is confirmed on-chain. |
193
+ | **Payment Verification** | Responses are only decrypted after successful blockchain transaction confirmation (`status="paid"` with valid transaction signature). |
194
+ | **Error Handling** | Failed payments result in encrypted responses with error details, preventing unauthorized access to agent output. |
195
+
196
+
197
+ ## Payment Structure
198
+
199
+ Payments are automatically split between:
200
+
201
+ - **Treasury**: Receives processing fee (default 5%, configured on settlement service)
202
+ - **Recipient**: Receives remainder (95% by default) - your wallet specified via `recipient_pubkey`
203
+
204
+ ### Supported Payment Tokens
205
+
206
+ - **SOL** (Solana native token)
207
+ - **USDC** (USD Coin on Solana)
208
+
209
+ ## Usage Data Formats
210
+
211
+ The middleware automatically supports multiple usage formats:
212
+
213
+ ### OpenAI Format
214
+
215
+ ```json
216
+ {
217
+ "usage": {
218
+ "prompt_tokens": 100,
219
+ "completion_tokens": 50,
220
+ "total_tokens": 150
221
+ }
222
+ }
223
+ ```
224
+
225
+ ### Anthropic Format
226
+
227
+ ```json
228
+ {
229
+ "usage": {
230
+ "input_tokens": 100,
231
+ "output_tokens": 50
232
+ }
233
+ }
234
+ ```
235
+
236
+ ### Google/Gemini Format
237
+
238
+ ```json
239
+ {
240
+ "usageMetadata": {
241
+ "promptTokenCount": 100,
242
+ "candidatesTokenCount": 50,
243
+ "totalTokenCount": 150
244
+ }
245
+ }
246
+ ```
247
+
248
+ The settlement service automatically detects and parses these formats, so you can use any format your agent API returns.
249
+
250
+ ## Configuration
251
+
252
+ ### Environment Variables
253
+
254
+ ```bash
255
+ # Settlement Service
256
+ ATP_SETTLEMENT_URL="https://facilitator.swarms.world" # Default
257
+ ATP_SETTLEMENT_TIMEOUT=300.0 # 5 minutes (default)
258
+
259
+ # Encryption (optional - generates new key if not set)
260
+ ATP_ENCRYPTION_KEY="base64-encoded-fernet-key"
261
+ ```
262
+
263
+ ### Middleware Configuration
264
+
265
+ ```python
266
+ app.add_middleware(
267
+ ATPSettlementMiddleware,
268
+ allowed_endpoints=["/v1/chat"], # Endpoints to protect
269
+ input_cost_per_million_usd=10.0, # Pricing
270
+ output_cost_per_million_usd=30.0,
271
+ recipient_pubkey="YourWalletPublicKey", # Required
272
+ payment_token=PaymentToken.SOL, # SOL or USDC
273
+ wallet_private_key_header="x-wallet-private-key",
274
+ require_wallet=True, # Require wallet for payment
275
+ settlement_service_url="https://facilitator.swarms.world",
276
+ settlement_timeout=300.0,
277
+ fail_on_settlement_error=False, # Graceful error handling
278
+ )
279
+ ```
280
+
281
+ ## API Reference
282
+
283
+ ### Middleware
284
+
285
+ The `ATPSettlementMiddleware` class provides automatic payment processing for FastAPI endpoints.
286
+
287
+ **Key Features:**
288
+
289
+ - Automatic usage parsing from multiple formats
290
+ - Response encryption before payment
291
+ - Payment execution via settlement service
292
+ - Response decryption after payment confirmation
293
+
294
+ See [Middleware Documentation](./atp/middleware.py) for complete API reference.
295
+
296
+ ### Client
297
+
298
+ The `ATPClient` class provides a simple interface for:
299
+
300
+ - Making requests to ATP-protected endpoints
301
+ - Interacting with the settlement service directly
302
+ - Parsing usage data
303
+ - Calculating payments
304
+ - Executing settlements
305
+
306
+ See [Client Documentation](./atp/client.py) for complete API reference.
307
+
308
+ ### Settlement Service
309
+
310
+ The settlement service (facilitator) handles:
311
+
312
+ - Usage parsing from various formats
313
+ - Payment calculation
314
+ - Blockchain transaction creation and execution
315
+ - Transaction confirmation
316
+
317
+ See [Settlement Service Documentation](https://docs.swarms.ai/docs/atp/facilitator) for complete API reference.
318
+
319
+
320
+ ## Development
321
+
322
+ ### Requirements
323
+
324
+ - Python 3.10+
325
+ - FastAPI (for middleware)
326
+ - Solana wallet (for payments)
327
+
328
+ ### Installation from Source
329
+
330
+ ```bash
331
+ git clone https://github.com/The-Swarm-Corporation/ATP-Protocol.git
332
+ cd ATP-Protocol
333
+ pip install -e .
334
+ ```
335
+
336
+ ### Running Tests
337
+
338
+ ```bash
339
+ pytest tests/
340
+ ```
341
+
342
+ ### Code Quality
343
+
344
+ ```bash
345
+ # Format code
346
+ black .
347
+
348
+ # Lint code
349
+ ruff check .
350
+ ```
351
+
352
+
353
+ ## Error Handling
354
+
355
+ ### Missing Wallet Key
356
+
357
+ If wallet private key is missing and `require_wallet=True`:
358
+
359
+ ```json
360
+ {
361
+ "detail": "Missing wallet private key in header: x-wallet-private-key"
362
+ }
363
+ ```
364
+
365
+ Status: `401 Unauthorized`
366
+
367
+ ### Payment Failure
368
+
369
+ If payment fails and `fail_on_settlement_error=False` (default):
370
+
371
+ ```json
372
+ {
373
+ "response": "encrypted_data_here",
374
+ "response_encrypted": true,
375
+ "atp_settlement": {
376
+ "error": "Settlement failed",
377
+ "detail": "Insufficient funds",
378
+ "status_code": 400
379
+ },
380
+ "atp_settlement_status": "failed",
381
+ "atp_message": "Agent response is encrypted. Payment required to decrypt."
382
+ }
383
+ ```
384
+
385
+ The response remains encrypted until payment succeeds.
386
+
387
+ ## Best Practices
388
+
389
+ 1. **Wallet Security**: Never log or persist wallet private keys. Use them only in-memory for transaction signing.
390
+
391
+ 2. **Error Handling**: Use `fail_on_settlement_error=False` for graceful degradation. Check `atp_settlement_status` in responses to handle payment failures appropriately.
392
+
393
+ 3. **Timeout Configuration**: Increase `settlement_timeout` if you experience timeout errors. Blockchain confirmation can take time depending on network conditions.
394
+
395
+ 4. **Usage Data**: Always include accurate token counts in your responses. Middleware skips settlement if usage data cannot be parsed.
396
+
397
+ 5. **Testing**: Use testnet wallets and small amounts for testing. Verify transactions on Solana explorer before production deployment.
398
+
399
+ 6. **Monitoring**: Monitor `atp_settlement_status` in responses to track payment success rates and identify potential issues.
400
+
401
+ ## Resources
402
+
403
+ | Resource | Description |
404
+ |-----------------------------------|------------------------------------|
405
+ | [Full Documentation](https://docs.swarms.ai/docs/atp/overview) | Complete API documentation |
406
+ | [Settlement Service API](https://docs.swarms.ai/docs/atp/facilitator) | Facilitator API reference |
407
+ | [Middleware Reference](https://docs.swarms.ai/docs/atp/middleware) | Middleware configuration |
408
+ | [Client Reference](https://docs.swarms.ai/docs/atp/client) | Client API reference |
409
+ | [ATP Vision](https://docs.swarms.ai/docs/atp/vision) | Protocol vision and roadmap |
410
+
411
+
412
+ ## Contributing
413
+
414
+ Contributions are welcome. Please read our contributing guidelines and submit pull requests for review.
415
+
416
+ ## License
417
+
418
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
419
+
420
+ ## Acknowledgments
421
+
422
+ Built by [The Swarm Corporation](https://swarms.ai) to enable agent-to-agent commerce on the blockchain.
423
+
424
+ ---
425
+
426
+ For additional information, see the [examples directory](./examples/) or the [complete documentation](https://docs.swarms.ai/docs/atp/overview).
427
+
@@ -0,0 +1,11 @@
1
+ atp/__init__.py,sha256=xCYA1cb5xw9IxqFsB1fC7jXBE48bHgKBq4ZhyW9AFyY,459
2
+ atp/client.py,sha256=GUZZ81PaJMia7mK_SS3uzU3qCpg0ChoLVYmQIRrfxQ8,24510
3
+ atp/config.py,sha256=tY_S8aXrTbZJ4WIRQIXhIiXiRjeYT6_5Jh47QwZ1gnw,3013
4
+ atp/encryption.py,sha256=kgyhjf8qGq3oZjDIxGHzOlc5KOLPTi7nv0RApPZGk7o,5341
5
+ atp/middleware.py,sha256=d3Sxj66qMr2AX6hxZNFHaiqpdyXafEpf1McWOJVaklo,29546
6
+ atp/schemas.py,sha256=29VtWKxtwlllAUOx2hoSEESpVWoKANdybOoTiTbFhnc,12344
7
+ atp/settlement_client.py,sha256=7e_271Bx1ZT2YzZH0HjAOx1krDXgPhMWVakRKsMMS3k,31395
8
+ atp_protocol-1.4.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
9
+ atp_protocol-1.4.0.dist-info/METADATA,sha256=rLnBQhoFlqGx9lxHDJXJm6zDDdIGVlXx0Ds4mpMYX24,15887
10
+ atp_protocol-1.4.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
11
+ atp_protocol-1.4.0.dist-info/RECORD,,