code-review-validator 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.
- code_review_validator-0.1.0/LICENSE +21 -0
- code_review_validator-0.1.0/PKG-INFO +104 -0
- code_review_validator-0.1.0/README.md +70 -0
- code_review_validator-0.1.0/pyproject.toml +66 -0
- code_review_validator-0.1.0/setup.cfg +4 -0
- code_review_validator-0.1.0/src/code_review_validator/__init__.py +92 -0
- code_review_validator-0.1.0/src/code_review_validator/_verify.py +48 -0
- code_review_validator-0.1.0/src/code_review_validator/client.py +242 -0
- code_review_validator-0.1.0/src/code_review_validator/errors.py +84 -0
- code_review_validator-0.1.0/src/code_review_validator/gate.py +119 -0
- code_review_validator-0.1.0/src/code_review_validator/models.py +106 -0
- code_review_validator-0.1.0/src/code_review_validator/py.typed +0 -0
- code_review_validator-0.1.0/src/code_review_validator.egg-info/PKG-INFO +104 -0
- code_review_validator-0.1.0/src/code_review_validator.egg-info/SOURCES.txt +19 -0
- code_review_validator-0.1.0/src/code_review_validator.egg-info/dependency_links.txt +1 -0
- code_review_validator-0.1.0/src/code_review_validator.egg-info/requires.txt +11 -0
- code_review_validator-0.1.0/src/code_review_validator.egg-info/top_level.txt +1 -0
- code_review_validator-0.1.0/tests/test_client.py +195 -0
- code_review_validator-0.1.0/tests/test_gate.py +118 -0
- code_review_validator-0.1.0/tests/test_models.py +58 -0
- code_review_validator-0.1.0/tests/test_verify.py +54 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Code Review Validator contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: code-review-validator
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the Code Review Validator API
|
|
5
|
+
Author: Code Review Validator
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://code-review-validator.fly.dev
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/danielpwhite/code-review-validator
|
|
9
|
+
Project-URL: Documentation, https://gitlab.com/danielpwhite/code-review-validator/-/blob/master/sdk/python/README.md
|
|
10
|
+
Keywords: solidity,smart-contract,security,attestation,erc-8004,web3
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: httpx>=0.27.0
|
|
25
|
+
Requires-Dist: pydantic>=2.0.0
|
|
26
|
+
Provides-Extra: crypto
|
|
27
|
+
Requires-Dist: eciespy>=0.4.0; extra == "crypto"
|
|
28
|
+
Requires-Dist: coincurve>=20.0.0; extra == "crypto"
|
|
29
|
+
Requires-Dist: web3>=7.6.0; extra == "crypto"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
32
|
+
Requires-Dist: anyio>=4.0.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# code-review-validator (Python SDK)
|
|
36
|
+
|
|
37
|
+
Python client for the Code Review Validator API.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install code-review-validator
|
|
43
|
+
# Optional crypto helpers
|
|
44
|
+
pip install "code-review-validator[crypto]"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Development Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install -e .
|
|
51
|
+
pip install -e ".[dev]"
|
|
52
|
+
# Optional crypto helpers while developing
|
|
53
|
+
pip install -e ".[dev,crypto]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Quickstart (async)
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from code_review_validator import AsyncClient
|
|
60
|
+
|
|
61
|
+
async def main() -> None:
|
|
62
|
+
async with AsyncClient(api_key="your-key") as client:
|
|
63
|
+
review = await client.review("contract C {}")
|
|
64
|
+
print(review.score, review.evidence_level)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Quickstart (sync)
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from code_review_validator import SyncClient
|
|
71
|
+
|
|
72
|
+
with SyncClient(api_key="your-key") as client:
|
|
73
|
+
review = client.review("contract C {}")
|
|
74
|
+
print(review.score, review.attestation_status)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## CI Gate
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from code_review_validator import GatePolicy, check_contract
|
|
81
|
+
|
|
82
|
+
policy = GatePolicy(min_score=80)
|
|
83
|
+
result = check_contract("contract C {}", api_key="your-key", policy=policy)
|
|
84
|
+
if not result.passed:
|
|
85
|
+
raise SystemExit(1)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Optional Crypto Helpers
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from code_review_validator import verify_response_hash, decrypt_findings
|
|
92
|
+
|
|
93
|
+
ok = verify_response_hash(ipfs_payload, on_chain_hash)
|
|
94
|
+
findings = decrypt_findings(ipfs_payload, private_key_hex)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Manual Publish Fallback
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
pip install build twine
|
|
101
|
+
cd sdk/python
|
|
102
|
+
python -m build
|
|
103
|
+
TWINE_USERNAME=__token__ TWINE_PASSWORD="$PYPI_TOKEN" twine upload dist/*
|
|
104
|
+
```
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# code-review-validator (Python SDK)
|
|
2
|
+
|
|
3
|
+
Python client for the Code Review Validator API.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install code-review-validator
|
|
9
|
+
# Optional crypto helpers
|
|
10
|
+
pip install "code-review-validator[crypto]"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Development Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install -e .
|
|
17
|
+
pip install -e ".[dev]"
|
|
18
|
+
# Optional crypto helpers while developing
|
|
19
|
+
pip install -e ".[dev,crypto]"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Quickstart (async)
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from code_review_validator import AsyncClient
|
|
26
|
+
|
|
27
|
+
async def main() -> None:
|
|
28
|
+
async with AsyncClient(api_key="your-key") as client:
|
|
29
|
+
review = await client.review("contract C {}")
|
|
30
|
+
print(review.score, review.evidence_level)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quickstart (sync)
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from code_review_validator import SyncClient
|
|
37
|
+
|
|
38
|
+
with SyncClient(api_key="your-key") as client:
|
|
39
|
+
review = client.review("contract C {}")
|
|
40
|
+
print(review.score, review.attestation_status)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## CI Gate
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from code_review_validator import GatePolicy, check_contract
|
|
47
|
+
|
|
48
|
+
policy = GatePolicy(min_score=80)
|
|
49
|
+
result = check_contract("contract C {}", api_key="your-key", policy=policy)
|
|
50
|
+
if not result.passed:
|
|
51
|
+
raise SystemExit(1)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Optional Crypto Helpers
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from code_review_validator import verify_response_hash, decrypt_findings
|
|
58
|
+
|
|
59
|
+
ok = verify_response_hash(ipfs_payload, on_chain_hash)
|
|
60
|
+
findings = decrypt_findings(ipfs_payload, private_key_hex)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Manual Publish Fallback
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install build twine
|
|
67
|
+
cd sdk/python
|
|
68
|
+
python -m build
|
|
69
|
+
TWINE_USERNAME=__token__ TWINE_PASSWORD="$PYPI_TOKEN" twine upload dist/*
|
|
70
|
+
```
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "code-review-validator"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK for the Code Review Validator API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Code Review Validator" },
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"solidity",
|
|
17
|
+
"smart-contract",
|
|
18
|
+
"security",
|
|
19
|
+
"attestation",
|
|
20
|
+
"erc-8004",
|
|
21
|
+
"web3",
|
|
22
|
+
]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 3 - Alpha",
|
|
25
|
+
"Intended Audience :: Developers",
|
|
26
|
+
"License :: OSI Approved :: MIT License",
|
|
27
|
+
"Programming Language :: Python :: 3",
|
|
28
|
+
"Programming Language :: Python :: 3.11",
|
|
29
|
+
"Programming Language :: Python :: 3.12",
|
|
30
|
+
"Programming Language :: Python :: 3.13",
|
|
31
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
32
|
+
"Topic :: Security",
|
|
33
|
+
"Typing :: Typed",
|
|
34
|
+
]
|
|
35
|
+
dependencies = [
|
|
36
|
+
"httpx>=0.27.0",
|
|
37
|
+
"pydantic>=2.0.0",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://code-review-validator.fly.dev"
|
|
42
|
+
Repository = "https://gitlab.com/danielpwhite/code-review-validator"
|
|
43
|
+
Documentation = "https://gitlab.com/danielpwhite/code-review-validator/-/blob/master/sdk/python/README.md"
|
|
44
|
+
|
|
45
|
+
[project.optional-dependencies]
|
|
46
|
+
crypto = [
|
|
47
|
+
"eciespy>=0.4.0",
|
|
48
|
+
"coincurve>=20.0.0",
|
|
49
|
+
"web3>=7.6.0",
|
|
50
|
+
]
|
|
51
|
+
dev = [
|
|
52
|
+
"pytest>=8.0.0",
|
|
53
|
+
"anyio>=4.0.0",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
[tool.setuptools]
|
|
57
|
+
license-files = ["LICENSE"]
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.packages.find]
|
|
60
|
+
where = ["src"]
|
|
61
|
+
|
|
62
|
+
[tool.setuptools.package-data]
|
|
63
|
+
code_review_validator = ["py.typed"]
|
|
64
|
+
|
|
65
|
+
[tool.pytest.ini_options]
|
|
66
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Public SDK surface for code-review-validator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError
|
|
6
|
+
from importlib.metadata import version as _pkg_version
|
|
7
|
+
|
|
8
|
+
from .client import AsyncClient, SyncClient
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
ConnectionError,
|
|
14
|
+
CryptoNotAvailableError,
|
|
15
|
+
PaymentRequiredError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
ServiceUnavailableError,
|
|
18
|
+
TimeoutError,
|
|
19
|
+
ValidatorError,
|
|
20
|
+
)
|
|
21
|
+
from .gate import GateCheck, GatePolicy, GateResult, check_contract, evaluate
|
|
22
|
+
from .models import (
|
|
23
|
+
AttestationStatus,
|
|
24
|
+
EvidenceLevel,
|
|
25
|
+
Finding,
|
|
26
|
+
HealthResult,
|
|
27
|
+
OnChainStatus,
|
|
28
|
+
ReputationResult,
|
|
29
|
+
ReviewResult,
|
|
30
|
+
Severity,
|
|
31
|
+
StatsResult,
|
|
32
|
+
StatusResult,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
__version__ = _pkg_version("code-review-validator")
|
|
37
|
+
except PackageNotFoundError:
|
|
38
|
+
__version__ = "0.1.0"
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
from ._verify import canonical_serialize, decrypt_findings, verify_response_hash
|
|
42
|
+
except Exception as exc: # pragma: no cover - exercised via fallback wrappers
|
|
43
|
+
_CRYPTO_IMPORT_ERROR = exc
|
|
44
|
+
|
|
45
|
+
def _raise_crypto_error() -> None:
|
|
46
|
+
raise CryptoNotAvailableError(
|
|
47
|
+
"Crypto helpers require optional dependencies. Install with [crypto]."
|
|
48
|
+
) from _CRYPTO_IMPORT_ERROR
|
|
49
|
+
|
|
50
|
+
def canonical_serialize(data: dict) -> bytes: # type: ignore[override]
|
|
51
|
+
_raise_crypto_error()
|
|
52
|
+
|
|
53
|
+
def verify_response_hash(ipfs_payload: dict, on_chain_hash: str) -> bool: # type: ignore[override]
|
|
54
|
+
_raise_crypto_error()
|
|
55
|
+
|
|
56
|
+
def decrypt_findings(encrypted_payload: dict, private_key_hex: str) -> dict: # type: ignore[override]
|
|
57
|
+
_raise_crypto_error()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"APIError",
|
|
62
|
+
"AsyncClient",
|
|
63
|
+
"AttestationStatus",
|
|
64
|
+
"AuthenticationError",
|
|
65
|
+
"BadRequestError",
|
|
66
|
+
"ConnectionError",
|
|
67
|
+
"CryptoNotAvailableError",
|
|
68
|
+
"EvidenceLevel",
|
|
69
|
+
"Finding",
|
|
70
|
+
"GateCheck",
|
|
71
|
+
"GatePolicy",
|
|
72
|
+
"GateResult",
|
|
73
|
+
"HealthResult",
|
|
74
|
+
"OnChainStatus",
|
|
75
|
+
"PaymentRequiredError",
|
|
76
|
+
"RateLimitError",
|
|
77
|
+
"ReputationResult",
|
|
78
|
+
"ReviewResult",
|
|
79
|
+
"ServiceUnavailableError",
|
|
80
|
+
"Severity",
|
|
81
|
+
"StatsResult",
|
|
82
|
+
"StatusResult",
|
|
83
|
+
"SyncClient",
|
|
84
|
+
"TimeoutError",
|
|
85
|
+
"ValidatorError",
|
|
86
|
+
"__version__",
|
|
87
|
+
"canonical_serialize",
|
|
88
|
+
"check_contract",
|
|
89
|
+
"decrypt_findings",
|
|
90
|
+
"evaluate",
|
|
91
|
+
"verify_response_hash",
|
|
92
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Optional crypto helpers for payload verification and decryption."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .errors import CryptoNotAvailableError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _normalize_hex(value: str) -> str:
|
|
11
|
+
return value.removeprefix("0x")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def canonical_serialize(data: dict) -> bytes:
|
|
15
|
+
"""Deterministic JSON encoding used for hashing."""
|
|
16
|
+
return json.dumps(data, sort_keys=True, separators=(",", ":")).encode()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def verify_response_hash(ipfs_payload: dict, on_chain_hash: str) -> bool:
|
|
20
|
+
"""Verify that payload hash matches on-chain response hash."""
|
|
21
|
+
try:
|
|
22
|
+
from web3 import Web3
|
|
23
|
+
except Exception as exc:
|
|
24
|
+
raise CryptoNotAvailableError(
|
|
25
|
+
"web3 is required for verify_response_hash. Install with [crypto]."
|
|
26
|
+
) from exc
|
|
27
|
+
|
|
28
|
+
computed = Web3.keccak(canonical_serialize(ipfs_payload)).hex()
|
|
29
|
+
return _normalize_hex(computed).lower() == _normalize_hex(on_chain_hash).lower()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def decrypt_findings(encrypted_payload: dict, private_key_hex: str) -> dict:
|
|
33
|
+
"""Decrypt findings payload using a secp256k1 private key."""
|
|
34
|
+
try:
|
|
35
|
+
import ecies
|
|
36
|
+
except Exception as exc:
|
|
37
|
+
raise CryptoNotAvailableError(
|
|
38
|
+
"eciespy is required for decrypt_findings. Install with [crypto]."
|
|
39
|
+
) from exc
|
|
40
|
+
|
|
41
|
+
encrypted_section = encrypted_payload.get("encrypted", encrypted_payload)
|
|
42
|
+
ciphertext_hex = encrypted_section.get("ciphertext")
|
|
43
|
+
if not isinstance(ciphertext_hex, str):
|
|
44
|
+
raise ValueError("encrypted payload is missing a hex ciphertext field")
|
|
45
|
+
|
|
46
|
+
ciphertext = bytes.fromhex(_normalize_hex(ciphertext_hex))
|
|
47
|
+
plaintext = ecies.decrypt(_normalize_hex(private_key_hex), ciphertext)
|
|
48
|
+
return json.loads(plaintext)
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""HTTP clients for the Code Review Validator API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
AuthenticationError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
ConnectionError,
|
|
14
|
+
PaymentRequiredError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ServiceUnavailableError,
|
|
17
|
+
TimeoutError,
|
|
18
|
+
parse_error_detail,
|
|
19
|
+
)
|
|
20
|
+
from .models import HealthResult, ReputationResult, ReviewResult, StatsResult, StatusResult
|
|
21
|
+
|
|
22
|
+
_DEFAULT_BASE_URL = "https://code-review-validator.fly.dev"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _extract_remaining_reviews(headers: httpx.Headers) -> int | None:
|
|
26
|
+
value = headers.get("X-API-Key-Remaining") or headers.get("X-Free-Tier-Remaining")
|
|
27
|
+
if value is None:
|
|
28
|
+
return None
|
|
29
|
+
try:
|
|
30
|
+
return int(value)
|
|
31
|
+
except ValueError:
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _retry_after(headers: httpx.Headers) -> int | None:
|
|
36
|
+
raw = headers.get("Retry-After")
|
|
37
|
+
if raw is None:
|
|
38
|
+
return None
|
|
39
|
+
try:
|
|
40
|
+
return int(raw)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _raise_for_response(response: httpx.Response) -> None:
|
|
46
|
+
if response.status_code < 400:
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
payload = response.json()
|
|
51
|
+
except ValueError:
|
|
52
|
+
payload = None
|
|
53
|
+
|
|
54
|
+
fallback = response.text.strip() or "Request failed"
|
|
55
|
+
detail = parse_error_detail(payload, fallback)
|
|
56
|
+
status_code = response.status_code
|
|
57
|
+
|
|
58
|
+
if status_code == 400:
|
|
59
|
+
raise BadRequestError(status_code, detail, response)
|
|
60
|
+
if status_code == 401:
|
|
61
|
+
raise AuthenticationError(status_code, detail, response)
|
|
62
|
+
if status_code == 402:
|
|
63
|
+
raise PaymentRequiredError(status_code, detail, response)
|
|
64
|
+
if status_code == 429:
|
|
65
|
+
raise RateLimitError(
|
|
66
|
+
status_code,
|
|
67
|
+
detail,
|
|
68
|
+
response,
|
|
69
|
+
retry_after=_retry_after(response.headers),
|
|
70
|
+
)
|
|
71
|
+
if status_code == 503:
|
|
72
|
+
raise ServiceUnavailableError(status_code, detail, response)
|
|
73
|
+
if status_code == 504:
|
|
74
|
+
raise TimeoutError(detail)
|
|
75
|
+
|
|
76
|
+
raise APIError(status_code, detail, response)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AsyncClient:
|
|
80
|
+
"""Async SDK client."""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
base_url: str = _DEFAULT_BASE_URL,
|
|
85
|
+
api_key: str | None = None,
|
|
86
|
+
timeout: float = 120.0,
|
|
87
|
+
_client: httpx.AsyncClient | None = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
self._owns_client = _client is None
|
|
90
|
+
if _client is None:
|
|
91
|
+
headers = {"X-API-Key": api_key} if api_key else None
|
|
92
|
+
self._client = httpx.AsyncClient(
|
|
93
|
+
base_url=base_url.rstrip("/"),
|
|
94
|
+
timeout=timeout,
|
|
95
|
+
headers=headers,
|
|
96
|
+
)
|
|
97
|
+
else:
|
|
98
|
+
self._client = _client
|
|
99
|
+
if api_key:
|
|
100
|
+
self._client.headers.setdefault("X-API-Key", api_key)
|
|
101
|
+
|
|
102
|
+
async def __aenter__(self) -> AsyncClient:
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
106
|
+
await self.close()
|
|
107
|
+
|
|
108
|
+
async def close(self) -> None:
|
|
109
|
+
if self._owns_client:
|
|
110
|
+
await self._client.aclose()
|
|
111
|
+
|
|
112
|
+
async def _request(self, method: str, path: str, *, json: dict[str, Any] | None = None) -> httpx.Response:
|
|
113
|
+
try:
|
|
114
|
+
response = await self._client.request(method, path, json=json)
|
|
115
|
+
except httpx.TimeoutException as exc:
|
|
116
|
+
raise TimeoutError(str(exc) or "Request timed out") from exc
|
|
117
|
+
except httpx.RequestError as exc:
|
|
118
|
+
raise ConnectionError(str(exc) or "Request failed") from exc
|
|
119
|
+
|
|
120
|
+
_raise_for_response(response)
|
|
121
|
+
return response
|
|
122
|
+
|
|
123
|
+
async def review(
|
|
124
|
+
self,
|
|
125
|
+
code: str,
|
|
126
|
+
*,
|
|
127
|
+
language: str = "solidity",
|
|
128
|
+
review_type: str = "security",
|
|
129
|
+
context: str = "",
|
|
130
|
+
encryption_key: str | None = None,
|
|
131
|
+
) -> ReviewResult:
|
|
132
|
+
payload: dict[str, Any] = {
|
|
133
|
+
"code": code,
|
|
134
|
+
"language": language,
|
|
135
|
+
"reviewType": review_type,
|
|
136
|
+
"context": context,
|
|
137
|
+
}
|
|
138
|
+
if encryption_key is not None:
|
|
139
|
+
payload["encryptionKey"] = encryption_key
|
|
140
|
+
|
|
141
|
+
response = await self._request("POST", "/review/", json=payload)
|
|
142
|
+
result = ReviewResult.model_validate(response.json())
|
|
143
|
+
return result.model_copy(update={"remaining_reviews": _extract_remaining_reviews(response.headers)})
|
|
144
|
+
|
|
145
|
+
async def status(self, request_hash: str) -> StatusResult:
|
|
146
|
+
response = await self._request("GET", f"/status/{request_hash}")
|
|
147
|
+
return StatusResult.model_validate(response.json())
|
|
148
|
+
|
|
149
|
+
async def reputation(self, agent_id: int) -> ReputationResult:
|
|
150
|
+
response = await self._request("GET", f"/reputation/{agent_id}")
|
|
151
|
+
return ReputationResult.model_validate(response.json())
|
|
152
|
+
|
|
153
|
+
async def health(self) -> HealthResult:
|
|
154
|
+
response = await self._request("GET", "/health")
|
|
155
|
+
return HealthResult.model_validate(response.json())
|
|
156
|
+
|
|
157
|
+
async def stats(self) -> StatsResult:
|
|
158
|
+
response = await self._request("GET", "/stats/")
|
|
159
|
+
return StatsResult.model_validate(response.json())
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class SyncClient:
|
|
163
|
+
"""Synchronous SDK client."""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
base_url: str = _DEFAULT_BASE_URL,
|
|
168
|
+
api_key: str | None = None,
|
|
169
|
+
timeout: float = 120.0,
|
|
170
|
+
_client: httpx.Client | None = None,
|
|
171
|
+
) -> None:
|
|
172
|
+
self._owns_client = _client is None
|
|
173
|
+
if _client is None:
|
|
174
|
+
headers = {"X-API-Key": api_key} if api_key else None
|
|
175
|
+
self._client = httpx.Client(
|
|
176
|
+
base_url=base_url.rstrip("/"),
|
|
177
|
+
timeout=timeout,
|
|
178
|
+
headers=headers,
|
|
179
|
+
)
|
|
180
|
+
else:
|
|
181
|
+
self._client = _client
|
|
182
|
+
if api_key:
|
|
183
|
+
self._client.headers.setdefault("X-API-Key", api_key)
|
|
184
|
+
|
|
185
|
+
def __enter__(self) -> SyncClient:
|
|
186
|
+
return self
|
|
187
|
+
|
|
188
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
189
|
+
self.close()
|
|
190
|
+
|
|
191
|
+
def close(self) -> None:
|
|
192
|
+
if self._owns_client:
|
|
193
|
+
self._client.close()
|
|
194
|
+
|
|
195
|
+
def _request(self, method: str, path: str, *, json: dict[str, Any] | None = None) -> httpx.Response:
|
|
196
|
+
try:
|
|
197
|
+
response = self._client.request(method, path, json=json)
|
|
198
|
+
except httpx.TimeoutException as exc:
|
|
199
|
+
raise TimeoutError(str(exc) or "Request timed out") from exc
|
|
200
|
+
except httpx.RequestError as exc:
|
|
201
|
+
raise ConnectionError(str(exc) or "Request failed") from exc
|
|
202
|
+
|
|
203
|
+
_raise_for_response(response)
|
|
204
|
+
return response
|
|
205
|
+
|
|
206
|
+
def review(
|
|
207
|
+
self,
|
|
208
|
+
code: str,
|
|
209
|
+
*,
|
|
210
|
+
language: str = "solidity",
|
|
211
|
+
review_type: str = "security",
|
|
212
|
+
context: str = "",
|
|
213
|
+
encryption_key: str | None = None,
|
|
214
|
+
) -> ReviewResult:
|
|
215
|
+
payload: dict[str, Any] = {
|
|
216
|
+
"code": code,
|
|
217
|
+
"language": language,
|
|
218
|
+
"reviewType": review_type,
|
|
219
|
+
"context": context,
|
|
220
|
+
}
|
|
221
|
+
if encryption_key is not None:
|
|
222
|
+
payload["encryptionKey"] = encryption_key
|
|
223
|
+
|
|
224
|
+
response = self._request("POST", "/review/", json=payload)
|
|
225
|
+
result = ReviewResult.model_validate(response.json())
|
|
226
|
+
return result.model_copy(update={"remaining_reviews": _extract_remaining_reviews(response.headers)})
|
|
227
|
+
|
|
228
|
+
def status(self, request_hash: str) -> StatusResult:
|
|
229
|
+
response = self._request("GET", f"/status/{request_hash}")
|
|
230
|
+
return StatusResult.model_validate(response.json())
|
|
231
|
+
|
|
232
|
+
def reputation(self, agent_id: int) -> ReputationResult:
|
|
233
|
+
response = self._request("GET", f"/reputation/{agent_id}")
|
|
234
|
+
return ReputationResult.model_validate(response.json())
|
|
235
|
+
|
|
236
|
+
def health(self) -> HealthResult:
|
|
237
|
+
response = self._request("GET", "/health")
|
|
238
|
+
return HealthResult.model_validate(response.json())
|
|
239
|
+
|
|
240
|
+
def stats(self) -> StatsResult:
|
|
241
|
+
response = self._request("GET", "/stats/")
|
|
242
|
+
return StatsResult.model_validate(response.json())
|