Spend-Cap Starter Kit (EBT r336 → ideation r335 #1, 18/20)

Nỗi đau: operator agent sợ nhất là "cày tiền không kiểm soát" — agent mua x402 calls trong automation, chủ không biết tốn bao nhiêu cho đến khi hóa đơn đến. Giải pháp: budget guardrails cắm vào client x402 trước khi gọi, hard cap không bỏ qua được.

1. Wrapper Python: hard-cap mọi x402 call (copy-paste)

import json, os, time
from decimal import Decimal

class SpendCappedX402Client:
    """Cap tổng chi tiêu x402 theo budget, không cần trust backend."""
    def __init__(self, budget_usdc: str, state_path: str = "/tmp/x402-spend.json"):
        self.budget = Decimal(budget_usdc)
        self.state_path = state_path
        self.state = {"spent": "0.0", "calls": 0}
        if os.path.exists(state_path):
            self.state = json.load(open(state_path))

    def spend(self) -> Decimal:
        return Decimal(self.state["spent"])

    def can_spend(self, price_usdc: str) -> bool:
        return self.spend() + Decimal(price_usdc) <= self.budget

    def before_call(self, endpoint: str, price_usdc: str):
        if not self.can_spend(price_usdc):
            raise RuntimeError(
                f"SPEND-CAP REACHED: spent=${self.spend():.4f} "
                f"budget=${self.budget:.4f}; next call {endpoint} "
                f"${price_usdc} rejected. Top up budget or lower cap."
            )

    def after_call(self, price_usdc: str):
        self.state["spent"] = str(self.spend() + Decimal(price_usdc))
        self.state["calls"] += 1
        json.dump(self.state, open(self.state_path, "w"))

# Dùng: bọc quanh mọi x402 fetch của agent
cap = SpendCappedX402Client(budget_usdc="1.00")  # ngân sách mỗi run
cap.before_call("aiverdict", "0.015")
# ... gọi endpoint, lấy response ...
cap.after_call("0.015")

2. Bảng giá tham khảo (Mekong Trade Intelligence fleet, USDC/Base)

NhómEndpoint ví dụGiá/call
Micro utility/ping, /uuid, /time, /random$0.001
Search/data/websearch, /ksearch, /tokenprice$0.007–$0.01
AI verdict/aiverdict$0.015
Enrichment/enrich$0.02
Intel nặng/13fintel, /contractaudit, /docextract$0.015–$0.30

Với budget $1.00/run, agent chạy được ~66 calls /aiverdict hoặc ~1000 calls /ping.

3. Quy tắc triển khai cho operator

  1. 1 budget = 1 agent run. Mỗi automation khởi tạo SpendCappedX402Client

với budget gắn với lần chạy, không dùng chung ngân sách tháng.

  1. Alert ở 80%. Khi spend() >= 0.8 * budget, gửi webhook/Telegram cho operator

(còn $X, còn ~N calls).

  1. Không bao giờ auto-topup. Top-up budget chỉ bằng tay. Agent không được quyền

nâng cap của chính nó.

  1. Log mỗi call: endpoint, price, timestamp → đối chiếu với settlement on-chain

(Base USDC, recipient 0x198f...EA93).

4. Vì sao kit này tồn tại

Sau 336 vòng vận hành fleet x402 trả phí thật, nỗi đau số 1 ngăn operator wire tiền vào automation KHÔNG PHẢI giá ($0.001–$0.30/call) mà là runaway-spend fear: agent tự gọi mà không có giới hạn. Kit này giải quyết bằng code buyer-side, không cần tin backend.

Kill criteria: 0 page hits/downloads 30 ngày sau khi publish công khai.

*Loop-owned, docs-only, reversible. Publish lên public /tools/ cần user nod.*

← Về trang công cụ Mekong Trade Intelligence