fiderail 2.3.1__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.
fiderail/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """FideRail Python SDK — Non-Custodial Payment Control Plane & Edge Firewall (zero dependencies)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .spec import (
6
+ ALL_CHAIN_KEYS,
7
+ API_BASE_URL,
8
+ CHAIN_SPECS,
9
+ EUR_USD_DEFAULT_RATE,
10
+ SDK_VERSION,
11
+ get_asset_spec,
12
+ get_primary_asset,
13
+ is_valid_address,
14
+ normalize_chain_address,
15
+ normalize_chain_name,
16
+ raw_amount_to_decimal,
17
+ to_usd_amount,
18
+ )
19
+ from .policy import (
20
+ DEFAULT_FIREWALL_POLICY,
21
+ canonicalize_jcs,
22
+ clamp_policy,
23
+ compute_payment_fingerprint,
24
+ compute_quote_digest,
25
+ create_salted_receipt_v2,
26
+ hash_jcs,
27
+ is_asset_allowed,
28
+ scan_outbound_secrets,
29
+ sha256_hex,
30
+ validate_mandate_chain,
31
+ verify_salted_receipt_v2,
32
+ )
33
+ from .ledger import SqliteSpendLedger
34
+ from .client import FideRailClient, parse_x402_challenge
35
+
36
+ __version__ = SDK_VERSION
37
+
38
+ __all__ = [
39
+ "__version__",
40
+ "SDK_VERSION",
41
+ "API_BASE_URL",
42
+ "ALL_CHAIN_KEYS",
43
+ "CHAIN_SPECS",
44
+ "EUR_USD_DEFAULT_RATE",
45
+ "DEFAULT_FIREWALL_POLICY",
46
+ "normalize_chain_name",
47
+ "normalize_chain_address",
48
+ "is_valid_address",
49
+ "get_primary_asset",
50
+ "get_asset_spec",
51
+ "raw_amount_to_decimal",
52
+ "to_usd_amount",
53
+ "canonicalize_jcs",
54
+ "sha256_hex",
55
+ "hash_jcs",
56
+ "clamp_policy",
57
+ "scan_outbound_secrets",
58
+ "is_asset_allowed",
59
+ "compute_payment_fingerprint",
60
+ "compute_quote_digest",
61
+ "create_salted_receipt_v2",
62
+ "verify_salted_receipt_v2",
63
+ "validate_mandate_chain",
64
+ "SqliteSpendLedger",
65
+ "FideRailClient",
66
+ "parse_x402_challenge",
67
+ ]
fiderail/client.py ADDED
@@ -0,0 +1,517 @@
1
+ """Hybrid Option-C Python client for FideRail Cloud Intelligence + Local Edge Firewall."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple
12
+
13
+ from .ledger import SqliteSpendLedger
14
+ from .policy import (
15
+ DEFAULT_FIREWALL_POLICY,
16
+ clamp_policy,
17
+ compute_payment_fingerprint,
18
+ compute_quote_digest,
19
+ create_salted_receipt_v2,
20
+ is_asset_allowed,
21
+ scan_outbound_secrets,
22
+ serialize_body,
23
+ sha256_hex,
24
+ validate_mandate_chain,
25
+ )
26
+ from .spec import (
27
+ API_BASE_URL,
28
+ get_asset_spec,
29
+ get_primary_asset,
30
+ is_valid_address,
31
+ normalize_chain_address,
32
+ normalize_chain_name,
33
+ raw_amount_to_decimal,
34
+ to_usd_amount,
35
+ )
36
+
37
+
38
+ def parse_x402_challenge(headers: Dict[str, str], body_obj: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
39
+ challenge = body_obj if isinstance(body_obj, dict) else None
40
+ lower_headers = {k.lower(): v for k, v in (headers or {}).items()}
41
+ encoded = lower_headers.get("x-payment-required") or lower_headers.get("payment-required")
42
+ if encoded:
43
+ try:
44
+ decoded = json.loads(base64.b64decode(encoded).decode("utf-8"))
45
+ if isinstance(decoded, dict):
46
+ challenge = decoded
47
+ except Exception:
48
+ pass
49
+ accepts = challenge.get("accepts", []) if isinstance(challenge, dict) else []
50
+ options: List[Dict[str, Any]] = []
51
+ for acc in accepts:
52
+ if not isinstance(acc, dict):
53
+ continue
54
+ chain = normalize_chain_name(acc.get("network"))
55
+ if not chain:
56
+ continue
57
+ pay_to = normalize_chain_address(chain, acc.get("payTo"))
58
+ if not pay_to:
59
+ continue
60
+ raw_str = str(acc.get("amount") or acc.get("maxAmountRequired") or "").strip()
61
+ try:
62
+ if int(raw_str) <= 0:
63
+ continue
64
+ except ValueError:
65
+ continue
66
+ asset_spec = get_asset_spec(chain, acc.get("asset")) or get_primary_asset(chain)
67
+ amount_decimal = raw_amount_to_decimal(raw_str, int(asset_spec["decimals"]))
68
+ amount_usd = to_usd_amount(amount_decimal, asset_spec["fiatPeg"])
69
+ options.append(
70
+ {
71
+ "chain": chain,
72
+ "network": str(acc.get("network")),
73
+ "scheme": str(acc.get("scheme") or "exact"),
74
+ "asset": str(acc["asset"]) if acc.get("asset") else None,
75
+ "assetSymbol": asset_spec["symbol"],
76
+ "payTo": pay_to,
77
+ "amountRaw": raw_str,
78
+ "amountDecimal": amount_decimal,
79
+ "amountUsdc": amount_usd,
80
+ "raw": acc,
81
+ }
82
+ )
83
+ return options
84
+
85
+
86
+ class FideRailClient:
87
+ """Zero-dependency Python client implementing FideRail Hybrid Option-C Control Plane."""
88
+
89
+ def __init__(
90
+ self,
91
+ api_base_url: str = API_BASE_URL,
92
+ *,
93
+ ledger_path: str = ":memory:",
94
+ cache_ttl_ms: int = 30000,
95
+ timeout_sec: float = 6.0,
96
+ on_outage: str = "fail-closed",
97
+ host_policy: Optional[Dict[str, Any]] = None,
98
+ ) -> None:
99
+ self.api_base_url = api_base_url.rstrip("/")
100
+ self.ledger = SqliteSpendLedger(ledger_path)
101
+ self.cache_ttl_ms = max(0, int(cache_ttl_ms))
102
+ self.timeout_sec = max(0.5, float(timeout_sec))
103
+ self.on_outage = on_outage if on_outage in ("fail-closed", "fail-open-micro") else "fail-closed"
104
+ self.host_policy = dict(host_policy) if isinstance(host_policy, dict) else None
105
+
106
+ def close(self) -> None:
107
+ self.ledger.close()
108
+
109
+ def _request_json(self, method: str, path: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
110
+ url = f"{self.api_base_url}{path}"
111
+ data = json.dumps(body).encode("utf-8") if body is not None else None
112
+ headers = {"Accept": "application/json"}
113
+ if data is not None:
114
+ headers["Content-Type"] = "application/json"
115
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
116
+ try:
117
+ with urllib.request.urlopen(req, timeout=self.timeout_sec) as resp:
118
+ raw = resp.read().decode("utf-8")
119
+ return json.loads(raw) if raw else {}
120
+ except urllib.error.HTTPError as exc:
121
+ err_body = exc.read().decode("utf-8", errors="replace")
122
+ try:
123
+ parsed = json.loads(err_body)
124
+ msg = parsed.get("error") or err_body
125
+ except Exception:
126
+ msg = err_body or f"HTTP {exc.code}"
127
+ raise RuntimeError(f"FideRail API error ({exc.code}): {msg}") from exc
128
+
129
+ def _resolve_trust_with_meta(self, chain: str, address: str) -> Tuple[Dict[str, Any], Optional[str]]:
130
+ cached = self.ledger.get_cached_trust(chain, address)
131
+ if cached is not None:
132
+ return cached, None
133
+ try:
134
+ profile = self._request_json(
135
+ "GET",
136
+ f"/v1/trust/{urllib.parse.quote(chain)}/{urllib.parse.quote(address)}",
137
+ )
138
+ if self.cache_ttl_ms > 0:
139
+ self.ledger.set_cached_trust(chain, address, profile, self.cache_ttl_ms)
140
+ return profile, None
141
+ except Exception as exc:
142
+ return (
143
+ {
144
+ "found": False,
145
+ "chain": chain,
146
+ "address": address,
147
+ "creditScore": None,
148
+ "tier": "UNVERIFIED",
149
+ "riskFlags": ["CLOUD_ORACLE_UNAVAILABLE"],
150
+ },
151
+ str(exc),
152
+ )
153
+
154
+ def get_health(self) -> Dict[str, Any]:
155
+ return self._request_json("GET", "/healthz")
156
+
157
+ def get_trust(self, chain: str, address: str) -> Dict[str, Any]:
158
+ norm_chain = normalize_chain_name(chain)
159
+ if not norm_chain:
160
+ raise ValueError(f"Unsupported chain: {chain}")
161
+ if not is_valid_address(norm_chain, address):
162
+ raise ValueError(f"Invalid {norm_chain} wallet address: {address}")
163
+ norm_addr = normalize_chain_address(norm_chain, address)
164
+ profile, err = self._resolve_trust_with_meta(norm_chain, norm_addr)
165
+ if err:
166
+ raise RuntimeError(f"FideRail Cloud Oracle unreachable: {err}")
167
+ return profile
168
+
169
+ def get_history(self, chain: str, address: str, limit: int = 50) -> Dict[str, Any]:
170
+ norm_chain = normalize_chain_name(chain)
171
+ if not norm_chain:
172
+ raise ValueError(f"Unsupported chain: {chain}")
173
+ if not is_valid_address(norm_chain, address):
174
+ raise ValueError(f"Invalid {norm_chain} wallet address: {address}")
175
+ norm_addr = normalize_chain_address(norm_chain, address)
176
+ return self._request_json(
177
+ "GET",
178
+ f"/v1/history/{urllib.parse.quote(norm_chain)}/{urllib.parse.quote(norm_addr)}?limit={int(limit)}",
179
+ )
180
+
181
+ def list_agents(self, **params: Any) -> Dict[str, Any]:
182
+ qs = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
183
+ return self._request_json("GET", f"/v1/agents?{qs}" if qs else "/v1/agents")
184
+
185
+ def discover_services(self, **params: Any) -> Dict[str, Any]:
186
+ qs = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
187
+ return self._request_json("GET", f"/v1/services?{qs}" if qs else "/v1/services")
188
+
189
+ def diagnose_endpoint(self, url: str, method: str = "GET", auto_register: bool = False) -> Dict[str, Any]:
190
+ return self._request_json(
191
+ "POST",
192
+ "/v1/diagnose",
193
+ {"url": url, "method": method, "autoRegister": bool(auto_register)},
194
+ )
195
+
196
+ def report_delivery_telemetry(self, payload: Dict[str, Any]) -> Dict[str, Any]:
197
+ return self._request_json("POST", "/v1/telemetry/delivery", payload)
198
+
199
+ def preflight_guard(
200
+ self,
201
+ *,
202
+ chain: str,
203
+ counterparty: str,
204
+ amount_usdc: float,
205
+ spent_today_usdc: Optional[float] = None,
206
+ policy: Optional[Dict[str, Any]] = None,
207
+ ) -> Dict[str, Any]:
208
+ norm_chain = normalize_chain_name(chain)
209
+ if not norm_chain:
210
+ raise ValueError(f"Unsupported chain: {chain}")
211
+ if not is_valid_address(norm_chain, counterparty):
212
+ raise ValueError(f"Invalid {norm_chain} wallet address: {counterparty}")
213
+ norm_addr = normalize_chain_address(norm_chain, counterparty)
214
+ amt = float(amount_usdc)
215
+ if amt <= 0:
216
+ raise ValueError("amount_usdc must be positive")
217
+ spent = float(spent_today_usdc) if spent_today_usdc is not None else self.ledger.get_effective_spent_today_usdc()
218
+
219
+ effective = clamp_policy(self.host_policy, policy) if self.host_policy else dict(policy or {})
220
+ applied = {**DEFAULT_FIREWALL_POLICY, **effective}
221
+ applied["allowlist"] = [normalize_chain_address(norm_chain, a) for a in (applied.get("allowlist") or [])]
222
+ applied["blocklist"] = [normalize_chain_address(norm_chain, a) for a in (applied.get("blocklist") or [])]
223
+
224
+ trust_profile, outage_err = self._resolve_trust_with_meta(norm_chain, norm_addr)
225
+ reasons: List[str] = []
226
+ decision = "ALLOW"
227
+
228
+ def escalate(nxt: str, reason: str) -> None:
229
+ nonlocal decision
230
+ reasons.append(reason)
231
+ if nxt == "BLOCK":
232
+ decision = "BLOCK"
233
+ elif nxt == "WARN" and decision != "BLOCK":
234
+ decision = "WARN"
235
+
236
+ if norm_addr in applied["blocklist"]:
237
+ escalate("BLOCK", "BLOCKLISTED_COUNTERPARTY")
238
+ if amt > float(applied["maxSingleTxUsdc"]):
239
+ escalate("BLOCK", f"EXCEEDS_MAX_SINGLE_TX: ${amt} > cap ${applied['maxSingleTxUsdc']}")
240
+ if spent + amt > float(applied["maxDailyUsdc"]):
241
+ escalate("BLOCK", f"EXCEEDS_DAILY_BUDGET: ${spent + amt:.4f} > daily cap ${applied['maxDailyUsdc']}")
242
+
243
+ if norm_addr not in applied["allowlist"]:
244
+ if outage_err:
245
+ if self.on_outage == "fail-open-micro" and amt <= float(applied["allowUnknownMaxUsdc"]):
246
+ escalate("WARN", f"CLOUD_ORACLE_UNAVAILABLE_MICRO_FALLBACK: {outage_err}")
247
+ elif self.on_outage == "fail-open-micro":
248
+ escalate("BLOCK", f"CLOUD_ORACLE_UNAVAILABLE_ABOVE_MICRO_CAP: {outage_err}")
249
+ else:
250
+ escalate("BLOCK", f"CLOUD_ORACLE_UNAVAILABLE_FAIL_CLOSED: {outage_err}")
251
+ elif not trust_profile.get("found"):
252
+ assoc = trust_profile.get("associatedCredit")
253
+ if (
254
+ isinstance(assoc, dict)
255
+ and assoc.get("status") == "ACTIVE"
256
+ and float(assoc.get("effectiveEndorsedScore") or 0) >= float(applied["minTrustScore"])
257
+ and amt <= float(assoc.get("maxEndorsedSingleTxUsd") or 0)
258
+ ):
259
+ escalate("WARN", "ASSOCIATED_CREDIT_COLD_START_ALLOWED")
260
+ elif amt > float(applied["allowUnknownMaxUsdc"]):
261
+ escalate("BLOCK", "UNKNOWN_COUNTERPARTY_ABOVE_CAP")
262
+ else:
263
+ escalate("WARN", "UNKNOWN_COUNTERPARTY_MICRO_ALLOWED")
264
+ else:
265
+ flags = trust_profile.get("riskFlags") or []
266
+ if applied["blockLoops"] and "RECIPROCAL_LOOP" in flags:
267
+ escalate("BLOCK", "RECIPROCAL_LOOP_DETECTED")
268
+ if "SINGLE_PAYER_CONCENTRATED" in flags and amt > float(applied["blockSinglePayerConcentratedAboveUsdc"]):
269
+ escalate("BLOCK", "SINGLE_PAYER_CONCENTRATED_ABOVE_CAP")
270
+ if "ISOLATED_PAYER_FARM" in flags and amt > float(applied["blockSinglePayerConcentratedAboveUsdc"]):
271
+ escalate("BLOCK", "ISOLATED_PAYER_FARM_ABOVE_CAP")
272
+ if "BEHAVIOR_DRIFT" in flags:
273
+ escalate("WARN", "BEHAVIOR_DRIFT_DETECTED")
274
+ if "NON_X402_WHALE_FLOW" in flags:
275
+ escalate("WARN", "NON_X402_WHALE_FLOW")
276
+ score = float(trust_profile.get("creditScore") or 0)
277
+ if score < float(applied["minTrustScore"]):
278
+ if amt > float(applied["allowUnknownMaxUsdc"]):
279
+ escalate("BLOCK", f"TRUST_SCORE_BELOW_THRESHOLD: {score} < {applied['minTrustScore']}")
280
+ else:
281
+ escalate("WARN", "LOW_TRUST_MICRO_ALLOWED")
282
+ else:
283
+ reasons.append("ALLOWLISTED_COUNTERPARTY")
284
+
285
+ if not reasons:
286
+ reasons.append("PASSED_TRUST_AND_BUDGET_GATES")
287
+
288
+ return {
289
+ "decision": decision,
290
+ "chain": norm_chain,
291
+ "counterparty": norm_addr,
292
+ "amountUsdc": amt,
293
+ "remainingDailyBudgetUsdc": round(max(0.0, float(applied["maxDailyUsdc"]) - spent), 6),
294
+ "reasons": reasons,
295
+ "trustProfile": trust_profile,
296
+ "policyApplied": applied,
297
+ }
298
+
299
+ def guarded_x402_request(
300
+ self,
301
+ url: str,
302
+ *,
303
+ method: str = "GET",
304
+ headers: Optional[Dict[str, str]] = None,
305
+ body: Any = None,
306
+ preferred_chain: str = "base",
307
+ policy: Optional[Dict[str, Any]] = None,
308
+ mandate_chain: Optional[Sequence[Dict[str, Any]]] = None,
309
+ auto_revoke_mandate_on_completion: bool = False,
310
+ telemetry_opt_out: bool = False,
311
+ task_id: Optional[str] = None,
312
+ signer: Optional[Callable[[Dict[str, Any], Dict[str, Any]], str]] = None,
313
+ ) -> Dict[str, Any]:
314
+ req_headers = dict(headers or {})
315
+ effective = clamp_policy(self.host_policy, policy) if self.host_policy else dict(policy or {})
316
+
317
+ if effective.get("blockOutboundSecrets") is not False:
318
+ scan = scan_outbound_secrets(url=url, headers=req_headers, body=body, block_pii=bool(effective.get("blockPii")))
319
+ if not scan["safe"]:
320
+ return {
321
+ "paid": False,
322
+ "blocked": True,
323
+ "decision": "BLOCK",
324
+ "reason": "OUTBOUND_SECRET_DETECTED",
325
+ "detectedPatterns": scan["matches"],
326
+ }
327
+
328
+ parsed_u = urllib.parse.urlparse(url)
329
+ endpoint_key = f"{parsed_u.scheme}://{parsed_u.netloc}{parsed_u.path}"
330
+ breaker = self.ledger.check_circuit_breaker(endpoint_key)
331
+ if breaker["open"]:
332
+ return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "CIRCUIT_BREAKER_OPEN"}
333
+
334
+ def _http_call(extra_headers: Optional[Dict[str, str]] = None) -> Tuple[int, Dict[str, str], str]:
335
+ all_headers = {**req_headers, **(extra_headers or {})}
336
+ payload = serialize_body(body).encode("utf-8") if body is not None else None
337
+ req = urllib.request.Request(url, data=payload, headers=all_headers, method=method)
338
+ try:
339
+ with urllib.request.urlopen(req, timeout=self.timeout_sec) as resp:
340
+ return resp.status, dict(resp.headers.items()), resp.read().decode("utf-8", errors="replace")
341
+ except urllib.error.HTTPError as exc:
342
+ return exc.code, dict(exc.headers.items()), exc.read().decode("utf-8", errors="replace")
343
+
344
+ status, resp_headers, resp_text = _http_call()
345
+ if status >= 500:
346
+ self.ledger.record_endpoint_failure(endpoint_key, status=status)
347
+ return {"paid": False, "blocked": False, "decision": "ERROR", "status": status}
348
+ if status != 402:
349
+ if 200 <= status < 300:
350
+ self.ledger.record_endpoint_success(endpoint_key)
351
+ return {"paid": False, "blocked": False, "decision": "NO_PAYMENT_REQUIRED", "status": status, "bodyText": resp_text}
352
+
353
+ try:
354
+ body_json = json.loads(resp_text) if resp_text else None
355
+ except Exception:
356
+ body_json = None
357
+ options = parse_x402_challenge(resp_headers, body_json)
358
+ if not options:
359
+ raise RuntimeError("HTTP 402 response contained no supported Base/Solana/Arbitrum/Polygon options.")
360
+
361
+ allowed_assets = effective.get("allowedAssets") or ["USDC"]
362
+ permitted = [o for o in options if is_asset_allowed(o["chain"], o["asset"], allowed_assets, bool(effective.get("strictAssetCheck")))]
363
+ if not permitted:
364
+ return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "DISALLOWED_PAYMENT_ASSET"}
365
+
366
+ pref = normalize_chain_name(preferred_chain) or "base"
367
+ chosen = next((o for o in permitted if o["chain"] == pref), permitted[0])
368
+
369
+ body_hash = sha256_hex(serialize_body(body))
370
+ quote_digest = compute_quote_digest(
371
+ url=url,
372
+ method=method,
373
+ body_hash=body_hash,
374
+ chain=chosen["chain"],
375
+ pay_to=chosen["payTo"],
376
+ asset=chosen["asset"],
377
+ amount_usdc=chosen["amountUsdc"],
378
+ )
379
+ fingerprint = compute_payment_fingerprint(
380
+ url=url,
381
+ method=method,
382
+ body=body,
383
+ chain=chosen["chain"],
384
+ pay_to=chosen["payTo"],
385
+ amount_usdc=chosen["amountUsdc"],
386
+ )
387
+ idemp = self.ledger.check_idempotency(fingerprint, int(effective.get("idempotencyWindowSec", 60)) * 1000)
388
+ if idemp["isDuplicate"]:
389
+ return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "DUPLICATE_PAYMENT_DETECTED"}
390
+
391
+ leaf_mandate = mandate_chain[-1] if mandate_chain else None
392
+ if mandate_chain:
393
+ revoked = self.ledger.get_revoked_mandate_ids()
394
+ spent_under = self.ledger.get_mandate_spent_usd(str(leaf_mandate["mandateId"])) if leaf_mandate else 0.0
395
+ intent = {
396
+ "intentId": quote_digest,
397
+ "taskId": task_id,
398
+ "protocol": "x402",
399
+ "chain": chosen["chain"],
400
+ "assetContract": chosen["asset"] or get_primary_asset(chosen["chain"])["contract"],
401
+ "assetSymbol": chosen["assetSymbol"],
402
+ "amountRaw": chosen["amountRaw"],
403
+ "amountUsd": chosen["amountUsdc"],
404
+ "payee": chosen["payTo"],
405
+ "domain": (parsed_u.hostname or "").lower(),
406
+ }
407
+ mcheck = validate_mandate_chain(
408
+ mandate_chain, intent, spent_under_mandate_usd=spent_under, revoked_mandate_ids=revoked
409
+ )
410
+ if not mcheck["valid"]:
411
+ return {
412
+ "paid": False,
413
+ "blocked": True,
414
+ "decision": "BLOCK",
415
+ "reason": mcheck["reasons"][0],
416
+ "mandateCheck": mcheck,
417
+ }
418
+
419
+ guard = self.preflight_guard(
420
+ chain=chosen["chain"],
421
+ counterparty=chosen["payTo"],
422
+ amount_usdc=chosen["amountUsdc"],
423
+ policy=effective,
424
+ )
425
+ if guard["decision"] == "BLOCK":
426
+ return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": guard["reasons"][0], "guard": guard}
427
+
428
+ if signer is None:
429
+ return {
430
+ "paid": False,
431
+ "blocked": False,
432
+ "readyToSign": True,
433
+ "decision": guard["decision"],
434
+ "quoteDigest": quote_digest,
435
+ "paymentOption": chosen,
436
+ "guard": guard,
437
+ }
438
+
439
+ max_daily = float(guard["policyApplied"]["maxDailyUsdc"])
440
+ res = self.ledger.reserve_budget(chosen["amountUsdc"], max_daily)
441
+ if not res["ok"]:
442
+ return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "EXCEEDS_DAILY_BUDGET"}
443
+
444
+ res_id = res["reservationId"]
445
+ try:
446
+ proof = signer({**chosen, "quoteDigest": quote_digest}, guard)
447
+ t0 = time.time()
448
+ paid_status, _, paid_body = _http_call({"X-PAYMENT": proof, "PAYMENT-SIGNATURE": proof})
449
+ latency_ms = int((time.time() - t0) * 1000)
450
+ delivered = bool(200 <= paid_status < 300 and paid_body.strip())
451
+
452
+ if paid_status != 402 and res_id:
453
+ self.ledger.commit_reservation(res_id)
454
+ res_id = None
455
+ if leaf_mandate:
456
+ self.ledger.record_mandate_spend(str(leaf_mandate["mandateId"]), chosen["amountUsdc"])
457
+
458
+ mandate_revoked = False
459
+ if delivered:
460
+ self.ledger.record_payment_fingerprint(fingerprint)
461
+ self.ledger.record_endpoint_success(endpoint_key)
462
+ if auto_revoke_mandate_on_completion and leaf_mandate:
463
+ self.ledger.revoke_mandate(str(leaf_mandate["mandateId"]), "TASK_COMPLETED")
464
+ mandate_revoked = True
465
+ else:
466
+ self.ledger.record_endpoint_failure(endpoint_key, status=paid_status)
467
+
468
+ receipt_v2 = create_salted_receipt_v2(
469
+ method=method,
470
+ url=url,
471
+ body="" if body is None else body,
472
+ quote_digest=quote_digest,
473
+ chain=chosen["chain"],
474
+ asset_symbol=chosen["assetSymbol"],
475
+ asset_contract=chosen["asset"] or get_primary_asset(chosen["chain"])["contract"],
476
+ pay_to=chosen["payTo"],
477
+ amount_raw=chosen["amountRaw"],
478
+ amount_usd=chosen["amountUsdc"],
479
+ http_status=paid_status,
480
+ response_body=paid_body,
481
+ delivered=delivered,
482
+ task_id=task_id,
483
+ )
484
+
485
+ if not telemetry_opt_out:
486
+ try:
487
+ self.report_delivery_telemetry(
488
+ {
489
+ "chain": chosen["chain"],
490
+ "address": chosen["payTo"],
491
+ "resourceUrl": url,
492
+ "httpStatus": paid_status,
493
+ "delivered": delivered,
494
+ "latencyMs": latency_ms,
495
+ "verificationTier": "L2_SIGNED_SAR_TELEMETRY",
496
+ "receipt": receipt_v2,
497
+ }
498
+ )
499
+ except Exception:
500
+ pass
501
+
502
+ return {
503
+ "paid": 200 <= paid_status < 300,
504
+ "delivered": delivered,
505
+ "blocked": False,
506
+ "decision": guard["decision"],
507
+ "mandateRevokedOnCompletion": mandate_revoked,
508
+ "quoteDigest": quote_digest,
509
+ "deliveryReceiptV2": receipt_v2,
510
+ "status": paid_status,
511
+ "bodyText": paid_body,
512
+ "guard": guard,
513
+ "spentTodayUsdc": self.ledger.get_spent_today_usdc(),
514
+ }
515
+ finally:
516
+ if res_id:
517
+ self.ledger.release_reservation(res_id)