web3-systemic-agent 1.0.2__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.
src/chain_inspector.py ADDED
@@ -0,0 +1,256 @@
1
+ """
2
+ Deterministic Chain Inspector Layer for Web3 Condition-Action Trigger Agent.
3
+ Interacts with EVM blockchains via AsyncWeb3 to evaluate on-chain conditions
4
+ (bytecode existence, native balance, calldata selectors) at zero LLM cost.
5
+ """
6
+
7
+ import asyncio
8
+ import logging
9
+ import os
10
+ import sys
11
+ from typing import Dict, Any, Optional, List, Union
12
+ from web3 import AsyncWeb3, AsyncHTTPProvider, Web3
13
+ from web3.exceptions import Web3Exception
14
+
15
+ # Ensure module search paths support running directly or as a package
16
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
17
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
18
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
19
+ for _p in (_ROOT_DIR, _SRC_DIR):
20
+ if _p not in sys.path:
21
+ sys.path.insert(0, _p)
22
+
23
+ try:
24
+ from src.schemas import DeterministicCondition, DeterministicResult
25
+ except ImportError:
26
+ from schemas import DeterministicCondition, DeterministicResult
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ BYTECODE_CACHE_MAX = 1024
31
+
32
+
33
+ class ChainInspector:
34
+ """
35
+ Deterministic Layer: Interacts with the EVM blockchain via AsyncWeb3.
36
+ Filters out non-matching conditions at zero LLM token cost.
37
+ """
38
+
39
+ BYTECODE_CACHE_MAX = BYTECODE_CACHE_MAX
40
+
41
+ DEFAULT_RPCS = {
42
+ 8453: "https://mainnet.base.org",
43
+ 84532: "https://sepolia.base.org",
44
+ 42161: "https://arb1.arbitrum.io/rpc",
45
+ }
46
+
47
+ KNOWN_SELECTORS = {
48
+ "0xa9059cbb": "transfer(address,uint256)",
49
+ "0x095ea7b3": "approve(address,uint256)",
50
+ "0x23b872dd": "transferFrom(address,address,uint256)",
51
+ "0xf2fde38b": "transferOwnership(address)",
52
+ "0x3659cfe6": "upgradeTo(address)",
53
+ "0x40c10f19": "mint(address,uint256)",
54
+ }
55
+
56
+ _bytecode_cache: Dict[str, bytes] = {}
57
+ _web3_cache: Dict[str, Any] = {}
58
+
59
+ @classmethod
60
+ def _set_bytecode_cache(cls, key: str, code: bytes) -> None:
61
+ if key in cls._bytecode_cache:
62
+ cls._bytecode_cache[key] = code
63
+ return
64
+ if len(cls._bytecode_cache) >= cls.BYTECODE_CACHE_MAX:
65
+ oldest_key = next(iter(cls._bytecode_cache))
66
+ cls._bytecode_cache.pop(oldest_key, None)
67
+ cls._bytecode_cache[key] = code
68
+
69
+ @classmethod
70
+ def clear_cache(cls) -> None:
71
+ cls._bytecode_cache.clear()
72
+ cls._web3_cache.clear()
73
+
74
+ @property
75
+ def bytecode_cache(self) -> Dict[str, bytes]:
76
+ return self._bytecode_cache
77
+
78
+ @classmethod
79
+ def resolve_rpc_urls(
80
+ cls, chain_id: int, rpc_url: Optional[Union[str, List[str]]] = None
81
+ ) -> List[str]:
82
+ if rpc_url is not None:
83
+ if isinstance(rpc_url, str):
84
+ urls = [u.strip() for u in rpc_url.split(",") if u.strip()]
85
+ elif isinstance(rpc_url, (list, tuple)):
86
+ urls = [str(u).strip() for u in rpc_url if str(u).strip()]
87
+ else:
88
+ urls = [str(rpc_url).strip()] if str(rpc_url).strip() else []
89
+ if urls:
90
+ return urls
91
+
92
+ env_var = os.getenv(f"RPC_URL_{chain_id}")
93
+ if env_var:
94
+ urls = [u.strip() for u in env_var.split(",") if u.strip()]
95
+ if urls:
96
+ return urls
97
+
98
+ default_rpc = cls.DEFAULT_RPCS.get(chain_id)
99
+ if default_rpc:
100
+ return [default_rpc]
101
+
102
+ raise ValueError(f"No default RPC configured for chain_id {chain_id}")
103
+
104
+ @classmethod
105
+ def _get_or_create_w3(
106
+ cls, chain_id: int, url: str, use_cache: bool = True
107
+ ) -> AsyncWeb3:
108
+ cache_key = f"{chain_id}:{url}"
109
+ if use_cache and cache_key in cls._web3_cache:
110
+ return cls._web3_cache[cache_key]
111
+ w3_instance = AsyncWeb3(AsyncHTTPProvider(url))
112
+ if use_cache:
113
+ cls._web3_cache[cache_key] = w3_instance
114
+ return w3_instance
115
+
116
+ def __init__(
117
+ self,
118
+ chain_id: int,
119
+ rpc_url: Optional[Union[str, List[str]]] = None,
120
+ use_cache: bool = True,
121
+ ):
122
+ self.chain_id = chain_id
123
+ self.use_cache = use_cache
124
+ self.rpc_urls = self.resolve_rpc_urls(chain_id, rpc_url)
125
+ self.w3 = self._get_or_create_w3(chain_id, self.rpc_urls[0], use_cache=use_cache)
126
+
127
+ async def verify_connection(self) -> bool:
128
+ try:
129
+ return await self.w3.is_connected()
130
+ except Web3Exception as exc:
131
+ logger.error(f"RPC connection failed: {exc}")
132
+ return False
133
+
134
+ @staticmethod
135
+ def inspect_calldata_selector(calldata: str) -> Dict[str, str]:
136
+ if not calldata or calldata == "0x" or len(calldata) < 10:
137
+ return {"selector": "0x", "signature": "native_transfer_or_empty"}
138
+ selector = calldata[:10].lower()
139
+ signature = ChainInspector.KNOWN_SELECTORS.get(selector, "unknown_selector")
140
+ return {"selector": selector, "signature": signature}
141
+
142
+ def _evaluate_post_rpc(
143
+ self,
144
+ condition: DeterministicCondition,
145
+ context: Dict[str, Any],
146
+ observed: Dict[str, Any],
147
+ ) -> DeterministicResult:
148
+ # Check transaction value passed in payload context
149
+ tx_value_wei = int(context.get("tx_value_wei", 0))
150
+ observed["tx_value_wei"] = tx_value_wei
151
+ if not condition.check_native_balance and tx_value_wei < condition.min_value_wei:
152
+ return DeterministicResult(
153
+ passed=False,
154
+ reason=f"Transaction value ({tx_value_wei} wei) is below threshold ({condition.min_value_wei} wei).",
155
+ observed_data=observed,
156
+ error=None,
157
+ )
158
+
159
+ # Inspect function selector if required
160
+ calldata = context.get("calldata", "0x")
161
+ selector_info = self.inspect_calldata_selector(calldata)
162
+ observed["calldata_analysis"] = selector_info
163
+
164
+ if condition.required_function_selectors:
165
+ normalized_required = [s.lower() for s in condition.required_function_selectors]
166
+ if selector_info["selector"] not in normalized_required:
167
+ return DeterministicResult(
168
+ passed=False,
169
+ reason=f"Selector {selector_info['selector']} not in required list {normalized_required}.",
170
+ observed_data=observed,
171
+ error=None,
172
+ )
173
+
174
+ return DeterministicResult(
175
+ passed=True,
176
+ reason="All deterministic on-chain conditions satisfied.",
177
+ observed_data=observed,
178
+ error=None,
179
+ )
180
+
181
+ async def evaluate_deterministic(
182
+ self, condition: DeterministicCondition, context: Dict[str, Any]
183
+ ) -> DeterministicResult:
184
+ target_addr = Web3.to_checksum_address(condition.target_address)
185
+ cache_key = f"{self.chain_id}:{target_addr}"
186
+ observed: Dict[str, Any] = {"target_address": target_addr}
187
+
188
+ try:
189
+ if not condition.check_native_balance and cache_key in self._bytecode_cache:
190
+ code = self._bytecode_cache[cache_key]
191
+ observed["is_contract"] = len(code) > 0
192
+ observed["rpc_url_index"] = 0
193
+ return self._evaluate_post_rpc(condition, context, observed)
194
+
195
+ last_exc: Optional[Exception] = None
196
+ for i, url in enumerate(self.rpc_urls):
197
+ observed = {"target_address": target_addr}
198
+ w3 = self._get_or_create_w3(self.chain_id, url, use_cache=self.use_cache)
199
+ try:
200
+ if condition.check_native_balance:
201
+ results = await asyncio.gather(
202
+ w3.eth.get_code(target_addr),
203
+ w3.eth.get_balance(target_addr),
204
+ return_exceptions=True,
205
+ )
206
+ code_res, balance_res = results[0], results[1]
207
+
208
+ if isinstance(code_res, Exception):
209
+ raise code_res
210
+ if isinstance(balance_res, Exception):
211
+ raise balance_res
212
+
213
+ self._set_bytecode_cache(cache_key, code_res)
214
+ observed["is_contract"] = len(code_res) > 0
215
+ observed["native_balance_wei"] = balance_res
216
+ observed["native_balance_eth"] = float(w3.from_wei(balance_res, "ether"))
217
+
218
+ if balance_res < condition.min_value_wei:
219
+ observed["rpc_url_index"] = i
220
+ return DeterministicResult(
221
+ passed=False,
222
+ reason=f"Target balance ({balance_res} wei) is below threshold ({condition.min_value_wei} wei).",
223
+ observed_data=observed,
224
+ error=None,
225
+ )
226
+ else:
227
+ code = await w3.eth.get_code(target_addr)
228
+ self._set_bytecode_cache(cache_key, code)
229
+ observed["is_contract"] = len(code) > 0
230
+
231
+ observed["rpc_url_index"] = i
232
+ return self._evaluate_post_rpc(condition, context, observed)
233
+
234
+ except Exception as exc:
235
+ logger.warning(
236
+ f"RPC call failed for URL {url} (index {i}, chain {self.chain_id}): {exc}"
237
+ )
238
+ last_exc = exc
239
+ continue
240
+
241
+ logger.exception("All RPC URLs failed during deterministic evaluation")
242
+ return DeterministicResult(
243
+ passed=False,
244
+ reason=f"RPC/Evaluation error: {str(last_exc)}",
245
+ observed_data=observed,
246
+ error=str(last_exc) if last_exc else "All RPC URLs failed",
247
+ )
248
+
249
+ except Exception as exc:
250
+ logger.exception("Error during deterministic evaluation")
251
+ return DeterministicResult(
252
+ passed=False,
253
+ reason=f"RPC/Evaluation error: {str(exc)}",
254
+ observed_data=observed,
255
+ error=str(exc),
256
+ )