token-verdict-mcp 0.1.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.
- token_verdict_mcp-0.1.0/.gitignore +8 -0
- token_verdict_mcp-0.1.0/PKG-INFO +150 -0
- token_verdict_mcp-0.1.0/README.md +135 -0
- token_verdict_mcp-0.1.0/pyproject.toml +33 -0
- token_verdict_mcp-0.1.0/src/token_verdict_mcp/__init__.py +7 -0
- token_verdict_mcp-0.1.0/src/token_verdict_mcp/__main__.py +4 -0
- token_verdict_mcp-0.1.0/src/token_verdict_mcp/client.py +310 -0
- token_verdict_mcp-0.1.0/src/token_verdict_mcp/schemas.py +89 -0
- token_verdict_mcp-0.1.0/src/token_verdict_mcp/server.py +105 -0
- token_verdict_mcp-0.1.0/tests/fixtures/payment_required.json +477 -0
- token_verdict_mcp-0.1.0/tests/fixtures/verdict_example.json +61 -0
- token_verdict_mcp-0.1.0/tests/test_client.py +246 -0
- token_verdict_mcp-0.1.0/tests/test_server.py +59 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: token-verdict-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for Token Verdict — pay-per-call token risk verdicts over x402 ($0.02 USDC on Base)
|
|
5
|
+
Author: Jobfile Studio
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: agents,base,mcp,risk,token,usdc,x402
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: eth-account>=0.11
|
|
10
|
+
Requires-Dist: httpx>=0.27
|
|
11
|
+
Requires-Dist: mcp<2,>=1.2
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
<!-- mcp-name: io.github.quincygb/token-verdict-mcp -->
|
|
17
|
+
# token-verdict-mcp
|
|
18
|
+
|
|
19
|
+
An [MCP](https://modelcontextprotocol.io) server (stdio transport) that
|
|
20
|
+
exposes **Token Verdict** as a native tool for any MCP host — Claude
|
|
21
|
+
Desktop, Cursor, or your own agent runtime.
|
|
22
|
+
|
|
23
|
+
Token Verdict is a pay-per-call token risk screen for AI agents: send a
|
|
24
|
+
token contract address, get back a verdict (**SOLID / CAUTION /
|
|
25
|
+
DANGER**), a 0–100 risk score, six weighted market-structure signals
|
|
26
|
+
explained in plain English, and a written analyst take. It costs
|
|
27
|
+
**$0.02 USDC per call on Base**, paid via the
|
|
28
|
+
[x402 protocol](https://x402.org) — no accounts, no API keys; the
|
|
29
|
+
payment is the authentication.
|
|
30
|
+
|
|
31
|
+
## The tool
|
|
32
|
+
|
|
33
|
+
**`token_verdict`** — one tool, the service's real contract:
|
|
34
|
+
|
|
35
|
+
| Input | Type | Notes |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| `address` | string (required) | Token contract address (`0x...`) |
|
|
38
|
+
| `chain` | string, default `"base"` | `base` · `ethereum` · `solana` — which token market to analyze. Payment always settles in USDC on Base. |
|
|
39
|
+
|
|
40
|
+
Output is the service's verdict JSON: `token`, `verdict`, `score`,
|
|
41
|
+
`signals` (exactly six), `take`, and `market` (the raw data the verdict
|
|
42
|
+
derives from, so callers can re-check the math). Market-structure
|
|
43
|
+
analysis only — honeypot simulation and holder concentration are not
|
|
44
|
+
checked, and the product says so in every take.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install token-verdict-mcp # once published; or from a checkout:
|
|
50
|
+
pip install ./mcp # (this directory)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Requires Python ≥ 3.10. The server pins the MCP v1 SDK API
|
|
54
|
+
(`mcp>=1.2,<2`).
|
|
55
|
+
|
|
56
|
+
## Configuration
|
|
57
|
+
|
|
58
|
+
All configuration is the **operator's own environment** — whoever runs
|
|
59
|
+
this server supplies their own wallet. No key material ships in this
|
|
60
|
+
package, and the package author never sees your key.
|
|
61
|
+
|
|
62
|
+
| Env var | Required | Purpose |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `AGENT_PRIVATE_KEY` | for paid calls | EVM private key (`0x...`) of a wallet holding USDC on Base. Used locally to sign the x402 EIP-3009 authorization. |
|
|
65
|
+
| `AGENT_KEY_FILE` | alternative | Path to a file containing that key. |
|
|
66
|
+
| `TOKEN_VERDICT_URL` | no | Service base URL override (default: production). |
|
|
67
|
+
| `TOKEN_VERDICT_MAX_AMOUNT_UNITS` | no | Spend guard per call in USDC micro-units (default `20000` = $0.02, the known price). The client refuses to sign anything priced above it. |
|
|
68
|
+
|
|
69
|
+
**Without a signer configured the tool never pays.** On a 402 it
|
|
70
|
+
returns the parsed challenge as a structured error — `error:
|
|
71
|
+
"payment_required"` with the full `accepts` array (scheme, network,
|
|
72
|
+
asset, amount, payTo) — so the calling agent can see the price and
|
|
73
|
+
decide what to do, or settle the challenge with its own x402 client.
|
|
74
|
+
|
|
75
|
+
## MCP host configuration
|
|
76
|
+
|
|
77
|
+
Claude Desktop (`claude_desktop_config.json`) — same shape for other
|
|
78
|
+
stdio MCP hosts:
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"mcpServers": {
|
|
83
|
+
"token-verdict": {
|
|
84
|
+
"command": "token-verdict-mcp",
|
|
85
|
+
"env": {
|
|
86
|
+
"AGENT_PRIVATE_KEY": "0xYOUR_OWN_WALLET_KEY"
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
From a checkout instead of an install:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"mcpServers": {
|
|
98
|
+
"token-verdict": {
|
|
99
|
+
"command": "python",
|
|
100
|
+
"args": ["-m", "token_verdict_mcp"],
|
|
101
|
+
"env": {
|
|
102
|
+
"PYTHONPATH": "/path/to/token-verdict-tools/mcp/src",
|
|
103
|
+
"AGENT_KEY_FILE": "/path/to/your/agent.key"
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Prefer `AGENT_KEY_FILE` over inlining a key in a config file when your
|
|
111
|
+
host setup allows it.
|
|
112
|
+
|
|
113
|
+
## How payment works
|
|
114
|
+
|
|
115
|
+
The client mirrors the standard x402 v2 flow (the same flow used for
|
|
116
|
+
the service's own live cataloging payment):
|
|
117
|
+
|
|
118
|
+
1. `POST /v1/verdict` unpaid → HTTP 402, challenge base64-encoded in the
|
|
119
|
+
`payment-required` header.
|
|
120
|
+
2. Pick the `exact` / `eip155:8453` entry from `accepts`.
|
|
121
|
+
3. Build an EIP-3009 `TransferWithAuthorization` (`validAfter: 0`,
|
|
122
|
+
`validBefore: now + maxTimeoutSeconds`, random 32-byte nonce) and
|
|
123
|
+
sign it as EIP-712 typed data against the USDC domain the challenge
|
|
124
|
+
advertises (`extra.name` / `extra.version`).
|
|
125
|
+
4. Retry the identical POST with the payload in the `PAYMENT-SIGNATURE`
|
|
126
|
+
header. The service verifies and settles through its facilitator
|
|
127
|
+
(PayAI) server-side; the settlement receipt comes back in the
|
|
128
|
+
`payment-response` header.
|
|
129
|
+
|
|
130
|
+
## Tests
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
pip install -e ".[dev]"
|
|
134
|
+
pytest
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
14 tests, all payments mocked (httpx `MockTransport`, throwaway signer
|
|
138
|
+
generated at test time). The 402 fixture is the real challenge captured
|
|
139
|
+
from production; the paid-flow test verifies the EIP-712 signature
|
|
140
|
+
actually recovers to the signer address.
|
|
141
|
+
|
|
142
|
+
## Security notes
|
|
143
|
+
|
|
144
|
+
- Your private key is read from your environment at runtime and used
|
|
145
|
+
only to sign payment authorizations locally. It is never transmitted —
|
|
146
|
+
the x402 payload contains a signature, not a key.
|
|
147
|
+
- The spend guard caps any single call at the configured amount
|
|
148
|
+
(default: exactly the $0.02 price).
|
|
149
|
+
- Run this with a dedicated agent wallet holding only working funds,
|
|
150
|
+
the same way you would fund any agent.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
<!-- mcp-name: io.github.quincygb/token-verdict-mcp -->
|
|
2
|
+
# token-verdict-mcp
|
|
3
|
+
|
|
4
|
+
An [MCP](https://modelcontextprotocol.io) server (stdio transport) that
|
|
5
|
+
exposes **Token Verdict** as a native tool for any MCP host — Claude
|
|
6
|
+
Desktop, Cursor, or your own agent runtime.
|
|
7
|
+
|
|
8
|
+
Token Verdict is a pay-per-call token risk screen for AI agents: send a
|
|
9
|
+
token contract address, get back a verdict (**SOLID / CAUTION /
|
|
10
|
+
DANGER**), a 0–100 risk score, six weighted market-structure signals
|
|
11
|
+
explained in plain English, and a written analyst take. It costs
|
|
12
|
+
**$0.02 USDC per call on Base**, paid via the
|
|
13
|
+
[x402 protocol](https://x402.org) — no accounts, no API keys; the
|
|
14
|
+
payment is the authentication.
|
|
15
|
+
|
|
16
|
+
## The tool
|
|
17
|
+
|
|
18
|
+
**`token_verdict`** — one tool, the service's real contract:
|
|
19
|
+
|
|
20
|
+
| Input | Type | Notes |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| `address` | string (required) | Token contract address (`0x...`) |
|
|
23
|
+
| `chain` | string, default `"base"` | `base` · `ethereum` · `solana` — which token market to analyze. Payment always settles in USDC on Base. |
|
|
24
|
+
|
|
25
|
+
Output is the service's verdict JSON: `token`, `verdict`, `score`,
|
|
26
|
+
`signals` (exactly six), `take`, and `market` (the raw data the verdict
|
|
27
|
+
derives from, so callers can re-check the math). Market-structure
|
|
28
|
+
analysis only — honeypot simulation and holder concentration are not
|
|
29
|
+
checked, and the product says so in every take.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install token-verdict-mcp # once published; or from a checkout:
|
|
35
|
+
pip install ./mcp # (this directory)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Requires Python ≥ 3.10. The server pins the MCP v1 SDK API
|
|
39
|
+
(`mcp>=1.2,<2`).
|
|
40
|
+
|
|
41
|
+
## Configuration
|
|
42
|
+
|
|
43
|
+
All configuration is the **operator's own environment** — whoever runs
|
|
44
|
+
this server supplies their own wallet. No key material ships in this
|
|
45
|
+
package, and the package author never sees your key.
|
|
46
|
+
|
|
47
|
+
| Env var | Required | Purpose |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| `AGENT_PRIVATE_KEY` | for paid calls | EVM private key (`0x...`) of a wallet holding USDC on Base. Used locally to sign the x402 EIP-3009 authorization. |
|
|
50
|
+
| `AGENT_KEY_FILE` | alternative | Path to a file containing that key. |
|
|
51
|
+
| `TOKEN_VERDICT_URL` | no | Service base URL override (default: production). |
|
|
52
|
+
| `TOKEN_VERDICT_MAX_AMOUNT_UNITS` | no | Spend guard per call in USDC micro-units (default `20000` = $0.02, the known price). The client refuses to sign anything priced above it. |
|
|
53
|
+
|
|
54
|
+
**Without a signer configured the tool never pays.** On a 402 it
|
|
55
|
+
returns the parsed challenge as a structured error — `error:
|
|
56
|
+
"payment_required"` with the full `accepts` array (scheme, network,
|
|
57
|
+
asset, amount, payTo) — so the calling agent can see the price and
|
|
58
|
+
decide what to do, or settle the challenge with its own x402 client.
|
|
59
|
+
|
|
60
|
+
## MCP host configuration
|
|
61
|
+
|
|
62
|
+
Claude Desktop (`claude_desktop_config.json`) — same shape for other
|
|
63
|
+
stdio MCP hosts:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"mcpServers": {
|
|
68
|
+
"token-verdict": {
|
|
69
|
+
"command": "token-verdict-mcp",
|
|
70
|
+
"env": {
|
|
71
|
+
"AGENT_PRIVATE_KEY": "0xYOUR_OWN_WALLET_KEY"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
From a checkout instead of an install:
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"mcpServers": {
|
|
83
|
+
"token-verdict": {
|
|
84
|
+
"command": "python",
|
|
85
|
+
"args": ["-m", "token_verdict_mcp"],
|
|
86
|
+
"env": {
|
|
87
|
+
"PYTHONPATH": "/path/to/token-verdict-tools/mcp/src",
|
|
88
|
+
"AGENT_KEY_FILE": "/path/to/your/agent.key"
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Prefer `AGENT_KEY_FILE` over inlining a key in a config file when your
|
|
96
|
+
host setup allows it.
|
|
97
|
+
|
|
98
|
+
## How payment works
|
|
99
|
+
|
|
100
|
+
The client mirrors the standard x402 v2 flow (the same flow used for
|
|
101
|
+
the service's own live cataloging payment):
|
|
102
|
+
|
|
103
|
+
1. `POST /v1/verdict` unpaid → HTTP 402, challenge base64-encoded in the
|
|
104
|
+
`payment-required` header.
|
|
105
|
+
2. Pick the `exact` / `eip155:8453` entry from `accepts`.
|
|
106
|
+
3. Build an EIP-3009 `TransferWithAuthorization` (`validAfter: 0`,
|
|
107
|
+
`validBefore: now + maxTimeoutSeconds`, random 32-byte nonce) and
|
|
108
|
+
sign it as EIP-712 typed data against the USDC domain the challenge
|
|
109
|
+
advertises (`extra.name` / `extra.version`).
|
|
110
|
+
4. Retry the identical POST with the payload in the `PAYMENT-SIGNATURE`
|
|
111
|
+
header. The service verifies and settles through its facilitator
|
|
112
|
+
(PayAI) server-side; the settlement receipt comes back in the
|
|
113
|
+
`payment-response` header.
|
|
114
|
+
|
|
115
|
+
## Tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
pip install -e ".[dev]"
|
|
119
|
+
pytest
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
14 tests, all payments mocked (httpx `MockTransport`, throwaway signer
|
|
123
|
+
generated at test time). The 402 fixture is the real challenge captured
|
|
124
|
+
from production; the paid-flow test verifies the EIP-712 signature
|
|
125
|
+
actually recovers to the signer address.
|
|
126
|
+
|
|
127
|
+
## Security notes
|
|
128
|
+
|
|
129
|
+
- Your private key is read from your environment at runtime and used
|
|
130
|
+
only to sign payment authorizations locally. It is never transmitted —
|
|
131
|
+
the x402 payload contains a signature, not a key.
|
|
132
|
+
- The spend guard caps any single call at the configured amount
|
|
133
|
+
(default: exactly the $0.02 price).
|
|
134
|
+
- Run this with a dedicated agent wallet holding only working funds,
|
|
135
|
+
the same way you would fund any agent.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "token-verdict-mcp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "MCP server for Token Verdict — pay-per-call token risk verdicts over x402 ($0.02 USDC on Base)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Jobfile Studio" }]
|
|
13
|
+
keywords = ["mcp", "x402", "base", "usdc", "token", "risk", "agents"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
# mcp 2.x renamed FastMCP -> MCPServer; this package targets the v1
|
|
16
|
+
# SDK API that current MCP hosts and docs are built against.
|
|
17
|
+
"mcp>=1.2,<2",
|
|
18
|
+
"httpx>=0.27",
|
|
19
|
+
"eth-account>=0.11",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
dev = ["pytest>=8"]
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
token-verdict-mcp = "token_verdict_mcp.server:main"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/token_verdict_mcp"]
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
pythonpath = ["src"]
|
|
33
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Token Verdict x402 client — the 402 -> sign -> retry flow.
|
|
2
|
+
|
|
3
|
+
This mirrors, field for field, the proven client flow used for Token
|
|
4
|
+
Verdict's live cataloging payment (Node: @x402/fetch +
|
|
5
|
+
@x402/evm 2.28.0 `ExactEvmScheme`, x402 protocol v2, `exact` scheme):
|
|
6
|
+
|
|
7
|
+
1. POST /v1/verdict unpaid -> HTTP 402 with a base64 JSON challenge in
|
|
8
|
+
the `payment-required` response header.
|
|
9
|
+
2. Pick the `exact` / `eip155:8453` entry from `accepts`.
|
|
10
|
+
3. Build an EIP-3009 `TransferWithAuthorization`:
|
|
11
|
+
{from, to: payTo, value: amount, validAfter: "0",
|
|
12
|
+
validBefore: now + maxTimeoutSeconds, nonce: 32 random bytes}.
|
|
13
|
+
4. Sign it as EIP-712 typed data with domain
|
|
14
|
+
{name: accepts.extra.name, version: accepts.extra.version,
|
|
15
|
+
chainId: 8453, verifyingContract: accepts.asset}.
|
|
16
|
+
5. Retry the identical POST with the payment payload in the
|
|
17
|
+
`PAYMENT-SIGNATURE` header (base64 JSON). The service's facilitator
|
|
18
|
+
(PayAI) verifies and settles USDC on Base server-side.
|
|
19
|
+
|
|
20
|
+
The signer is ALWAYS supplied by whoever runs this package, from their
|
|
21
|
+
own environment (AGENT_PRIVATE_KEY or AGENT_KEY_FILE). No key material
|
|
22
|
+
ships in this package, and without a signer the client never pays — it
|
|
23
|
+
raises PaymentRequiredError carrying the parsed challenge instead.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import base64
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import secrets
|
|
32
|
+
import time
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
import httpx
|
|
37
|
+
from eth_account import Account
|
|
38
|
+
from eth_account.signers.local import LocalAccount
|
|
39
|
+
|
|
40
|
+
DEFAULT_BASE_URL = "https://token-verdict-production.up.railway.app"
|
|
41
|
+
VERDICT_PATH = "/v1/verdict"
|
|
42
|
+
BASE_NETWORK = "eip155:8453"
|
|
43
|
+
# Spend guard: Token Verdict costs 20000 units ($0.02). Refuse to sign for
|
|
44
|
+
# anything above the configured cap (default: exactly the known price),
|
|
45
|
+
# so a hostile or misconfigured endpoint cannot drain more per call.
|
|
46
|
+
DEFAULT_MAX_AMOUNT_UNITS = 20_000
|
|
47
|
+
|
|
48
|
+
TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
49
|
+
"TransferWithAuthorization": [
|
|
50
|
+
{"name": "from", "type": "address"},
|
|
51
|
+
{"name": "to", "type": "address"},
|
|
52
|
+
{"name": "value", "type": "uint256"},
|
|
53
|
+
{"name": "validAfter", "type": "uint256"},
|
|
54
|
+
{"name": "validBefore", "type": "uint256"},
|
|
55
|
+
{"name": "nonce", "type": "bytes32"},
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class TokenVerdictError(Exception):
|
|
61
|
+
"""Non-payment failure from the service (carries HTTP status + body)."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, status: int, detail: Any):
|
|
64
|
+
super().__init__(f"token verdict request failed: HTTP {status}: {detail}")
|
|
65
|
+
self.status = status
|
|
66
|
+
self.detail = detail
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PaymentRequiredError(Exception):
|
|
70
|
+
"""The endpoint demands payment and this client could/did not pay.
|
|
71
|
+
|
|
72
|
+
Carries the full parsed 402 challenge so callers can inspect or
|
|
73
|
+
settle it themselves. Raised when no signer is configured, when the
|
|
74
|
+
price exceeds the spend guard, or when a paid retry still gets a 402.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, challenge: dict, reason: str):
|
|
78
|
+
super().__init__(reason)
|
|
79
|
+
self.challenge = challenge
|
|
80
|
+
self.reason = reason
|
|
81
|
+
|
|
82
|
+
def structured_error(self) -> dict:
|
|
83
|
+
"""The challenge as a JSON-friendly structured error object."""
|
|
84
|
+
return {
|
|
85
|
+
"error": "payment_required",
|
|
86
|
+
"reason": self.reason,
|
|
87
|
+
"x402Version": self.challenge.get("x402Version"),
|
|
88
|
+
"resource": self.challenge.get("resource"),
|
|
89
|
+
"accepts": self.challenge.get("accepts"),
|
|
90
|
+
"extensions": self.challenge.get("extensions"),
|
|
91
|
+
"hint": (
|
|
92
|
+
"Token Verdict costs $0.02 USDC per call on Base (x402). "
|
|
93
|
+
"Configure AGENT_PRIVATE_KEY or AGENT_KEY_FILE with an EVM "
|
|
94
|
+
"wallet holding USDC on Base and the call will be paid "
|
|
95
|
+
"automatically, or settle this challenge with any x402 v2 "
|
|
96
|
+
"client and retry."
|
|
97
|
+
),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_payment_required(response: httpx.Response) -> dict:
|
|
102
|
+
"""Parse the x402 v2 challenge from a 402 response.
|
|
103
|
+
|
|
104
|
+
The challenge travels base64-encoded in the `payment-required`
|
|
105
|
+
header; some stacks also put it in the JSON body. Raises ValueError
|
|
106
|
+
when neither carries a usable challenge.
|
|
107
|
+
"""
|
|
108
|
+
header = response.headers.get("payment-required")
|
|
109
|
+
if header:
|
|
110
|
+
try:
|
|
111
|
+
decoded = json.loads(base64.b64decode(header).decode("utf-8"))
|
|
112
|
+
if isinstance(decoded, dict) and decoded.get("accepts"):
|
|
113
|
+
return decoded
|
|
114
|
+
except (ValueError, UnicodeDecodeError):
|
|
115
|
+
pass
|
|
116
|
+
try:
|
|
117
|
+
body = response.json()
|
|
118
|
+
except ValueError:
|
|
119
|
+
body = None
|
|
120
|
+
if isinstance(body, dict) and body.get("accepts"):
|
|
121
|
+
return body
|
|
122
|
+
raise ValueError("402 response carried no parseable x402 payment challenge")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def select_requirement(
|
|
126
|
+
challenge: dict, network: str = BASE_NETWORK, scheme: str = "exact"
|
|
127
|
+
) -> dict:
|
|
128
|
+
"""Pick the accepts entry this client can settle (exact EVM on Base)."""
|
|
129
|
+
for entry in challenge.get("accepts") or []:
|
|
130
|
+
if entry.get("scheme") == scheme and entry.get("network") == network:
|
|
131
|
+
return entry
|
|
132
|
+
raise ValueError(
|
|
133
|
+
f"challenge offers no {scheme} requirement on {network}: "
|
|
134
|
+
f"{[ (a.get('scheme'), a.get('network')) for a in challenge.get('accepts') or [] ]}"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def build_authorization(
|
|
139
|
+
from_address: str,
|
|
140
|
+
requirement: dict,
|
|
141
|
+
*,
|
|
142
|
+
now: int | None = None,
|
|
143
|
+
nonce: str | None = None,
|
|
144
|
+
) -> dict:
|
|
145
|
+
"""EIP-3009 authorization, string fields exactly as @x402/evm builds."""
|
|
146
|
+
now = int(time.time()) if now is None else now
|
|
147
|
+
return {
|
|
148
|
+
"from": from_address,
|
|
149
|
+
"to": requirement["payTo"],
|
|
150
|
+
"value": str(requirement["amount"]),
|
|
151
|
+
"validAfter": "0",
|
|
152
|
+
"validBefore": str(now + int(requirement.get("maxTimeoutSeconds", 300))),
|
|
153
|
+
"nonce": nonce or ("0x" + secrets.token_hex(32)),
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def sign_authorization(
|
|
158
|
+
account: LocalAccount, requirement: dict, authorization: dict
|
|
159
|
+
) -> str:
|
|
160
|
+
"""EIP-712 sign the TransferWithAuthorization against the USDC domain
|
|
161
|
+
the challenge advertises in accepts.extra (name/version)."""
|
|
162
|
+
extra = requirement.get("extra") or {}
|
|
163
|
+
if not extra.get("name") or not extra.get("version"):
|
|
164
|
+
raise ValueError(
|
|
165
|
+
"payment requirement is missing EIP-712 domain parameters "
|
|
166
|
+
f"(extra.name/extra.version) for asset {requirement.get('asset')}"
|
|
167
|
+
)
|
|
168
|
+
network = requirement.get("network", BASE_NETWORK)
|
|
169
|
+
if not network.startswith("eip155:"):
|
|
170
|
+
raise ValueError(f"unsupported network for EVM signing: {network}")
|
|
171
|
+
domain = {
|
|
172
|
+
"name": extra["name"],
|
|
173
|
+
"version": extra["version"],
|
|
174
|
+
"chainId": int(network.split(":", 1)[1]),
|
|
175
|
+
"verifyingContract": requirement["asset"],
|
|
176
|
+
}
|
|
177
|
+
message = {
|
|
178
|
+
"from": authorization["from"],
|
|
179
|
+
"to": authorization["to"],
|
|
180
|
+
"value": int(authorization["value"]),
|
|
181
|
+
"validAfter": int(authorization["validAfter"]),
|
|
182
|
+
"validBefore": int(authorization["validBefore"]),
|
|
183
|
+
"nonce": bytes.fromhex(authorization["nonce"].removeprefix("0x")),
|
|
184
|
+
}
|
|
185
|
+
signed = account.sign_typed_data(
|
|
186
|
+
domain_data=domain,
|
|
187
|
+
message_types=TRANSFER_WITH_AUTHORIZATION_TYPES,
|
|
188
|
+
message_data=message,
|
|
189
|
+
)
|
|
190
|
+
return signed.signature.hex() if signed.signature.hex().startswith("0x") else "0x" + signed.signature.hex()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_payment_payload(
|
|
194
|
+
challenge: dict, requirement: dict, authorization: dict, signature: str
|
|
195
|
+
) -> dict:
|
|
196
|
+
"""The x402 v2 PaymentPayload the retry carries."""
|
|
197
|
+
return {
|
|
198
|
+
"x402Version": challenge.get("x402Version", 2),
|
|
199
|
+
"resource": challenge.get("resource"),
|
|
200
|
+
"accepted": requirement,
|
|
201
|
+
"payload": {"authorization": authorization, "signature": signature},
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def encode_payment_header(payload: dict) -> str:
|
|
206
|
+
return base64.b64encode(
|
|
207
|
+
json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
208
|
+
).decode("ascii")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def decode_receipt(response: httpx.Response) -> dict | None:
|
|
212
|
+
"""Decode the base64 `payment-response` settlement receipt, if any."""
|
|
213
|
+
raw = response.headers.get("payment-response")
|
|
214
|
+
if not raw:
|
|
215
|
+
return None
|
|
216
|
+
try:
|
|
217
|
+
return json.loads(base64.b64decode(raw).decode("utf-8"))
|
|
218
|
+
except (ValueError, UnicodeDecodeError):
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def load_account_from_env(env: dict | None = None) -> LocalAccount | None:
|
|
223
|
+
"""Build the signer from the operator's OWN environment.
|
|
224
|
+
|
|
225
|
+
AGENT_PRIVATE_KEY: a 0x-prefixed EVM private key.
|
|
226
|
+
AGENT_KEY_FILE: path to a file whose contents are that key.
|
|
227
|
+
Returns None when neither is set — callers then never pay.
|
|
228
|
+
"""
|
|
229
|
+
env = os.environ if env is None else env
|
|
230
|
+
key = (env.get("AGENT_PRIVATE_KEY") or "").strip()
|
|
231
|
+
if not key:
|
|
232
|
+
key_file = (env.get("AGENT_KEY_FILE") or "").strip()
|
|
233
|
+
if key_file:
|
|
234
|
+
key = Path(key_file).read_text(encoding="utf-8").strip()
|
|
235
|
+
if not key:
|
|
236
|
+
return None
|
|
237
|
+
if not key.startswith("0x"):
|
|
238
|
+
key = "0x" + key
|
|
239
|
+
return Account.from_key(key)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class TokenVerdictClient:
|
|
243
|
+
"""Synchronous Token Verdict client with automatic x402 payment."""
|
|
244
|
+
|
|
245
|
+
def __init__(
|
|
246
|
+
self,
|
|
247
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
248
|
+
account: LocalAccount | None = None,
|
|
249
|
+
*,
|
|
250
|
+
http: httpx.Client | None = None,
|
|
251
|
+
max_amount_units: int = DEFAULT_MAX_AMOUNT_UNITS,
|
|
252
|
+
timeout: float = 30.0,
|
|
253
|
+
):
|
|
254
|
+
self.base_url = base_url.rstrip("/")
|
|
255
|
+
self.account = account
|
|
256
|
+
self.max_amount_units = max_amount_units
|
|
257
|
+
self._http = http or httpx.Client(timeout=timeout)
|
|
258
|
+
self.last_receipt: dict | None = None
|
|
259
|
+
|
|
260
|
+
def get_verdict(self, address: str, chain: str = "base") -> dict:
|
|
261
|
+
"""POST /v1/verdict, paying the 402 challenge when a signer is
|
|
262
|
+
configured. Returns the verdict JSON (see schemas.py)."""
|
|
263
|
+
url = self.base_url + VERDICT_PATH
|
|
264
|
+
body = {"address": address, "chain": chain}
|
|
265
|
+
response = self._http.post(url, json=body)
|
|
266
|
+
if response.status_code == 200:
|
|
267
|
+
self.last_receipt = decode_receipt(response)
|
|
268
|
+
return response.json()
|
|
269
|
+
if response.status_code != 402:
|
|
270
|
+
raise TokenVerdictError(response.status_code, _safe_json(response))
|
|
271
|
+
|
|
272
|
+
challenge = parse_payment_required(response)
|
|
273
|
+
if self.account is None:
|
|
274
|
+
raise PaymentRequiredError(
|
|
275
|
+
challenge,
|
|
276
|
+
"payment required and no signer configured "
|
|
277
|
+
"(set AGENT_PRIVATE_KEY or AGENT_KEY_FILE)",
|
|
278
|
+
)
|
|
279
|
+
requirement = select_requirement(challenge)
|
|
280
|
+
amount = int(requirement["amount"])
|
|
281
|
+
if amount > self.max_amount_units:
|
|
282
|
+
raise PaymentRequiredError(
|
|
283
|
+
challenge,
|
|
284
|
+
f"price {amount} units exceeds spend guard "
|
|
285
|
+
f"{self.max_amount_units} units; refusing to sign",
|
|
286
|
+
)
|
|
287
|
+
authorization = build_authorization(self.account.address, requirement)
|
|
288
|
+
signature = sign_authorization(self.account, requirement, authorization)
|
|
289
|
+
payload = build_payment_payload(challenge, requirement, authorization, signature)
|
|
290
|
+
paid = self._http.post(
|
|
291
|
+
url,
|
|
292
|
+
json=body,
|
|
293
|
+
headers={"PAYMENT-SIGNATURE": encode_payment_header(payload)},
|
|
294
|
+
)
|
|
295
|
+
if paid.status_code == 200:
|
|
296
|
+
self.last_receipt = decode_receipt(paid)
|
|
297
|
+
return paid.json()
|
|
298
|
+
if paid.status_code == 402:
|
|
299
|
+
raise PaymentRequiredError(
|
|
300
|
+
parse_payment_required(paid),
|
|
301
|
+
"paid retry still returned 402 (settlement rejected)",
|
|
302
|
+
)
|
|
303
|
+
raise TokenVerdictError(paid.status_code, _safe_json(paid))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _safe_json(response: httpx.Response) -> Any:
|
|
307
|
+
try:
|
|
308
|
+
return response.json()
|
|
309
|
+
except ValueError:
|
|
310
|
+
return response.text[:500]
|