ctcc-x402 1.0.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.
ctcc_x402/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ ctcc-x402 - Python SDK for CTCC™ (Cinqueport Token Control Check)
3
+ """
4
+
5
+ from .models import (
6
+ CtccObservationResponse,
7
+ CtccObservations,
8
+ Erc20Signals,
9
+ ControlAuthorities,
10
+ PauseState,
11
+ ProxyIndicators
12
+ )
13
+ from .client import (
14
+ CtccClient,
15
+ AsyncCtccClient,
16
+ check_token_control,
17
+ check_token_control_async,
18
+ DEFAULT_CTCC_ENDPOINT
19
+ )
20
+
21
+ __all__ = [
22
+ "CtccClient",
23
+ "AsyncCtccClient",
24
+ "check_token_control",
25
+ "check_token_control_async",
26
+ "CtccObservationResponse",
27
+ "CtccObservations",
28
+ "Erc20Signals",
29
+ "ControlAuthorities",
30
+ "PauseState",
31
+ "ProxyIndicators",
32
+ "DEFAULT_CTCC_ENDPOINT"
33
+ ]
ctcc_x402/client.py ADDED
@@ -0,0 +1,192 @@
1
+ """
2
+ Synchronous and Asynchronous Clients for CTCC™ (Cinqueport Token Control Check)
3
+ """
4
+
5
+ import time
6
+ import re
7
+ from typing import Optional, Dict, Any, Tuple
8
+ import requests
9
+ import httpx
10
+
11
+ from .models import CtccObservationResponse
12
+
13
+ DEFAULT_CTCC_ENDPOINT = "https://cinqueport.net/check"
14
+ ADDRESS_REGEX = re.compile(r"^0x[a-fA-F0-9]{40}$")
15
+
16
+
17
+ class CtccClient:
18
+ """Synchronous CTCC client with optional in-memory TTL caching and retry logic."""
19
+
20
+ def __init__(
21
+ self,
22
+ endpoint: str = DEFAULT_CTCC_ENDPOINT,
23
+ private_key: Optional[str] = None,
24
+ cache_ttl_seconds: int = 0,
25
+ max_retries: int = 2,
26
+ retry_delay_seconds: float = 0.5,
27
+ session: Optional[requests.Session] = None
28
+ ):
29
+ self.endpoint = endpoint
30
+ self.private_key = private_key
31
+ self.cache_ttl = cache_ttl_seconds
32
+ self.max_retries = max_retries
33
+ self.retry_delay = retry_delay_seconds
34
+ self.session = session or requests.Session()
35
+ self._cache: Dict[str, Tuple[CtccObservationResponse, float]] = {}
36
+
37
+ self._x402_client = None
38
+ if private_key:
39
+ try:
40
+ from x402 import x402Client
41
+ self._x402_client = x402Client(private_key=private_key)
42
+ except ImportError:
43
+ pass
44
+
45
+ def check_token_control(self, contract_address: str) -> CtccObservationResponse:
46
+ """Inspects Base Mainnet contract control characteristics."""
47
+ addr = contract_address.strip()
48
+ if not ADDRESS_REGEX.match(addr):
49
+ raise ValueError(f"Invalid Ethereum/Base address format: {contract_address}")
50
+
51
+ normalized = addr.lower()
52
+ now = time.time()
53
+
54
+ # 1. Check in-memory cache
55
+ if self.cache_ttl > 0 and normalized in self._cache:
56
+ data, expires_at = self._cache[normalized]
57
+ if now < expires_at:
58
+ return data
59
+
60
+ # 2. Query endpoint with retry backoff
61
+ last_exc = None
62
+ for attempt in range(self.max_retries + 1):
63
+ try:
64
+ payload = {"address": addr}
65
+ if self._x402_client:
66
+ res = self._x402_client.post(self.endpoint, json=payload, timeout=15)
67
+ else:
68
+ res = self.session.post(self.endpoint, json=payload, timeout=15)
69
+
70
+ if res.status_code == 402:
71
+ raise RuntimeError(
72
+ "x402 Payment Required: Server requires $0.01 USDC on Base Mainnet. Provide private_key to CtccClient."
73
+ )
74
+
75
+ if res.status_code in (429, 502, 503, 504):
76
+ raise RuntimeError(f"CTCC server transient error: HTTP {res.status_code}")
77
+
78
+ res.raise_for_status()
79
+ data = CtccObservationResponse.model_validate(res.json())
80
+
81
+ if self.cache_ttl > 0:
82
+ self._cache[normalized] = (data, now + self.cache_ttl)
83
+
84
+ return data
85
+ except Exception as e:
86
+ last_exc = e
87
+ if attempt < self.max_retries:
88
+ time.sleep(self.retry_delay * (2 ** attempt))
89
+
90
+ raise last_exc or RuntimeError("CTCC query failed after retries")
91
+
92
+ def clear_cache(self) -> None:
93
+ self._cache.clear()
94
+
95
+
96
+ class AsyncCtccClient:
97
+ """Asynchronous CTCC client for asyncio frameworks, LangGraph, and trading bots."""
98
+
99
+ def __init__(
100
+ self,
101
+ endpoint: str = DEFAULT_CTCC_ENDPOINT,
102
+ private_key: Optional[str] = None,
103
+ cache_ttl_seconds: int = 0,
104
+ max_retries: int = 2,
105
+ retry_delay_seconds: float = 0.5,
106
+ client: Optional[httpx.AsyncClient] = None
107
+ ):
108
+ self.endpoint = endpoint
109
+ self.private_key = private_key
110
+ self.cache_ttl = cache_ttl_seconds
111
+ self.max_retries = max_retries
112
+ self.retry_delay = retry_delay_seconds
113
+ self._client = client
114
+ self._cache: Dict[str, Tuple[CtccObservationResponse, float]] = {}
115
+
116
+ async def _get_client(self) -> httpx.AsyncClient:
117
+ if self._client is None or self._client.is_closed:
118
+ self._client = httpx.AsyncClient(timeout=15.0)
119
+ return self._client
120
+
121
+ async def check_token_control(self, contract_address: str) -> CtccObservationResponse:
122
+ """Asynchronously inspects Base Mainnet contract control characteristics."""
123
+ addr = contract_address.strip()
124
+ if not ADDRESS_REGEX.match(addr):
125
+ raise ValueError(f"Invalid Ethereum/Base address format: {contract_address}")
126
+
127
+ normalized = addr.lower()
128
+ now = time.time()
129
+
130
+ if self.cache_ttl > 0 and normalized in self._cache:
131
+ data, expires_at = self._cache[normalized]
132
+ if now < expires_at:
133
+ return data
134
+
135
+ client = await self._get_client()
136
+ last_exc = None
137
+
138
+ for attempt in range(self.max_retries + 1):
139
+ try:
140
+ res = await client.post(self.endpoint, json={"address": addr})
141
+
142
+ if res.status_code == 402:
143
+ raise RuntimeError(
144
+ "x402 Payment Required: Server requires $0.01 USDC on Base Mainnet."
145
+ )
146
+
147
+ if res.status_code in (429, 502, 503, 504):
148
+ raise RuntimeError(f"CTCC server transient error: HTTP {res.status_code}")
149
+
150
+ res.raise_for_status()
151
+ data = CtccObservationResponse.model_validate(res.json())
152
+
153
+ if self.cache_ttl > 0:
154
+ self._cache[normalized] = (data, now + self.cache_ttl)
155
+
156
+ return data
157
+ except Exception as e:
158
+ last_exc = e
159
+ if attempt < self.max_retries:
160
+ import asyncio
161
+ await asyncio.sleep(self.retry_delay * (2 ** attempt))
162
+
163
+ raise last_exc or RuntimeError("CTCC async query failed after retries")
164
+
165
+ async def close(self) -> None:
166
+ if self._client and not self._client.is_closed:
167
+ await self._client.aclose()
168
+
169
+
170
+ def check_token_control(
171
+ contract_address: str,
172
+ private_key: Optional[str] = None,
173
+ endpoint: str = DEFAULT_CTCC_ENDPOINT,
174
+ cache_ttl_seconds: int = 0
175
+ ) -> CtccObservationResponse:
176
+ """Convenience functional wrapper for synchronous inspection."""
177
+ client = CtccClient(endpoint=endpoint, private_key=private_key, cache_ttl_seconds=cache_ttl_seconds)
178
+ return client.check_token_control(contract_address)
179
+
180
+
181
+ async def check_token_control_async(
182
+ contract_address: str,
183
+ private_key: Optional[str] = None,
184
+ endpoint: str = DEFAULT_CTCC_ENDPOINT,
185
+ cache_ttl_seconds: int = 0
186
+ ) -> CtccObservationResponse:
187
+ """Convenience functional wrapper for asynchronous inspection."""
188
+ client = AsyncCtccClient(endpoint=endpoint, private_key=private_key, cache_ttl_seconds=cache_ttl_seconds)
189
+ try:
190
+ return await client.check_token_control(contract_address)
191
+ finally:
192
+ await client.close()
ctcc_x402/models.py ADDED
@@ -0,0 +1,54 @@
1
+ """
2
+ Pydantic Data Models for CTCC™ (Cinqueport Token Control Check)
3
+ Network: Base Mainnet (eip155:8453)
4
+ Protocol: x402 v2 ($0.01 USDC)
5
+ """
6
+
7
+ from typing import Optional, Dict, Any
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ class Erc20Signals(BaseModel):
12
+ signals_detected: bool = Field(..., description="Whether ERC-20 symbol or decimals were detected")
13
+ name: Optional[str] = Field(None, description="Decoded ERC-20 name")
14
+ symbol: Optional[str] = Field(None, description="Decoded ERC-20 symbol")
15
+ decimals: Optional[int] = Field(None, description="Decoded ERC-20 decimals")
16
+ total_supply: Optional[str] = Field(None, description="Decoded ERC-20 total supply in atomic units")
17
+
18
+
19
+ class ControlAuthorities(BaseModel):
20
+ owner_present: bool = Field(..., description="Whether a non-zero owner address was returned by owner()")
21
+ owner_address: Optional[str] = Field(None, description="Current owner address")
22
+ proxy_admin_address: Optional[str] = Field(None, description="EIP-1967 admin storage slot address")
23
+
24
+
25
+ class PauseState(BaseModel):
26
+ pausable_detected: bool = Field(..., description="Whether paused() selector responded")
27
+ is_paused: bool = Field(False, description="Current boolean pause state")
28
+
29
+
30
+ class ProxyIndicators(BaseModel):
31
+ is_eip1967_proxy: bool = Field(..., description="Whether EIP-1967 implementation or beacon slot is non-zero")
32
+ implementation_address: Optional[str] = Field(None, description="EIP-1967 logic implementation address")
33
+ beacon_address: Optional[str] = Field(None, description="EIP-1967 beacon contract address")
34
+
35
+
36
+ class CtccObservations(BaseModel):
37
+ contract_exists: bool = Field(..., description="Whether deployed bytecode exists at target address")
38
+ bytecode_bytes: int = Field(..., description="Length of bytecode in bytes")
39
+ erc20: Optional[Erc20Signals] = None
40
+ control_authorities: Optional[ControlAuthorities] = None
41
+ pause_state: Optional[PauseState] = None
42
+ proxy_indicators: Optional[ProxyIndicators] = None
43
+
44
+
45
+ class CtccObservationResponse(BaseModel):
46
+ address: str = Field(..., description="Inspected contract address")
47
+ network: str = Field("Base Mainnet", description="Blockchain network name")
48
+ chain_id: str = Field("eip155:8453", description="CAIP-2 Chain ID")
49
+ checked_at: str = Field(..., description="ISO 8601 UTC timestamp of inspection")
50
+ observations: CtccObservations
51
+ disclaimer: str = Field(
52
+ "CTCC returns structured facts only. No safe/scam or tradeability verdict is provided. The calling agent applies its own policy.",
53
+ description="Governance disclaimer"
54
+ )
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctcc-x402
3
+ Version: 1.0.0
4
+ Summary: Deterministic smart-contract authority and control inspection for AI agents on Base Mainnet via x402 v2 micropayments ($0.01 USDC).
5
+ Author-email: "Cinque Port (Pavilion)" <hello@pspt.ltd>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://cinqueport.net/#ctcc
8
+ Project-URL: Documentation, https://cinqueport.net/openapi.json
9
+ Project-URL: Repository, https://github.com/jamesbjgates-web/ctcc-mcp
10
+ Keywords: x402,base,smart-contracts,token-security,ai-agents,defi
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: requests>=2.28.0
25
+ Requires-Dist: httpx>=0.24.0
26
+ Requires-Dist: pydantic>=2.0.0
27
+ Provides-Extra: x402
28
+ Requires-Dist: x402>=0.1.0; extra == "x402"
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=7.0.0; extra == "test"
31
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
32
+
33
+ # ctcc-x402
34
+
35
+ > Deterministic smart-contract control and authority inspection for AI agents on **Base Mainnet (eip155:8453)**, micro-settled via the **x402 v2 protocol ($0.01 USDC)**.
36
+
37
+ Developed by [Cinque Port](https://cinqueport.net), the specialist international trade and evidential due-diligence division of **Pavilion (Stockport) Ltd** (`pspt.ltd`).
38
+
39
+ ---
40
+
41
+ ## Features
42
+ - **Deterministic Observations**: Raw contract bytecode presence, ERC-20 metadata, owner/admin addresses, pause state, and EIP-1967 proxy mechanisms.
43
+ - **Dual Engine**: High-performance synchronous (`CtccClient`) and asynchronous (`AsyncCtccClient`) interfaces.
44
+ - **Bot-Optimized Caching**: Built-in TTL in-memory caching to eliminate redundant on-chain payments in high-frequency trading loops.
45
+ - **Pydantic Validation**: Fully typed dataclasses for strict runtime validation.
46
+
47
+ ---
48
+
49
+ ## Installation
50
+ ```bash
51
+ pip install ctcc-x402
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Quickstart
57
+
58
+ ### 1. Synchronous Inspection
59
+ ```python
60
+ from ctcc_x402 import check_token_control
61
+ import os
62
+
63
+ observations = check_token_control(
64
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
65
+ private_key=os.environ.get("EVM_PRIVATE_KEY")
66
+ )
67
+
68
+ print(f"Address: {observations.address}")
69
+ print(f"ERC-20 Symbol: {observations.observations.erc20.symbol}")
70
+ print(f"Owner: {observations.observations.control_authorities.owner_address}")
71
+ print(f"Paused: {observations.observations.pause_state.is_paused}")
72
+ ```
73
+
74
+ ### 2. High-Frequency Bot with Caching
75
+ ```python
76
+ from ctcc_x402 import CtccClient
77
+ import os
78
+
79
+ client = CtccClient(
80
+ private_key=os.environ.get("EVM_PRIVATE_KEY"),
81
+ cache_ttl_seconds=300, # 5-minute memory cache
82
+ max_retries=3
83
+ )
84
+
85
+ # First query: settles $0.01 USDC
86
+ obs1 = client.check_token_control("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
87
+
88
+ # Second query within 5 minutes: zero-latency cache hit (zero payment)
89
+ obs2 = client.check_token_control("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
90
+ ```
91
+
92
+ ### 3. Asynchronous Inspection (LangGraph / Asyncio)
93
+ ```python
94
+ from ctcc_x402 import AsyncCtccClient
95
+ import asyncio
96
+ import os
97
+
98
+ async def main():
99
+ client = AsyncCtccClient(private_key=os.environ.get("EVM_PRIVATE_KEY"))
100
+ try:
101
+ obs = await client.check_token_control("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
102
+ print("Bytecode size:", obs.observations.bytecode_bytes)
103
+ finally:
104
+ await client.close()
105
+
106
+ asyncio.run(main())
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Specification & Discovery
112
+ - **Protected Endpoint**: `POST https://cinqueport.net/check`
113
+ - **OpenAPI 3.1.0**: https://cinqueport.net/openapi.json
114
+ - **A2A Agent Card**: https://cinqueport.net/.well-known/agent.json
115
+ - **x402 Manifest**: https://cinqueport.net/.well-known/x402.json
116
+ - **LLMs Documentation**: https://cinqueport.net/llms.txt
117
+
118
+ ---
119
+
120
+ ## License
121
+ MIT © Pavilion (Stockport) Ltd.
@@ -0,0 +1,7 @@
1
+ ctcc_x402/__init__.py,sha256=KwVJo9USiJQ90A17qcE0-aEN5WIbsZxRty6kzOsquu8,659
2
+ ctcc_x402/client.py,sha256=t-WVm-8gw6CqAJC11tmLoc6ppb5meMfr-IIjDaho4zI,6988
3
+ ctcc_x402/models.py,sha256=FFAgKd_rJWiYW98Vxg4OtjX0oLQ6_Sf0giapvR3YeOs,2613
4
+ ctcc_x402-1.0.0.dist-info/METADATA,sha256=ubwBrG5k0buKyqVrUuPNuczPMP9FQXw65gdDKVnvIwY,4220
5
+ ctcc_x402-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ ctcc_x402-1.0.0.dist-info/top_level.txt,sha256=ISPPRoHbw37gLWUcpUvye3c7N6lNlKd5M5AR5O_LunU,10
7
+ ctcc_x402-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ ctcc_x402