getaccord 0.6.0__tar.gz
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.
- getaccord-0.6.0/.gitignore +5 -0
- getaccord-0.6.0/PKG-INFO +136 -0
- getaccord-0.6.0/README.md +119 -0
- getaccord-0.6.0/examples/seller_webhook.py +59 -0
- getaccord-0.6.0/examples/trip_booker.py +51 -0
- getaccord-0.6.0/examples/x402_gateway.py +47 -0
- getaccord-0.6.0/pyproject.toml +32 -0
- getaccord-0.6.0/src/getaccord/__init__.py +38 -0
- getaccord-0.6.0/src/getaccord/aio.py +44 -0
- getaccord-0.6.0/src/getaccord/client.py +348 -0
- getaccord-0.6.0/src/getaccord/errors.py +15 -0
- getaccord-0.6.0/src/getaccord/keys.py +176 -0
- getaccord-0.6.0/src/getaccord/money.py +62 -0
- getaccord-0.6.0/src/getaccord/py.typed +0 -0
- getaccord-0.6.0/src/getaccord/seller.py +106 -0
- getaccord-0.6.0/src/getaccord/settings.py +27 -0
- getaccord-0.6.0/src/getaccord/x402.py +237 -0
- getaccord-0.6.0/tests/fixtures.json +66 -0
- getaccord-0.6.0/tests/test_intent.py +152 -0
- getaccord-0.6.0/tests/test_keys.py +54 -0
- getaccord-0.6.0/tests/test_live.py +47 -0
- getaccord-0.6.0/tests/test_money_settings.py +43 -0
- getaccord-0.6.0/tests/test_seller.py +51 -0
- getaccord-0.6.0/tests/test_x402.py +68 -0
getaccord-0.6.0/PKG-INFO
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: getaccord
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Let AI agents spend within limits you set: holds, sign-off and exact payments, enforced on chain.
|
|
5
|
+
Project-URL: Homepage, https://useaccord.ai
|
|
6
|
+
Author: Accord
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Keywords: ai agents,payments,sui,x402
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Requires-Dist: cryptography>=42
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# getaccord (Python)
|
|
19
|
+
|
|
20
|
+
Let AI agents spend within limits you set. An agent holds money with sellers, then pays everyone at once or no one; the limits are enforced on chain. The same API as [`@getaccord/sdk`](https://www.npmjs.com/package/@getaccord/sdk), for Python 3.9+.
|
|
21
|
+
|
|
22
|
+
Test mode: test dollars only.
|
|
23
|
+
|
|
24
|
+
## Quickstart
|
|
25
|
+
|
|
26
|
+
1. Make an agent key in your project folder. It's created on your machine and never leaves it:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npx @getaccord/cli init
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
This writes `ACCORD_AGENT_KEY` to `.env`, which the Python SDK reads as is.
|
|
33
|
+
|
|
34
|
+
2. Install:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install getaccord
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
3. Buy something: hold money with each seller, then commit.
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from getaccord import Accord
|
|
44
|
+
|
|
45
|
+
accord = Accord() # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
|
|
46
|
+
intent = accord.intent(budget=4500) # whole cents; budget_micros= for exact sub-cent amounts
|
|
47
|
+
intent.hold("skyfare", 3000, ref="SFO to JFK")
|
|
48
|
+
intent.hold("stayco", 1500, ref="2 nights")
|
|
49
|
+
result = intent.commit() # everyone is paid, or no one is
|
|
50
|
+
print(result.status, result.intent["proofUrl"])
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Amounts are whole cents (`int`) or exact micros (`amount_micros=`, millionths of a dollar). Floats are refused, so no amount is ever rounded.
|
|
54
|
+
|
|
55
|
+
## Buying
|
|
56
|
+
|
|
57
|
+
| | |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `accord.intent(budget, *, budget_micros, coin, mode, expires_in, key)` | Opens a purchase. `coin`: the usual dollar coin or `"USDC"`. `mode`: `"all"` (everyone or no one) or `"each"`. |
|
|
60
|
+
| `intent.hold(seller, amount, *, amount_micros, ref, type)` | Locks money with one seller. `type`: `"reserve"` or `"deliver"`. |
|
|
61
|
+
| `intent.holds([...])` | Several holds in one step (one transaction). |
|
|
62
|
+
| `intent.commit(wait="60s")` | Waits for every seller to confirm, then pays them all. In `"all"` mode a decline or timeout releases everything. |
|
|
63
|
+
| `intent.abort()` | Calls it off; every held dollar comes back. |
|
|
64
|
+
| `intent.results()`, `intent.accept(i)`, `intent.reject(i)` | Deliver holds: check the work before anyone is paid. |
|
|
65
|
+
| `accord.balance()` | What's available, and what's left of the key's weekly budget. |
|
|
66
|
+
|
|
67
|
+
Errors are `AccordError` with a stable `.code` (`limit_exceeded`, `seller_not_allowed`, `insufficient_balance`, `awaiting_approval`, `too_many_holds`, ...) and a message that says what to do.
|
|
68
|
+
|
|
69
|
+
A purchase over the key's sign-off limit waits for a person: `hold()` raises `awaiting_approval` and no money is locked. In test mode, `accord.test.approve(intent.id)` approves it as the owner would.
|
|
70
|
+
|
|
71
|
+
Async: `AsyncAccord` has the same methods, awaitable.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from getaccord import AsyncAccord
|
|
75
|
+
|
|
76
|
+
accord = AsyncAccord()
|
|
77
|
+
intent = await accord.intent(budget=4500)
|
|
78
|
+
await intent.hold("skyfare", 3000)
|
|
79
|
+
result = await intent.commit()
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Paying x402 sellers
|
|
83
|
+
|
|
84
|
+
Sellers that charge per request with [x402](https://www.x402.org) can add an Accord option to their 402.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from getaccord.x402 import pay
|
|
88
|
+
|
|
89
|
+
response = pay("https://seller.example/report") # quote, hold, commit, fetch with the proof
|
|
90
|
+
print(response.status, response.json())
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Several sellers in one purchase: `quote(url)`, `hold(intent, offer)` for each, `intent.commit()`, then `fetch_paid(offer, intent.id, result.digest, indexes)`.
|
|
94
|
+
|
|
95
|
+
Selling with x402: add `accord_requirement(pay_to=..., usd_cents=25)` to your 402's `accepts`, then check each paid request with `verify_accord_payment(header, requirement, resource=url)`. See `examples/x402_gateway.py`.
|
|
96
|
+
|
|
97
|
+
## Selling (webhooks)
|
|
98
|
+
|
|
99
|
+
Accord tells your server about each hold with a signed webhook. Answer whether you can deliver:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from getaccord import Handler
|
|
103
|
+
|
|
104
|
+
handler = Handler(
|
|
105
|
+
on_hold=lambda event: True, # ready (or False, or {"declined": "why"})
|
|
106
|
+
on_commit=lambda event: print("paid", event["intentId"]),
|
|
107
|
+
) # reads ACCORD_WEBHOOK_SECRET
|
|
108
|
+
|
|
109
|
+
# Flask
|
|
110
|
+
@app.post("/accord")
|
|
111
|
+
def accord_webhook():
|
|
112
|
+
status, body = handler.handle(request.get_data(), request.headers)
|
|
113
|
+
return body, status
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`handle()` checks the `Accord-Signature` header (HMAC-SHA256, a 5-minute window against replays, old and new secrets during a rotation) and answers each event once. Give it the raw request body. `verify_signature(raw, header, secret)` is there on its own too.
|
|
117
|
+
|
|
118
|
+
## Examples
|
|
119
|
+
|
|
120
|
+
- `examples/trip_booker.py`: a flight, a hotel and a car, all paid or none (`--fail ridenow` to see a decline release everything).
|
|
121
|
+
- `examples/seller_webhook.py`: a seller answering webhooks with no framework.
|
|
122
|
+
- `examples/x402_gateway.py`: an x402 gateway paid through Accord.
|
|
123
|
+
|
|
124
|
+
## Tests
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
pip install -e '.[dev]'
|
|
128
|
+
pytest # unit tests
|
|
129
|
+
ACCORD_LIVE=1 ACCORD_URL=https://api.useaccord.ai pytest # plus a live test-mode purchase
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Signatures are checked byte-for-byte against the TypeScript SDK's.
|
|
133
|
+
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
Apache-2.0
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# getaccord (Python)
|
|
2
|
+
|
|
3
|
+
Let AI agents spend within limits you set. An agent holds money with sellers, then pays everyone at once or no one; the limits are enforced on chain. The same API as [`@getaccord/sdk`](https://www.npmjs.com/package/@getaccord/sdk), for Python 3.9+.
|
|
4
|
+
|
|
5
|
+
Test mode: test dollars only.
|
|
6
|
+
|
|
7
|
+
## Quickstart
|
|
8
|
+
|
|
9
|
+
1. Make an agent key in your project folder. It's created on your machine and never leaves it:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx @getaccord/cli init
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This writes `ACCORD_AGENT_KEY` to `.env`, which the Python SDK reads as is.
|
|
16
|
+
|
|
17
|
+
2. Install:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install getaccord
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
3. Buy something: hold money with each seller, then commit.
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from getaccord import Accord
|
|
27
|
+
|
|
28
|
+
accord = Accord() # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
|
|
29
|
+
intent = accord.intent(budget=4500) # whole cents; budget_micros= for exact sub-cent amounts
|
|
30
|
+
intent.hold("skyfare", 3000, ref="SFO to JFK")
|
|
31
|
+
intent.hold("stayco", 1500, ref="2 nights")
|
|
32
|
+
result = intent.commit() # everyone is paid, or no one is
|
|
33
|
+
print(result.status, result.intent["proofUrl"])
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Amounts are whole cents (`int`) or exact micros (`amount_micros=`, millionths of a dollar). Floats are refused, so no amount is ever rounded.
|
|
37
|
+
|
|
38
|
+
## Buying
|
|
39
|
+
|
|
40
|
+
| | |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `accord.intent(budget, *, budget_micros, coin, mode, expires_in, key)` | Opens a purchase. `coin`: the usual dollar coin or `"USDC"`. `mode`: `"all"` (everyone or no one) or `"each"`. |
|
|
43
|
+
| `intent.hold(seller, amount, *, amount_micros, ref, type)` | Locks money with one seller. `type`: `"reserve"` or `"deliver"`. |
|
|
44
|
+
| `intent.holds([...])` | Several holds in one step (one transaction). |
|
|
45
|
+
| `intent.commit(wait="60s")` | Waits for every seller to confirm, then pays them all. In `"all"` mode a decline or timeout releases everything. |
|
|
46
|
+
| `intent.abort()` | Calls it off; every held dollar comes back. |
|
|
47
|
+
| `intent.results()`, `intent.accept(i)`, `intent.reject(i)` | Deliver holds: check the work before anyone is paid. |
|
|
48
|
+
| `accord.balance()` | What's available, and what's left of the key's weekly budget. |
|
|
49
|
+
|
|
50
|
+
Errors are `AccordError` with a stable `.code` (`limit_exceeded`, `seller_not_allowed`, `insufficient_balance`, `awaiting_approval`, `too_many_holds`, ...) and a message that says what to do.
|
|
51
|
+
|
|
52
|
+
A purchase over the key's sign-off limit waits for a person: `hold()` raises `awaiting_approval` and no money is locked. In test mode, `accord.test.approve(intent.id)` approves it as the owner would.
|
|
53
|
+
|
|
54
|
+
Async: `AsyncAccord` has the same methods, awaitable.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from getaccord import AsyncAccord
|
|
58
|
+
|
|
59
|
+
accord = AsyncAccord()
|
|
60
|
+
intent = await accord.intent(budget=4500)
|
|
61
|
+
await intent.hold("skyfare", 3000)
|
|
62
|
+
result = await intent.commit()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Paying x402 sellers
|
|
66
|
+
|
|
67
|
+
Sellers that charge per request with [x402](https://www.x402.org) can add an Accord option to their 402.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from getaccord.x402 import pay
|
|
71
|
+
|
|
72
|
+
response = pay("https://seller.example/report") # quote, hold, commit, fetch with the proof
|
|
73
|
+
print(response.status, response.json())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Several sellers in one purchase: `quote(url)`, `hold(intent, offer)` for each, `intent.commit()`, then `fetch_paid(offer, intent.id, result.digest, indexes)`.
|
|
77
|
+
|
|
78
|
+
Selling with x402: add `accord_requirement(pay_to=..., usd_cents=25)` to your 402's `accepts`, then check each paid request with `verify_accord_payment(header, requirement, resource=url)`. See `examples/x402_gateway.py`.
|
|
79
|
+
|
|
80
|
+
## Selling (webhooks)
|
|
81
|
+
|
|
82
|
+
Accord tells your server about each hold with a signed webhook. Answer whether you can deliver:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from getaccord import Handler
|
|
86
|
+
|
|
87
|
+
handler = Handler(
|
|
88
|
+
on_hold=lambda event: True, # ready (or False, or {"declined": "why"})
|
|
89
|
+
on_commit=lambda event: print("paid", event["intentId"]),
|
|
90
|
+
) # reads ACCORD_WEBHOOK_SECRET
|
|
91
|
+
|
|
92
|
+
# Flask
|
|
93
|
+
@app.post("/accord")
|
|
94
|
+
def accord_webhook():
|
|
95
|
+
status, body = handler.handle(request.get_data(), request.headers)
|
|
96
|
+
return body, status
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`handle()` checks the `Accord-Signature` header (HMAC-SHA256, a 5-minute window against replays, old and new secrets during a rotation) and answers each event once. Give it the raw request body. `verify_signature(raw, header, secret)` is there on its own too.
|
|
100
|
+
|
|
101
|
+
## Examples
|
|
102
|
+
|
|
103
|
+
- `examples/trip_booker.py`: a flight, a hotel and a car, all paid or none (`--fail ridenow` to see a decline release everything).
|
|
104
|
+
- `examples/seller_webhook.py`: a seller answering webhooks with no framework.
|
|
105
|
+
- `examples/x402_gateway.py`: an x402 gateway paid through Accord.
|
|
106
|
+
|
|
107
|
+
## Tests
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
pip install -e '.[dev]'
|
|
111
|
+
pytest # unit tests
|
|
112
|
+
ACCORD_LIVE=1 ACCORD_URL=https://api.useaccord.ai pytest # plus a live test-mode purchase
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Signatures are checked byte-for-byte against the TypeScript SDK's.
|
|
116
|
+
|
|
117
|
+
## License
|
|
118
|
+
|
|
119
|
+
Apache-2.0
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""A seller that answers Accord's webhooks, with no framework (Python's http.server).
|
|
2
|
+
|
|
3
|
+
ACCORD_WEBHOOK_SECRET=whsec_... python seller_webhook.py # listens on :8080
|
|
4
|
+
|
|
5
|
+
The same Handler works in Flask or FastAPI; give it the raw body:
|
|
6
|
+
|
|
7
|
+
# Flask
|
|
8
|
+
@app.post("/accord")
|
|
9
|
+
def accord_webhook():
|
|
10
|
+
status, body = handler.handle(request.get_data(), request.headers)
|
|
11
|
+
return body, status
|
|
12
|
+
|
|
13
|
+
# FastAPI
|
|
14
|
+
@app.post("/accord")
|
|
15
|
+
async def accord_webhook(request: Request):
|
|
16
|
+
status, body = handler.handle(await request.body(), request.headers)
|
|
17
|
+
return JSONResponse(body, status_code=status)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
21
|
+
import json
|
|
22
|
+
|
|
23
|
+
from getaccord import Handler, usd
|
|
24
|
+
|
|
25
|
+
STOCK = {"room-101": True, "room-102": False}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def on_hold(event):
|
|
29
|
+
# Can we deliver what this hold is for? Answer within a few seconds.
|
|
30
|
+
print(f"hold {event['index']}: {usd(event.get('amountMicros', event['amount'] * 10_000))} for {event['ref']!r} from {event['buyer']}")
|
|
31
|
+
return STOCK.get(event["ref"], True) or {"declined": f"{event['ref']} is taken"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def on_commit(event):
|
|
35
|
+
print(f"paid: purchase {event['intentId']} hold {event['index']}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def on_abort(event):
|
|
39
|
+
print(f"released: purchase {event['intentId']} hold {event['index']} ({event['type']})")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
handler = Handler(on_hold=on_hold, on_commit=on_commit, on_abort=on_abort) # reads ACCORD_WEBHOOK_SECRET
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Webhook(BaseHTTPRequestHandler):
|
|
46
|
+
def do_POST(self):
|
|
47
|
+
raw = self.rfile.read(int(self.headers.get("content-length", 0)))
|
|
48
|
+
status, body = handler.handle(raw, dict(self.headers))
|
|
49
|
+
out = json.dumps(body).encode()
|
|
50
|
+
self.send_response(status)
|
|
51
|
+
self.send_header("content-type", "application/json")
|
|
52
|
+
self.send_header("content-length", str(len(out)))
|
|
53
|
+
self.end_headers()
|
|
54
|
+
self.wfile.write(out)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
print("seller webhook on http://localhost:8080")
|
|
59
|
+
HTTPServer(("", 8080), Webhook).serve_forever()
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Trip booker: hold a flight, a hotel and a car. All three are paid, or nobody is.
|
|
2
|
+
|
|
3
|
+
python trip_booker.py --fail ridenow # RideNow declines -> aborted, nobody paid (run this first)
|
|
4
|
+
python trip_booker.py # everyone confirms -> committed
|
|
5
|
+
|
|
6
|
+
Uses ACCORD_AGENT_KEY from the environment or ./.env (npx @getaccord/cli init).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from getaccord import Accord, AccordError, HoldSpec, usd
|
|
12
|
+
|
|
13
|
+
accord = Accord()
|
|
14
|
+
failing = sys.argv[sys.argv.index("--fail") + 1] if "--fail" in sys.argv else None
|
|
15
|
+
if failing:
|
|
16
|
+
accord.test.fail_seller(failing, True)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
intent = accord.intent(1200_00) # cents
|
|
20
|
+
trip = [
|
|
21
|
+
HoldSpec("skyfare", 640_00, ref="SFO to JFK, Dec 18"),
|
|
22
|
+
HoldSpec("stayco", 420_00, ref="2 nights"),
|
|
23
|
+
HoldSpec("ridenow", 85_00, ref="airport pickup"),
|
|
24
|
+
]
|
|
25
|
+
try:
|
|
26
|
+
holds = intent.holds(trip) # one step for all three
|
|
27
|
+
except AccordError as e:
|
|
28
|
+
if e.code != "awaiting_approval":
|
|
29
|
+
raise
|
|
30
|
+
# This key's unapproved spending in 24 hours would go over its limit: a person signs off.
|
|
31
|
+
print(f"Waiting for sign-off: {e.detail.split(' No money')[0]}")
|
|
32
|
+
print("Approving it as the owner (test mode: accord.test.approve).")
|
|
33
|
+
accord.test.approve(intent.id)
|
|
34
|
+
holds = intent.holds(trip)
|
|
35
|
+
print(f"Intent opened budget {usd(1200_00 * 10_000)}")
|
|
36
|
+
print(f"{len(holds)} holds placed {usd(sum(h.amount_micros for h in holds))} locked")
|
|
37
|
+
|
|
38
|
+
result = intent.commit() # all three, or nothing moves
|
|
39
|
+
for h in result.intent["holds"]:
|
|
40
|
+
print(f"{h['seller']:<17} {h['state']}")
|
|
41
|
+
if result.status == "committed":
|
|
42
|
+
print(f"\nCommitted: {len(result.intent['holds'])} sellers paid {usd(result.intent['paidMicros'])} in one step")
|
|
43
|
+
else:
|
|
44
|
+
print(f"\n{result.status.capitalize()}: {result.reason or ''}. Every hold released; nobody paid.")
|
|
45
|
+
print(f"Timeline: {result.intent['proofUrl']}")
|
|
46
|
+
except AccordError as e:
|
|
47
|
+
print(f"Refused ({e.code}): {e.detail or ''}")
|
|
48
|
+
sys.exit(1)
|
|
49
|
+
finally:
|
|
50
|
+
if failing:
|
|
51
|
+
accord.test.fail_seller(failing, False)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""An x402 gateway in Python: charges 25 cents per request, paid through Accord.
|
|
2
|
+
|
|
3
|
+
PAY_TO=0x... python x402_gateway.py # listens on :8404
|
|
4
|
+
|
|
5
|
+
It adds an Accord option to its 402 and checks the buyer's payment with Accord's facilitator
|
|
6
|
+
before answering. Any buyer that pays x402 through Accord can pay it (TypeScript or Python).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
14
|
+
|
|
15
|
+
from getaccord.x402 import accord_requirement, verify_accord_payment
|
|
16
|
+
|
|
17
|
+
PORT = int(os.environ.get("PORT", 8404))
|
|
18
|
+
PAY_TO = os.environ["PAY_TO"] # the account the gateway is paid to
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Gateway(BaseHTTPRequestHandler):
|
|
22
|
+
def do_GET(self):
|
|
23
|
+
url = f"http://localhost:{PORT}{self.path}"
|
|
24
|
+
accord = accord_requirement(pay_to=PAY_TO, usd_cents=25)
|
|
25
|
+
header = self.headers.get("payment-signature")
|
|
26
|
+
if not header:
|
|
27
|
+
required = {"x402Version": 2, "error": "payment required", "resource": {"url": url, "description": "Market data"}, "accepts": [accord]}
|
|
28
|
+
return self._send(402, required, {"payment-required": base64.b64encode(json.dumps(required).encode()).decode()})
|
|
29
|
+
paid = verify_accord_payment(header, accord, resource=url) # on chain, signed for this URL, used once
|
|
30
|
+
if not paid["ok"]:
|
|
31
|
+
return self._send(402, {"error": paid["reason"], "message": paid.get("message")})
|
|
32
|
+
data = {"path": self.path, "quote": {"pair": "SUI/USD", "price": "3.21", "asOf": datetime.now(timezone.utc).isoformat()}}
|
|
33
|
+
self._send(200, data)
|
|
34
|
+
|
|
35
|
+
def _send(self, status, body, headers=None):
|
|
36
|
+
out = json.dumps(body).encode()
|
|
37
|
+
self.send_response(status)
|
|
38
|
+
self.send_header("content-type", "application/json")
|
|
39
|
+
for k, v in (headers or {}).items():
|
|
40
|
+
self.send_header(k, v)
|
|
41
|
+
self.end_headers()
|
|
42
|
+
self.wfile.write(out)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
print(f"x402 gateway on http://localhost:{PORT} (paid to {PAY_TO})")
|
|
47
|
+
HTTPServer(("", PORT), Gateway).serve_forever()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "getaccord"
|
|
7
|
+
version = "0.6.0"
|
|
8
|
+
description = "Let AI agents spend within limits you set: holds, sign-off and exact payments, enforced on chain."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [{ name = "Accord" }]
|
|
13
|
+
keywords = ["ai agents", "payments", "x402", "sui"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
]
|
|
19
|
+
dependencies = ["cryptography>=42"]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = ["pytest>=8"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://useaccord.ai"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["src/getaccord"]
|
|
29
|
+
|
|
30
|
+
[tool.pytest.ini_options]
|
|
31
|
+
testpaths = ["tests"]
|
|
32
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Accord for Python: let AI agents spend within limits you set.
|
|
2
|
+
|
|
3
|
+
from getaccord import Accord
|
|
4
|
+
|
|
5
|
+
accord = Accord() # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
|
|
6
|
+
intent = accord.intent(budget=4500) # cents; or budget_micros= for exact sub-cent amounts
|
|
7
|
+
intent.hold("skyfare", 3000)
|
|
8
|
+
intent.hold("stayco", 1500)
|
|
9
|
+
result = intent.commit() # everyone is paid, or no one is
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .aio import AsyncAccord, AsyncIntent
|
|
13
|
+
from .client import Accord, CommitResult, HoldSpec, Intent, PlacedHold
|
|
14
|
+
from .errors import AccordError
|
|
15
|
+
from .keys import AgentKey, agent_id
|
|
16
|
+
from .money import micros, usd
|
|
17
|
+
from .seller import Handler, verify_signature
|
|
18
|
+
from .settings import DEFAULT_URL
|
|
19
|
+
|
|
20
|
+
__version__ = "0.6.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"Accord",
|
|
24
|
+
"AccordError",
|
|
25
|
+
"AgentKey",
|
|
26
|
+
"AsyncAccord",
|
|
27
|
+
"AsyncIntent",
|
|
28
|
+
"CommitResult",
|
|
29
|
+
"DEFAULT_URL",
|
|
30
|
+
"Handler",
|
|
31
|
+
"HoldSpec",
|
|
32
|
+
"Intent",
|
|
33
|
+
"PlacedHold",
|
|
34
|
+
"agent_id",
|
|
35
|
+
"micros",
|
|
36
|
+
"usd",
|
|
37
|
+
"verify_signature",
|
|
38
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Async versions: the same methods, run in a worker thread so they don't block the event loop.
|
|
2
|
+
|
|
3
|
+
accord = AsyncAccord()
|
|
4
|
+
intent = await accord.intent(budget=4500)
|
|
5
|
+
await intent.hold("skyfare", 3000)
|
|
6
|
+
result = await intent.commit()
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import functools
|
|
13
|
+
from typing import Any, Callable, Optional
|
|
14
|
+
|
|
15
|
+
from .client import Accord, Intent
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _run(f: Callable[..., Any]) -> Callable[..., Any]:
|
|
19
|
+
@functools.wraps(f)
|
|
20
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
21
|
+
return await asyncio.to_thread(f, *args, **kwargs)
|
|
22
|
+
|
|
23
|
+
return wrapper
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AsyncIntent:
|
|
27
|
+
def __init__(self, intent: Intent):
|
|
28
|
+
self._i = intent
|
|
29
|
+
for name in ("hold", "holds", "results", "accept", "reject", "commit", "abort", "state"):
|
|
30
|
+
setattr(self, name, _run(getattr(intent, name)))
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def id(self) -> Optional[str]:
|
|
34
|
+
return self._i.id
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AsyncAccord:
|
|
38
|
+
def __init__(self, url: Optional[str] = None, **kwargs: Any):
|
|
39
|
+
self.sync = Accord(url, **kwargs)
|
|
40
|
+
self.get = _run(self.sync.get)
|
|
41
|
+
self.balance = _run(self.sync.balance)
|
|
42
|
+
|
|
43
|
+
async def intent(self, *args: Any, **kwargs: Any) -> AsyncIntent:
|
|
44
|
+
return AsyncIntent(await asyncio.to_thread(self.sync.intent, *args, **kwargs))
|