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.
@@ -1,401 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: atp-protocol
3
- Version: 1.2.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: fastapi
21
- Requires-Dist: httpx
22
- Requires-Dist: loguru
23
- Requires-Dist: pydantic
24
- Requires-Dist: python-dotenv
25
- Requires-Dist: setuptools
26
- Requires-Dist: starlette
27
- Requires-Dist: swarms
28
- Project-URL: Documentation, https://github.com/The-Swarm-Corporation/ATP-Protocol
29
- Project-URL: Homepage, https://github.com/The-Swarm-Corporation/ATP-Protocol
30
- Project-URL: Repository, https://github.com/The-Swarm-Corporation/ATP-Protocol
31
- Description-Content-Type: text/markdown
32
-
33
- # ATP-Protocol
34
-
35
- ATP Protocol is a **payment-gated agent execution API** that makes **agent-to-agent payments** and “pay to unlock results” easy on **Solana**, with a simple client integration (two endpoints + a Solana payment).
36
-
37
- At a high level:
38
-
39
- - An agent (or any client) requests work from another agent via the ATP Gateway.
40
- - The Gateway executes the upstream agent immediately, but **returns a 402 challenge** instead of the result.
41
- - The requester pays **once** to the agent treasury (in **SOL** or **USDC**).
42
- - After settlement, the Gateway releases the stored agent output.
43
-
44
- The ATP Gateway exposes:
45
-
46
- - `POST /v1/agent/trade`: execute + return payment challenge (402)
47
- - `POST /v1/agent/settle`: facilitator signs+submits payment (using provided private key) + releases output
48
- - optional helper endpoints for token price/payment info
49
-
50
- ---
51
-
52
- ## One simple end-to-end example (trade → settle)
53
-
54
- Run the server, then run:
55
-
56
- ```bash
57
- export ATP_BASE_URL="http://localhost:8000"
58
- export ATP_USER_WALLET="<YOUR_SOLANA_PUBKEY>"
59
- export ATP_PRIVATE_KEY="<YOUR_PRIVATE_KEY_STRING>"
60
-
61
- # Safety switch: settlement will broadcast a real SOL transaction
62
- export ATP_ALLOW_SPEND="true"
63
-
64
- python full_flow_example.py
65
- ```
66
-
67
- Notes:
68
- - The first call (`/v1/agent/trade`) returns **HTTP 402** with a `job_id` and the payment challenge JSON.
69
- - The second call (`/v1/agent/settle`) signs+sends the SOL payment in-memory and returns **HTTP 200** with `agent_output`.
70
-
71
- Server-side pricing (optional):
72
- - Set `INPUT_COST_PER_MILLION_USD` and/or `OUTPUT_COST_PER_MILLION_USD` on the server to compute `usd_cost` from `usage` token counts.
73
- - If not set (or if token counts are missing), the gateway falls back to upstream `usage.total_cost` (and then a small default).
74
-
75
- ---
76
-
77
- ## Conceptual purpose
78
-
79
- ATP exists to solve a common agentic workflow problem:
80
-
81
- - Agents can call other agents (“agent tools”, “specialist agents”, “market-data agents”), but **payments and settlement** are usually ad-hoc.
82
- - ATP standardizes **a simple handshake**: *execute → challenge → pay → settle → release*.
83
- - Because the settlement happens on Solana, it’s **cheap**, **fast**, and can be done by **another agent** programmatically (no human-in-the-loop required).
84
-
85
- Key design goals:
86
-
87
- - **Agent-to-agent friendly**: the “client” can be another agent, a bot, or a backend service.
88
- - **Simple integration**: clients can settle by providing a private key string for a single request (used in-memory only).
89
- - **Token flexibility**: support SOL today, and USDC as a stable-priced option.
90
-
91
- ---
92
-
93
- ## Core actors
94
-
95
- - **Requester (Agent A)**: wants work done (submits the task, later pays and settles).
96
- - **ATP Gateway**: runs the upstream agent, produces the payment challenge, holds the result temporarily.
97
- - **Upstream Agent Service (Swarms API)**: executes the requested agent workload.
98
- - **Solana**: settlement rail (payment transaction + signature).
99
- - **Facilitator**: signs+submits the payment transaction during settlement.
100
- - **Agent Treasury**: receives the payment (minus the fee split logic described below).
101
- - **Swarms Treasury**: receives the **5% settlement fee**.
102
- - **Temporary lockbox**: the gateway holds the output until paid (expires after a TTL).
103
-
104
- ---
105
-
106
- ## How it works (step-by-step)
107
-
108
- ### 1) Request a trade (create challenge)
109
-
110
- The requester calls:
111
-
112
- - `POST /v1/agent/trade`
113
-
114
- with:
115
-
116
- - `agent_config`: full agent spec (see `atp/schemas.py:AgentSpec`)
117
- - `task`: what to do
118
- - `user_wallet`: payer public key (used during verification)
119
- - `payment_token`: `SOL` or `USDC`
120
- - optional `history` / `img` / `imgs`
121
-
122
- ### 2) Gateway executes the agent immediately
123
-
124
- The Gateway forwards the request to the upstream agent service (`SWARMS_API_URL`) and waits for completion.
125
-
126
- ### 3) Gateway computes the price + fee split
127
-
128
- The Gateway:
129
-
130
- - reads the USD cost from upstream usage (`usage.total_cost`, with a fallback),
131
- - fetches token/USD price (SOL via CoinGecko, USDC treated as $1),
132
- - computes the **total payment** and the **5% settlement fee**.
133
-
134
- Important: the fee is **taken from the total** (not added on top):
135
- \[
136
- \text{total} = \frac{\text{usd\_cost}}{\text{token\_price}}
137
- \quad
138
- \text{fee} = 0.05 \cdot \text{total}
139
- \quad
140
- \text{agent\_receives} = \text{total} - \text{fee}
141
- \]
142
-
143
- ### 4) Gateway stores the result (locked) with a TTL
144
-
145
- The agent output is held in a temporary lockbox under a generated `job_id`.
146
-
147
- If the requester never pays, the job expires automatically (default TTL: 10 minutes).
148
-
149
- ### 5) Gateway returns a 402 Payment Required challenge
150
-
151
- Instead of returning the agent output, the Gateway returns **HTTP 402** with a JSON payload containing:
152
-
153
- - `job_id`
154
- - `recipient` (the agent treasury pubkey)
155
- - amount to pay (in lamports or USDC micro-units)
156
- - a memo format like `ATP:{job_id}`
157
- - a fee breakdown (5% to Swarms treasury)
158
- - TTL info
159
-
160
- ### 6) Requester pays on Solana
161
-
162
- The requester provides a private key string during settlement; the gateway signs+sends the SOL payment transaction in-memory.
163
-
164
- ### 7) Settle to unlock
165
-
166
- The requester calls:
167
-
168
- - `POST /v1/agent/settle`
169
-
170
- with:
171
-
172
- - `job_id`
173
- - `private_key`
174
-
175
- ### 8) Gateway verifies and releases the output
176
-
177
- The Gateway:
178
-
179
- - looks up the pending job by `job_id`,
180
- - signs+sends the on-chain payment transaction and verifies it succeeded,
181
- - releases the output exactly once (prevents double-settlement),
182
- - returns the stored `agent_output` and settlement details.
183
-
184
- ---
185
-
186
- ## Diagrams
187
-
188
- ### Architecture overview
189
-
190
- ```mermaid
191
- flowchart LR
192
- A["Requester<br/>(Agent A / App / Bot)"] -->|POST /v1/agent/trade| G["ATP Gateway<br/>FastAPI"]
193
- G -->|Execute task| S["Swarms Agent API<br/>Upstream execution"]
194
- S -->|Result + usage cost| G
195
-
196
- A -->|POST /v1/agent/settle<br/>(job_id, private_key)| G
197
- G <-->|Send payment tx| C["Solana<br/>(SOL / USDC)"]
198
- G -->|Verify signature status| C
199
- G -->|Unlocked agent output| A
200
-
201
- C --> T1[Agent Treasury]
202
- C --> T2["Swarms Treasury<br/>(5% fee)"]
203
- ```
204
-
205
- ### End-to-end sequence (challenge → payment → settlement)
206
-
207
- ```mermaid
208
- sequenceDiagram
209
- autonumber
210
- participant A as Requester (Agent A)
211
- participant G as ATP Gateway
212
- participant S as Swarms Agent API
213
- participant C as Solana
214
-
215
- A->>G: POST /v1/agent/trade (agent_config, task, wallet, token)
216
- G->>S: Execute agent task
217
- S-->>G: outputs + usage.total_cost
218
- G->>G: Compute total + 5% fee split<br/>(fetch token price)
219
- G->>G: Lock result (job_id, ttl)
220
- G-->>A: 402 Payment Required<br/>(job_id + payment instruction)
221
-
222
- A->>G: POST /v1/agent/settle (job_id, private_key)
223
- G->>C: Send payment tx (SOL/USDC)<br/>recipient=Agent Treasury
224
- C-->>G: tx_signature
225
- G->>G: Load locked job by job_id
226
- G->>C: Verify tx signature success
227
- G->>G: Release output once
228
- G-->>A: 200 OK (agent_output + settlement_details)
229
- ```
230
-
231
- ### Job lifecycle / state machine
232
-
233
- ```mermaid
234
- stateDiagram-v2
235
- [*] --> Created: /v1/agent/trade<br/>job_id minted
236
- Created --> Locked: result locked until paid
237
- Locked --> Expired: TTL elapses<br/>(no settlement)
238
- Locked --> Settling: /v1/agent/settle<br/>signed payment submitted
239
- Settling --> Released: signature verified<br/>output released
240
- Settling --> Locked: verification failed<br/>job remains until TTL
241
- Released --> [*]
242
- Expired --> [*]
243
- ```
244
-
245
- ---
246
-
247
- ## Client expectations (what you can rely on)
248
-
249
- - **Two-call integration**: request work via `/v1/agent/trade`, then unlock via `/v1/agent/settle`.
250
- - **Single payment**: you pay once to the `recipient` address returned by the 402 challenge.
251
- - **Clear fee disclosure**: the 402 includes a breakdown showing the **5% settlement fee** and who receives it.
252
- - **Time-bounded**: each `job_id` expires after `ttl_seconds` if you don't settle in time.
253
-
254
- ---
255
-
256
- ## ATP Settlement Middleware
257
-
258
- The ATP Settlement Middleware enables **automatic payment processing** for any FastAPI endpoint. Unlike the main ATP Gateway (which uses a 402 challenge), the middleware handles payment **automatically after** your endpoint executes—perfect for APIs that want seamless billing.
259
-
260
- ### How It Works
261
-
262
- The middleware intercepts requests, executes your endpoint, then automatically processes payment:
263
-
264
- ```mermaid
265
- sequenceDiagram
266
- autonumber
267
- participant C as Client
268
- participant M as Middleware
269
- participant E as Endpoint
270
- participant SS as Settlement Service
271
- participant S as Solana
272
-
273
- C->>M: POST /v1/chat<br/>(x-wallet-private-key header)
274
- M->>E: Forward request
275
- E-->>M: Response + usage data
276
- M->>M: Extract token usage<br/>(auto-detects format)
277
- M->>SS: Calculate payment<br/>(usage → USD → SOL/USDC)
278
- SS->>SS: Split payment<br/>(95% recipient, 5% treasury)
279
- SS->>S: Send payment transaction
280
- S-->>SS: Transaction signature
281
- SS-->>M: Settlement details
282
- M->>M: Add settlement info<br/>to response
283
- M-->>C: Response + atp_settlement
284
- ```
285
-
286
- **Step-by-step:**
287
-
288
- 1. **Client sends request** with wallet private key in header (`x-wallet-private-key`)
289
- 2. **Middleware forwards** request to your endpoint
290
- 3. **Endpoint executes** and returns response with usage data
291
- 4. **Middleware extracts** token counts (supports OpenAI, Anthropic, Google, etc.)
292
- 5. **Settlement service calculates** cost: `(input_tokens × input_rate + output_tokens × output_rate) / 1M`
293
- 6. **Settlement service splits** payment: 95% to recipient, 5% to Swarms Treasury
294
- 7. **Settlement service sends** Solana transaction
295
- 8. **Middleware adds** settlement info to response and returns to client
296
-
297
- ### Quick Start
298
-
299
- ```python
300
- from fastapi import FastAPI
301
- from atp.middleware import ATPSettlementMiddleware
302
- from atp.schemas import PaymentToken
303
-
304
- app = FastAPI()
305
-
306
- app.add_middleware(
307
- ATPSettlementMiddleware,
308
- allowed_endpoints=["/v1/chat", "/v1/completions"],
309
- input_cost_per_million_usd=10.0, # $10 per million input tokens
310
- output_cost_per_million_usd=30.0, # $30 per million output tokens
311
- recipient_pubkey="YourPublicKeyHere", # Your wallet receives 95%
312
- payment_token=PaymentToken.SOL,
313
- )
314
- ```
315
-
316
- **Client request:**
317
- ```bash
318
- curl -X POST http://localhost:8000/v1/chat \
319
- -H "x-wallet-private-key: [1,2,3,...]" \
320
- -d '{"message": "Hello!"}'
321
- ```
322
-
323
- **Your endpoint:**
324
- ```python
325
- @app.post("/v1/chat")
326
- async def chat(request: dict):
327
- return {
328
- "output": "Response here",
329
- "usage": {
330
- "input_tokens": 150,
331
- "output_tokens": 50,
332
- }
333
- }
334
- ```
335
-
336
- **Response includes settlement:**
337
- ```json
338
- {
339
- "output": "Response here",
340
- "usage": {"input_tokens": 150, "output_tokens": 50},
341
- "atp_settlement": {
342
- "status": "paid",
343
- "transaction_signature": "5j7s8K9...",
344
- "payment": {
345
- "total_amount_sol": 0.0003,
346
- "recipient": {"amount_sol": 0.000285},
347
- "treasury": {"amount_sol": 0.000015}
348
- }
349
- }
350
- }
351
- ```
352
-
353
- ### Configuration
354
-
355
- | Parameter | Required | Description |
356
- |-----------|----------|-------------|
357
- | `allowed_endpoints` | ✅ | List of paths to apply settlement (e.g., `["/v1/chat"]`) |
358
- | `input_cost_per_million_usd` | ✅ | Cost per million input tokens |
359
- | `output_cost_per_million_usd` | ✅ | Cost per million output tokens |
360
- | `recipient_pubkey` | ✅ | Your Solana wallet (receives 95% of payment) |
361
- | `wallet_private_key_header` | ❌ | Header name for wallet key (default: `x-wallet-private-key`) |
362
- | `payment_token` | ❌ | `PaymentToken.SOL` or `PaymentToken.USDC` (default: SOL) |
363
- | `require_wallet` | ❌ | Require wallet key or skip settlement (default: `True`) |
364
- | `settlement_service_url` | ❌ | Settlement service URL (default: from `ATP_SETTLEMENT_URL` env) |
365
-
366
- ### Payment Calculation
367
-
368
- The middleware uses your configured rates to calculate cost:
369
-
370
- ```
371
- usd_cost = (input_tokens / 1,000,000 × input_rate) + (output_tokens / 1,000,000 × output_rate)
372
- token_amount = usd_cost / token_price_usd
373
- ```
374
-
375
- Payment is split automatically:
376
- - **95%** → `recipient_pubkey` (your wallet)
377
- - **5%** → Swarms Treasury (processing fee)
378
-
379
- The fee is **deducted from the total** (not added on top).
380
-
381
- ### Supported Usage Formats
382
-
383
- The middleware auto-detects usage from common API formats:
384
-
385
- - **OpenAI**: `prompt_tokens`, `completion_tokens`
386
- - **Anthropic**: `input_tokens`, `output_tokens`
387
- - **Google/Gemini**: `promptTokenCount`, `candidatesTokenCount`
388
- - **Generic**: `input_tokens`, `output_tokens`, `total_tokens`
389
- - **Nested**: `usage.*`, `meta.usage`, `statistics.*`
390
-
391
- ### Middleware vs. Main Protocol
392
-
393
- | Feature | Main Gateway | Middleware |
394
- |---------|--------------|------------|
395
- | **Flow** | Two-step: 402 challenge → settle | Automatic: single request |
396
- | **Use Case** | Pay-to-unlock results | Per-request billing |
397
- | **Integration** | Two API calls | One API call |
398
-
399
- **Use middleware for:** Automatic billing on every request
400
- **Use main protocol for:** Explicit payment approval before results
401
-
@@ -1,9 +0,0 @@
1
- atp/__init__.py,sha256=fpKQQCi9HQEj4t2Rs5ng5qmp0KwGV6bZIl1tnS-3HQ8,251
2
- atp/config.py,sha256=lYERbrySRTuyS_jeaAnLHYuBEQNLqaKLQTy_nEFP7lY,2041
3
- atp/middleware.py,sha256=GlRBXEba_hlGMPi69LAGUJSQsKfmwSnAENKZQ9QcXhU,13185
4
- atp/schemas.py,sha256=iASVBPpAhrO-LDXs2UC9ABtfV1oDYsu4kZcz3dVeJNA,6220
5
- atp/settlement_client.py,sha256=jfvhxDqp2kDISWG7tjX5s88goAPxp-lMXvuJtpMyOys,6742
6
- atp_protocol-1.2.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
7
- atp_protocol-1.2.0.dist-info/METADATA,sha256=r-Q1CFshMWPS-jftoGwI7OuPcj8B609IRGcBe00VX0E,14295
8
- atp_protocol-1.2.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
9
- atp_protocol-1.2.0.dist-info/RECORD,,