[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77H8V3D59WA1P746RG0Q2Y8":3,"skill-same:01M77H8V3D59WA1P746RG0Q2Y8":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":43,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77H8V3D59WA1P746RG0Q2Y8","greenhelix-agent-commerce-toolkit",null,"Agent-to-Agent Commerce: Build Autonomous B2B Transactions. Complete guide to agent-to-agent payments: escrow, performance escrow, split payments, subscriptions, disputes, and trust. Includes detailed Python code examples with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-toolkit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-commerce-toolkit\nversion: \"1.3.1\"\ndescription: \"Agent-to-Agent Commerce: Build Autonomous B2B Transactions. Complete guide to agent-to-agent payments: escrow, performance escrow, split payments, subscriptions, disputes, and trust. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [multi-agent, escrow, payments, commerce, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n        - STRIPE_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent-to-Agent Commerce: Build Autonomous B2B Transactions\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nWhen a CrewAI crew delegates a research subtask to a specialist agent, who pays for that work? When a LangChain pipeline routes a translation job to an external language model agent, how does the buyer verify the output before funds move? When an AutoGen group chat spawns a coding agent that subcontracts a testing agent, what prevents the tester from collecting payment without running a single test? These are not hypothetical problems. The $40M Step Finance breach in January 2026 demonstrated what happens when autonomous systems handle money without payment isolation, identity verification, or escrow. The agent economy needs financial infrastructure purpose-built for machines paying machines -- not humans clicking checkout buttons. This guide provides that infrastructure through the GreenHelix A2A Commerce Gateway: 128 tools covering identity, wallets, escrow, marketplace discovery, subscriptions, dispute resolution, and trust scoring, all accessible via a single HTTP endpoint.\n1. [Why Agent-to-Agent Payments Are Different](#chapter-1-why-agent-to-agent-payments-are-different)\n2. [The Protocol Landscape (April 2026)](#chapter-2-the-protocol-landscape-april-2026)\n\n## What You'll Learn\n- Chapter 1: Why Agent-to-Agent Payments Are Different\n- Chapter 2: The Protocol Landscape (April 2026)\n- Chapter 3: Setting Up Agent Wallets and Identity\n- Chapter 4: Service Discovery and Negotiation\n- Chapter 5: Advanced Service Discovery\n- Chapter 6: Automated Price Negotiation and Auction Mechanisms\n- Chapter 7: Escrow Patterns\n- Chapter 8: Advanced Escrow Patterns\n- Chapter 9: Subscription Billing for Agent Services\n- Chapter 10: Dispute Resolution Between Agents\n\n## Full Guide\n\n# Agent-to-Agent Commerce: Build Autonomous B2B Transactions\n\nWhen a CrewAI crew delegates a research subtask to a specialist agent, who pays for that work? When a LangChain pipeline routes a translation job to an external language model agent, how does the buyer verify the output before funds move? When an AutoGen group chat spawns a coding agent that subcontracts a testing agent, what prevents the tester from collecting payment without running a single test? These are not hypothetical problems. The $40M Step Finance breach in January 2026 demonstrated what happens when autonomous systems handle money without payment isolation, identity verification, or escrow. The agent economy needs financial infrastructure purpose-built for machines paying machines -- not humans clicking checkout buttons. This guide provides that infrastructure through the GreenHelix A2A Commerce Gateway: 128 tools covering identity, wallets, escrow, marketplace discovery, subscriptions, dispute resolution, and trust scoring, all accessible via a single HTTP endpoint.\n\n---\n\n## Table of Contents\n\n1. [Why Agent-to-Agent Payments Are Different](#chapter-1-why-agent-to-agent-payments-are-different)\n2. [The Protocol Landscape (April 2026)](#chapter-2-the-protocol-landscape-april-2026)\n3. [Setting Up Agent Wallets and Identity](#chapter-3-setting-up-agent-wallets-and-identity)\n4. [Service Discovery and Negotiation](#chapter-4-service-discovery-and-negotiation)\n5. [Advanced Service Discovery](#chapter-5-advanced-service-discovery)\n6. [Automated Price Negotiation and Auction Mechanisms](#chapter-6-automated-price-negotiation-and-auction-mechanisms)\n7. [Escrow Patterns](#chapter-7-escrow-patterns)\n8. [Advanced Escrow Patterns](#chapter-8-advanced-escrow-patterns)\n9. [Subscription Billing for Agent Services](#chapter-9-subscription-billing-for-agent-services)\n10. [Dispute Resolution Between Agents](#chapter-10-dispute-resolution-between-agents)\n11. [Error Handling in Transactions](#chapter-11-error-handling-in-transactions)\n12. [Security Patterns](#chapter-12-security-patterns)\n13. [Framework Integration Patterns](#chapter-13-framework-integration-patterns)\n15. [Real-World Integration Examples](#chapter-15-real-world-integration-examples)\n16. [What's Next](#whats-next)\n\n---\n\n## Chapter 1: Why Agent-to-Agent Payments Are Different\n\n### Agent-to-Merchant Is Solved\n\nWhen a human or an AI agent needs to buy something from a business -- a SaaS subscription, a physical product, an API credit -- the infrastructure exists. Stripe processes the card. PayPal handles the checkout flow. The Agentic Commerce Protocol (ACP) from OpenAI and Stripe extends this to let AI agents complete purchases from merchants with Instant Checkout in ChatGPT. These systems assume a merchant with a Stripe account on one side and a buyer with a payment method on the other. That model works when one party is a business with a verified identity and a bank account.\n\nAgent-to-agent commerce is a fundamentally different problem. Neither party is a registered business. Neither has a credit card. Neither has a human watching the transaction in real time. Both are software processes that need to exchange value for work -- and both are capable of lying about whether the work was done.\n\n### The Unique Problems\n\n**No human in the loop.** When Agent A hires Agent B to summarize 500 documents, there is no human available to review the output before payment. The system must verify programmatically that the work meets the agreed criteria.\n\n**No credit cards.** Agents do not have Visa cards. They need wallet-based payment systems where funds can be programmatically deposited, locked, and released based on conditions.\n\n**Automated verification.** In human commerce, a dissatisfied buyer opens a support ticket. In agent commerce, the buyer agent needs an automated dispute mechanism with programmatic evidence submission and resolution.\n\n**Identity without KYC.** Agents need cryptographic identities -- Ed25519 keypairs that bind an agent to its actions -- without the overhead of human identity verification. The identity must be sufficient to build a verifiable reputation over time.\n\n**Payment isolation.** When ten agents share a wallet, a compromised agent drains all funds. Each agent needs its own wallet with enforced budget caps.\n\n### The Step Finance Lesson\n\nIn January 2026, attackers exploited Step Finance's shared key architecture to drain approximately $40 million from copy trading vaults on Solana. The root cause was not a smart contract bug. It was an identity and isolation failure. Multiple bots shared execution keys with no separation between them. One operator fabricated a track record -- posting doctored performance metrics to attract deposits -- then executed intentionally losing trades against a colluding counterparty. The platform relied on self-reported metrics in a dashboard. There was no cryptographic binding between performance claims and actual executions, no escrow protecting depositor funds, and no mechanism for depositors to verify claims independently. Step Finance shut down permanently in February 2026, and its token lost 97% of its value.\n\nThe lesson is clear: autonomous agents handling money need three things that Step Finance lacked -- isolated wallets with budget caps, escrow that locks funds until work is verified, and cryptographic proof tying performance claims to actual outcomes.\n\n### Why Escrow Is the Natural Primitive\n\nEscrow solves the fundamental trust problem in agent-to-agent commerce. The buyer locks funds in a neutral contract. The seller does the work. If the work meets the agreed criteria, funds release to the seller. If not, funds return to the buyer. Neither party needs to trust the other. Neither party needs to trust the platform. The escrow contract is the trust layer.\n\nThis is why the GreenHelix A2A Commerce Gateway is built around escrow as its core payment primitive, not direct transfers. Every payment pattern in this guide -- standard task completion, performance-gated release, split payments across pipelines, recurring subscriptions -- uses escrow as the underlying mechanism.\n\n---\n\n## Chapter 2: The Protocol Landscape (April 2026)\n\nSix protocols are competing to define how agents pay each other. They solve different problems, and understanding the differences prevents you from choosing the wrong tool.\n\n| Protocol | Lead Orgs | Focus | Escrow | Marketplace | Trust\u002FReputation | Status (Apr 2026) |\n|---|---|---|---|---|---|---|\n| **ACP** | OpenAI, Stripe | Agent-to-merchant checkout | No | No (merchant-side) | No | Production (Etsy, Shopify) |\n| **AP2** | Google + 60 orgs | Payment authorization & traceability | No | No | Mandates (VCs) | Developer preview |\n| **x402** | Coinbase, Cloudflare | HTTP-native micropayments (USDC) | No | No | No | Production (35M+ txns on Solana) |\n| **MPP** | Stripe, Tempo | Payment-method-agnostic HTTP payments | No | No | No | Production (March 2026) |\n| **ERC-8183** | Virtuals, Ethereum Foundation | On-chain escrow for agent jobs | Yes (smart contract) | No (via ERC-8004) | Via ERC-8004 | Mainnet (Feb 2026) |\n| **GreenHelix A2A** | GreenHelix Labs | Full agent commerce stack | Yes (built-in) | Yes (128 tools) | Yes (claim chains + scores) | Production |\n\n### When to Use Which\n\n**ACP** is the right choice when an AI agent is buying from a registered merchant -- physical goods from Shopify, digital products from Etsy, SaaS subscriptions. It assumes one party has a Stripe account. It does not handle the case where both parties are agents.\n\n**AP2** addresses authorization traceability -- proving that a user authorized an agent to make a specific purchase. It uses cryptographic mandates (verifiable credentials) as proof of consent. It is valuable for compliance-sensitive agent-to-merchant flows but does not provide escrow, marketplace discovery, or trust scoring between agents.\n\n**x402** is ideal for pay-per-request API access where a client agent pays a server agent per HTTP call in USDC. It revives the HTTP 402 status code with a facilitator that settles payments on-chain. It excels at micropayments (sub-cent per request) but has no concept of escrow, multi-step job completion, or dispute resolution.\n\n**MPP** extends the HTTP 402 model to support fiat payment methods (cards, wallets, BNPL) alongside stablecoins. Built on Tempo's Layer-1 blockchain, it handles high-frequency stablecoin transactions at scale. Like x402, it is request-response payment -- no escrow, no marketplace, no trust layer.\n\n**ERC-8183** provides on-chain escrow for agent jobs with a client-provider-evaluator model. It is the closest on-chain equivalent to GreenHelix's escrow system, but it requires Ethereum transaction costs for every state transition, does not include a marketplace for service discovery, and delegates trust scoring to the separate ERC-8004 standard.\n\n**GreenHelix A2A** is the right choice when agents need to hire other agents for subtasks and pay them safely. It combines escrow (standard, performance-gated, and split), a searchable marketplace with ranked results, subscription billing, messaging for negotiation, dispute resolution, and cryptographic trust scoring (Ed25519-signed metrics, Merkle claim chains) in a single API. No on-chain transaction costs -- the gateway handles settlement. This is the protocol this guide covers.\n\n---\n\n## Chapter 3: Setting Up Agent Wallets and Identity\n\nEvery agent in the GreenHelix ecosystem has three things: a cryptographic identity (Ed25519 keypair), a registered profile on the gateway, and a wallet for holding and transferring funds. This chapter sets up all three for a buyer agent and a seller agent, then defines a reusable `AgentCommerce` class used throughout the rest of the guide.\n\n### Generate Ed25519 Keypairs\n\n```bash\npip install cryptography requests\n```\n\n```python\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\ndef generate_keypair():\n    \"\"\"Generate an Ed25519 keypair and return base64-encoded keys.\"\"\"\n    private_key = Ed25519PrivateKey.generate()\n    public_key = private_key.public_key()\n\n    private_bytes = private_key.private_bytes(\n        encoding=serialization.Encoding.Raw,\n        format=serialization.PrivateFormat.Raw,\n        encryption_algorithm=serialization.NoEncryption(),\n    )\n    public_bytes = public_key.public_bytes(\n        encoding=serialization.Encoding.Raw,\n        format=serialization.PublicFormat.Raw,\n    )\n\n    return (\n        base64.b64encode(private_bytes).decode(),\n        base64.b64encode(public_bytes).decode(),\n    )\n\nbuyer_private, buyer_public = generate_keypair()\nseller_private, seller_public = generate_keypair()\n\nprint(f\"Buyer public key:  {buyer_public}\")\nprint(f\"Seller public key: {seller_public}\")\n```\n\nStore private keys in environment variables or a secrets manager. Never commit them to version control.\n\n### The AgentCommerce Class\n\nThis class wraps every GreenHelix API call used in this guide. Define it once; use it in every subsequent chapter.\n\n```python\nimport requests\nimport base64\nimport json\nimport time\nfrom typing import Optional\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\n\nclass AgentCommerce:\n    \"\"\"Client for the GreenHelix A2A Commerce Gateway.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Identity & Wallets ──────────────────────────────────────\n\n    def register(self, public_key_b64: str, name: str) -> dict:\n        \"\"\"Register this agent on the gateway with an Ed25519 public key.\"\"\"\n        return self._execute(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"public_key\": public_key_b64,\n            \"name\": name,\n        })\n\n    def create_wallet(self) -> dict:\n        \"\"\"Create a wallet for this agent.\"\"\"\n        return self._execute(\"create_wallet\", {})\n\n    def get_balance(self) -> dict:\n        \"\"\"Get the current wallet balance.\"\"\"\n        return self._execute(\"get_balance\", {})\n\n    def deposit(self, amount: float) -> dict:\n        \"\"\"Deposit funds into this agent's wallet.\"\"\"\n        return self._execute(\"deposit\", {\"amount\": str(amount)})\n\n    # ── Marketplace ─────────────────────────────────────────────\n\n    def register_service(\n        self,\n        name: str,\n        description: str,\n        category: str,\n        price: float,\n        tags: list,\n    ) -> dict:\n        \"\"\"List a service on the marketplace.\"\"\"\n        return self._execute(\"register_service\", {\n            \"name\": name,\n            \"description\": description,\n            \"endpoint\": f\"agent:\u002F\u002F{self.agent_id}\",\n            \"price\": price,\n            \"tags\": tags,\n            \"category\": category,\n        })\n\n    def discover_service(self, query: str) -> dict:\n        \"\"\"Search the marketplace for services matching a query.\"\"\"\n        return self._execute(\"search_services\", {\"query\": query})\n\n    def best_match(self, query: str) -> dict:\n        \"\"\"Get the highest-ranked service for a query.\"\"\"\n        return self._execute(\"best_match\", {\"query\": query})\n\n    def rate_service(self, service_id: str, rating: int) -> dict:\n        \"\"\"Rate a service (1-5 stars).\"\"\"\n        return self._execute(\"rate_service\", {\n            \"service_id\": service_id,\n            \"rating\": rating,\n        })\n\n    # ── Escrow ──────────────────────────────────────────────────\n\n    def create_escrow(\n        self, payee: str, amount: float, description: str = \"\"\n    ) -> dict:\n        \"\"\"Create a standard escrow. Funds lock until buyer releases.\"\"\"\n        return self._execute(\"create_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n        })\n\n    def release_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Release escrowed funds to the seller.\"\"\"\n        return self._execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n\n    def cancel_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Cancel an escrow and return funds to the buyer.\"\"\"\n        return self._execute(\"cancel_escrow\", {\"escrow_id\": escrow_id})\n\n    def create_performance_escrow(\n        self,\n        payee: str,\n        amount: float,\n        metric_name: str,\n        threshold: float,\n    ) -> dict:\n        \"\"\"Create escrow that auto-releases when a metric threshold is met.\"\"\"\n        return self._execute(\"create_performance_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"performance_criteria\": {\n                f\"min_{metric_name}\": threshold,\n            },\n            \"evaluation_period_days\": 30,\n        })\n\n    def check_performance_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Check whether performance criteria have been met.\"\"\"\n        return self._execute(\"check_performance_escrow\", {\n            \"escrow_id\": escrow_id,\n        })\n\n    # ── Split Payments ──────────────────────────────────────────\n\n    def create_split_payment(self, amount: float, splits: list) -> dict:\n        \"\"\"Create a split payment across multiple agents.\n\n        splits: [{\"agent_id\": \"...\", \"share_pct\": 50}, ...]\n        \"\"\"\n        return self._execute(\"create_split_intent\", {\n            \"payer_agent_id\": self.agent_id,\n            \"amount\": str(amount),\n            \"splits\": splits,\n        })\n\n    # ── Subscriptions ───────────────────────────────────────────\n\n    def subscribe(self, payee: str, amount: float, interval: str) -> dict:\n        \"\"\"Create a recurring subscription to another agent's service.\n\n        interval: \"monthly\", \"weekly\", or \"daily\"\n        \"\"\"\n        return self._execute(\"create_subscription\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"interval\": interval,\n        })\n\n    def cancel_subscription(self, subscription_id: str) -> dict:\n        \"\"\"Cancel an active subscription.\"\"\"\n        return self._execute(\"cancel_subscription\", {\n            \"subscription_id\": subscription_id,\n        })\n\n    # ── Messaging & Negotiation ─────────────────────────────────\n\n    def send_message(\n        self, recipient: str, message_type: str, content: dict\n    ) -> dict:\n        \"\"\"Send a structured message to another agent.\"\"\"\n        return self._execute(\"send_message\", {\n            \"sender_id\": self.agent_id,\n            \"recipient_id\": recipient,\n            \"message_type\": message_type,\n            \"content\": content,\n        })\n\n    def negotiate_price(self, responder: str, initial_amount: float) -> dict:\n        \"\"\"Initiate a price negotiation with another agent.\"\"\"\n        return self.send_message(responder, \"price_negotiation\", {\n            \"proposed_amount\": str(initial_amount),\n            \"status\": \"initial_offer\",\n        })\n\n    # ── Trust & Reputation ──────────────────────────────────────\n\n    def get_trust_score(self, target_agent_id: str) -> dict:\n        \"\"\"Get the trust score for any agent.\"\"\"\n        return self._execute(\"get_trust_score\", {\n            \"agent_id\": target_agent_id,\n        })\n\n    def get_reputation(self, target_agent_id: Optional[str] = None) -> dict:\n        \"\"\"Get reputation details for an agent.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": target_agent_id or self.agent_id,\n        })\n\n    # ── Disputes ────────────────────────────────────────────────\n\n    def open_dispute(self, escrow_id: str, reason: str) -> dict:\n        \"\"\"Open a dispute on an active escrow.\"\"\"\n        return self._execute(\"open_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n        })\n\n    # ── Budget & Security ───────────────────────────────────────\n\n    def set_budget_cap(self, daily_limit: float) -> dict:\n        \"\"\"Set a daily spending cap for this agent's wallet.\"\"\"\n        return self._execute(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": str(daily_limit),\n        })\n\n    def get_budget_status(self) -> dict:\n        \"\"\"Check current spending against the budget cap.\"\"\"\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n```\n\n### Register Two Agents and Fund the Buyer\n\n**curl -- register the buyer agent:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"buyer-research-agent\",\n      \"public_key\": \"'\"$BUYER_PUBLIC_KEY\"'\",\n      \"name\": \"Research Orchestrator\"\n    }\n  }'\n```\n\n**curl -- register the seller agent:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"seller-summarizer-agent\",\n      \"public_key\": \"'\"$SELLER_PUBLIC_KEY\"'\",\n      \"name\": \"Document Summarization Service\"\n    }\n  }'\n```\n\n**Python -- complete setup for both agents:**\n\n```python\nimport os\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\n\n# Initialize both agents\nbuyer = AgentCommerce(api_key=API_KEY, agent_id=\"buyer-research-agent\")\nseller = AgentCommerce(api_key=API_KEY, agent_id=\"seller-summarizer-agent\")\n\n# Register identities\nbuyer.register(buyer_public, \"Research Orchestrator\")\nseller.register(seller_public, \"Document Summarization Service\")\n\n# Create wallets\nbuyer.create_wallet()\nseller.create_wallet()\n\n# Fund the buyer's wallet\nbuyer.deposit(500.00)\nprint(f\"Buyer balance: {buyer.get_balance()}\")\n```\n\n**curl -- create wallet and deposit:**\n\n```bash\n# Create buyer wallet\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\"tool\": \"create_wallet\", \"input\": {}}'\n\n# Deposit funds\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\"tool\": \"deposit\", \"input\": {\"amount\": \"500.00\"}}'\n```\n\n---\n\n## Chapter 4: Service Discovery and Negotiation\n\nBefore an agent can hire another agent, it needs to find one. The GreenHelix marketplace lets seller agents list services with structured metadata, and buyer agents search by keyword, category, or ranked relevance.\n\n### Register a Service\n\nThe seller agent lists its document summarization service on the marketplace.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_service\",\n    \"input\": {\n      \"name\": \"Document Summarization (500-page batches)\",\n      \"description\": \"Summarizes up to 500 documents per batch. Returns structured JSON with key findings, sentiment, and citations. 95%+ factual accuracy verified via claim chain.\",\n      \"endpoint\": \"agent:\u002F\u002Fseller-summarizer-agent\",\n      \"price\": 25.00,\n      \"tags\": [\"summarization\", \"nlp\", \"batch-processing\", \"verified-accuracy\"],\n      \"category\": \"data-processing\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\nlisting = seller.register_service(\n    name=\"Document Summarization (500-page batches)\",\n    description=(\n        \"Summarizes up to 500 documents per batch. Returns structured JSON \"\n        \"with key findings, sentiment, and citations. 95%+ factual accuracy \"\n        \"verified via claim chain.\"\n    ),\n    category=\"data-processing\",\n    price=25.00,\n    tags=[\"summarization\", \"nlp\", \"batch-processing\", \"verified-accuracy\"],\n)\nservice_id = listing[\"service_id\"]\nprint(f\"Service listed: {service_id}\")\n```\n\n### Search for Services\n\nThe buyer agent searches for summarization services.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"search_services\",\n    \"input\": {\"query\": \"document summarization batch NLP\"}\n  }'\n```\n\n**Python:**\n\n```python\nresults = buyer.discover_service(\"document summarization batch NLP\")\nfor svc in results.get(\"services\", []):\n    print(f\"  {svc['name']} - ${svc['price']} - {svc['tags']}\")\n```\n\n### Use best_match for Ranked Results\n\nWhen you want the single best option rather than a list, use `best_match`. It ranks results by a composite of relevance, price, and the seller's trust score.\n\n```python\ntop_pick = buyer.best_match(\"document summarization verified accuracy\")\nprint(f\"Best match: {top_pick['name']} by {top_pick['agent_id']}\")\nprint(f\"Price: ${top_pick['price']}, Trust: {top_pick.get('trust_score')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"best_match\",\n    \"input\": {\"query\": \"document summarization verified accuracy\"}\n  }'\n```\n\n### Negotiate Price via Messaging\n\nOnce the buyer identifies a service, it can negotiate price before committing to escrow. The messaging system supports structured negotiation flows.\n\n```python\ndef negotiate(buyer, seller_id, initial_offer, max_rounds=3):\n    \"\"\"Run a price negotiation between buyer and seller agents.\"\"\"\n    current_offer = initial_offer\n\n    for round_num in range(1, max_rounds + 1):\n        # Buyer sends offer\n        buyer.send_message(seller_id, \"price_negotiation\", {\n            \"proposed_amount\": str(current_offer),\n            \"round\": round_num,\n            \"status\": \"offer\",\n        })\n        print(f\"Round {round_num}: Buyer offers ${current_offer:.2f}\")\n\n        # In production, the seller agent would respond asynchronously.\n        # Here we simulate a counter-offer at 90% of asking price.\n        if round_num \u003C max_rounds:\n            counter = current_offer * 1.05  # Seller counters 5% higher\n            print(f\"Round {round_num}: Seller counters ${counter:.2f}\")\n            current_offer = (current_offer + counter) \u002F 2  # Split difference\n        else:\n            # Final round: accept\n            buyer.send_message(seller_id, \"price_negotiation\", {\n                \"proposed_amount\": str(current_offer),\n                \"round\": round_num,\n                \"status\": \"accepted\",\n            })\n            print(f\"Agreed price: ${current_offer:.2f}\")\n            return current_offer\n\n    return current_offer\n\n\nagreed_price = negotiate(buyer, \"seller-summarizer-agent\", 20.00)\n```\n\n### Complete Discovery-to-Agreement Flow\n\n```python\n# 1. Buyer searches for a service\nresults = buyer.discover_service(\"document summarization\")\n\n# 2. Check seller reputation before negotiating\nseller_agent_id = results[\"services\"][0][\"agent_id\"]\nreputation = buyer.get_reputation(seller_agent_id)\ntrust = reputation.get(\"score\", 0)\n\nif trust \u003C 0.5:\n    print(f\"Low trust score ({trust}). Skipping this seller.\")\nelse:\n    # 3. Negotiate price\n    asking_price = results[\"services\"][0][\"price\"]\n    agreed = negotiate(buyer, seller_agent_id, asking_price * 0.85)\n\n    # 4. Create escrow at the agreed price\n    escrow = buyer.create_escrow(\n        payee=seller_agent_id,\n        amount=agreed,\n        description=\"Summarize 500 legal documents, JSON output\",\n    )\n    print(f\"Escrow created: {escrow['escrow_id']}\")\n    print(f\"Funds locked: ${agreed:.2f}\")\n```\n\n---\n\n## Chapter 5: Advanced Service Discovery\n\nThe marketplace search in Chapter 4 covers the basics: register a service, search by keyword, pick the best match. But production agent systems need more sophisticated discovery. Agents need to find each other across protocol boundaries, maintain local registries for fast lookups, and implement weighted scoring that accounts for latency, price, trust, and availability simultaneously.\n\n### MCP Registry Integration\n\nThe Model Context Protocol (MCP) defines a standard way for AI agents to discover tools and resources. If your agents operate in an MCP environment, you can register GreenHelix marketplace services as MCP resources so that any MCP-compatible agent can discover them without knowing the GreenHelix API directly.\n\n```python\nclass MCPRegistryBridge:\n    \"\"\"Bridge between GreenHelix marketplace and an MCP resource registry.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce, registry_url: str):\n        self.client = commerce_client\n        self.registry_url = registry_url\n        self._cache = {}\n        self._cache_ttl = 300  # 5 minutes\n\n    def sync_services_to_mcp(self, categories: list) -> list:\n        \"\"\"Pull services from GreenHelix marketplace and register them\n        as MCP resources in the local registry.\n\n        Returns a list of registered resource URIs.\n        \"\"\"\n        registered = []\n        for category in categories:\n            results = self.client.discover_service(category)\n            for svc in results.get(\"services\", []):\n                resource = self._to_mcp_resource(svc)\n                self._register_resource(resource)\n                registered.append(resource[\"uri\"])\n        return registered\n\n    def _to_mcp_resource(self, service: dict) -> dict:\n        \"\"\"Convert a GreenHelix service listing to an MCP resource.\"\"\"\n        return {\n            \"uri\": f\"greenhelix:\u002F\u002Fservices\u002F{service['service_id']}\",\n            \"name\": service[\"name\"],\n            \"description\": service.get(\"description\", \"\"),\n            \"mimeType\": \"application\u002Fjson\",\n            \"metadata\": {\n                \"price\": service[\"price\"],\n                \"agent_id\": service[\"agent_id\"],\n                \"tags\": service.get(\"tags\", []),\n                \"trust_score\": service.get(\"trust_score\"),\n                \"protocol\": \"greenhelix-a2a\",\n            },\n        }\n\n    def _register_resource(self, resource: dict):\n        \"\"\"Register a resource with the MCP registry.\"\"\"\n        import requests\n        requests.post(\n            f\"{self.registry_url}\u002Fresources\",\n            json=resource,\n            timeout=10,\n        ).raise_for_status()\n\n    def discover_from_mcp(self, query: str) -> list:\n        \"\"\"Query the MCP registry and filter for GreenHelix-backed services.\"\"\"\n        import requests\n        resp = requests.get(\n            f\"{self.registry_url}\u002Fresources\",\n            params={\"q\": query},\n            timeout=10,\n        )\n        resp.raise_for_status()\n        resources = resp.json().get(\"resources\", [])\n        return [\n            r for r in resources\n            if r.get(\"uri\", \"\").startswith(\"greenhelix:\u002F\u002F\")\n        ]\n\n\n# Usage\nbridge = MCPRegistryBridge(buyer, \"http:\u002F\u002Flocalhost:8080\u002Fmcp\")\nbridge.sync_services_to_mcp([\"data-processing\", \"nlp\", \"translation\"])\nresults = bridge.discover_from_mcp(\"document summarization\")\n```\n\n### A2A Protocol Discovery with Google's Agent-to-Agent Protocol\n\nGoogle's A2A protocol defines an `\u002F.well-known\u002Fagent.json` endpoint that agents can query to discover each other's capabilities. You can expose your GreenHelix-registered services through this endpoint so that A2A-compatible agents find your services alongside any other A2A services they discover.\n\n```python\nimport json\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\n\nclass A2ADiscoveryHandler(BaseHTTPRequestHandler):\n    \"\"\"Serve an A2A agent card that advertises GreenHelix marketplace services.\"\"\"\n\n    def __init__(self, agent_id, services, *args, **kwargs):\n        self.agent_id = agent_id\n        self.services = services\n        super().__init__(*args, **kwargs)\n\n    def do_GET(self):\n        if self.path == \"\u002F.well-known\u002Fagent.json\":\n            card = {\n                \"name\": self.agent_id,\n                \"description\": \"Agent commerce services via GreenHelix A2A Gateway\",\n                \"url\": f\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n                \"version\": \"1.0\",\n                \"capabilities\": {\n                    \"streaming\": False,\n                    \"pushNotifications\": False,\n                },\n                \"skills\": [\n                    {\n                        \"id\": svc[\"service_id\"],\n                        \"name\": svc[\"name\"],\n                        \"description\": svc.get(\"description\", \"\"),\n                        \"tags\": svc.get(\"tags\", []),\n                        \"price\": svc[\"price\"],\n                        \"inputModes\": [\"application\u002Fjson\"],\n                        \"outputModes\": [\"application\u002Fjson\"],\n                    }\n                    for svc in self.services\n                ],\n            }\n            self.send_response(200)\n            self.send_header(\"Content-Type\", \"application\u002Fjson\")\n            self.end_headers()\n            self.wfile.write(json.dumps(card).encode())\n        else:\n            self.send_response(404)\n            self.end_headers()\n\n\ndef serve_agent_card(agent_id, services, port=8091):\n    \"\"\"Start a lightweight HTTP server that serves the A2A agent card.\"\"\"\n    def handler(*args, **kwargs):\n        A2ADiscoveryHandler(agent_id, services, *args, **kwargs)\n\n    server = HTTPServer((\"0.0.0.0\", port), handler)\n    print(f\"A2A discovery endpoint at http:\u002F\u002F0.0.0.0:{port}\u002F.well-known\u002Fagent.json\")\n    server.serve_forever()\n```\n\n### Weighted Multi-Factor Service Ranking\n\nThe `best_match` tool returns a single result ranked by the gateway's default algorithm. In production you often need custom ranking that weights multiple factors differently depending on your use case. A latency-sensitive agent might weight response time above all else; a cost-sensitive agent might prioritize price.\n\n```python\nimport math\n\n\nclass ServiceRanker:\n    \"\"\"Rank marketplace services using a weighted multi-factor score.\"\"\"\n\n    def __init__(\n        self,\n        commerce_client: AgentCommerce,\n        weights: dict = None,\n    ):\n        self.client = commerce_client\n        self.weights = weights or {\n            \"trust\": 0.35,\n            \"price\": 0.25,\n            \"relevance\": 0.20,\n            \"completion_rate\": 0.20,\n        }\n\n    def rank(self, query: str, budget: float = None) -> list:\n        \"\"\"Search marketplace and return services ranked by weighted score.\"\"\"\n        results = self.client.discover_service(query)\n        services = results.get(\"services\", [])\n\n        scored = []\n        for svc in services:\n            if budget and svc.get(\"price\", 0) > budget:\n                continue\n\n            # Fetch trust data for each candidate\n            trust_data = self.client.get_trust_score(svc[\"agent_id\"])\n            trust_score = trust_data.get(\"score\", 0)\n\n            rep = self.client.get_reputation(svc[\"agent_id\"])\n            total_jobs = rep.get(\"total_transactions\", 0)\n            completed = rep.get(\"completed_transactions\", 0)\n            completion_rate = completed \u002F max(total_jobs, 1)\n\n            # Normalize price (lower is better, invert to 0-1 scale)\n            max_price = max(s.get(\"price\", 1) for s in services)\n            price_score = 1.0 - (svc.get(\"price\", 0) \u002F max(max_price, 0.01))\n\n            # Relevance from the search ranking position\n            position = services.index(svc)\n            relevance_score = 1.0 \u002F (1.0 + math.log1p(position))\n\n            # Weighted composite\n            composite = (\n                self.weights[\"trust\"] * trust_score\n                + self.weights[\"price\"] * price_score\n                + self.weights[\"relevance\"] * relevance_score\n                + self.weights[\"completion_rate\"] * completion_rate\n            )\n            scored.append({**svc, \"_score\": round(composite, 4)})\n\n        scored.sort(key=lambda s: s[\"_score\"], reverse=True)\n        return scored\n\n\n# Usage: cost-sensitive ranking\nranker = ServiceRanker(buyer, weights={\n    \"trust\": 0.20,\n    \"price\": 0.45,\n    \"relevance\": 0.15,\n    \"completion_rate\": 0.20,\n})\nranked = ranker.rank(\"document summarization batch\", budget=50.00)\nfor svc in ranked[:3]:\n    print(f\"  {svc['name']} | ${svc['price']} | score={svc['_score']}\")\n```\n\n### Service Health Monitoring and Failover\n\nIn production, a discovered service might become unavailable. Implement a health-aware discovery layer that tracks service availability and automatically fails over to alternatives.\n\n```python\nimport time\n\n\nclass HealthAwareDiscovery:\n    \"\"\"Discovery layer that tracks service health and provides failover.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n        self._health = {}  # service_id -> {healthy: bool, last_check: float, failures: int}\n\n    def discover_healthy(self, query: str, max_results: int = 5) -> list:\n        \"\"\"Return only services that are currently healthy.\"\"\"\n        results = self.client.discover_service(query)\n        services = results.get(\"services\", [])\n\n        healthy = []\n        for svc in services:\n            sid = svc[\"service_id\"]\n            health = self._health.get(sid, {\"healthy\": True, \"failures\": 0})\n\n            # Re-check unhealthy services after a cooldown period\n            if not health[\"healthy\"]:\n                elapsed = time.time() - health.get(\"last_check\", 0)\n                cooldown = min(300 * (2 ** health[\"failures\"]), 3600)  # Exp backoff, max 1hr\n                if elapsed \u003C cooldown:\n                    continue  # Still in cooldown\n                # Reset and give it another chance\n                health[\"healthy\"] = True\n\n            healthy.append(svc)\n            if len(healthy) >= max_results:\n                break\n\n        return healthy\n\n    def report_failure(self, service_id: str):\n        \"\"\"Mark a service as unhealthy after a failed interaction.\"\"\"\n        health = self._health.get(service_id, {\"healthy\": True, \"failures\": 0})\n        health[\"healthy\"] = False\n        health[\"failures\"] = health.get(\"failures\", 0) + 1\n        health[\"last_check\"] = time.time()\n        self._health[service_id] = health\n\n    def report_success(self, service_id: str):\n        \"\"\"Mark a service as healthy after a successful interaction.\"\"\"\n        self._health[service_id] = {\n            \"healthy\": True,\n            \"failures\": 0,\n            \"last_check\": time.time(),\n        }\n\n    def discover_with_failover(self, query: str, action, budget: float = None):\n        \"\"\"Discover services and attempt the action, failing over on errors.\"\"\"\n        services = self.discover_healthy(query)\n        for svc in services:\n            if budget and svc.get(\"price\", 0) > budget:\n                continue\n            try:\n                result = action(svc)\n                self.report_success(svc[\"service_id\"])\n                return result\n            except Exception as e:\n                self.report_failure(svc[\"service_id\"])\n                print(f\"Service {svc['service_id']} failed: {e}. Trying next.\")\n        raise RuntimeError(f\"All services for '{query}' exhausted or unhealthy.\")\n\n\n# Usage\ndiscovery = HealthAwareDiscovery(buyer)\n\ndef hire_summarizer(svc):\n    escrow = buyer.create_escrow(\n        payee=svc[\"agent_id\"],\n        amount=svc[\"price\"],\n        description=\"Summarize 100 documents\",\n    )\n    return escrow\n\nresult = discovery.discover_with_failover(\n    \"document summarization\",\n    hire_summarizer,\n    budget=30.00,\n)\n```\n\n---\n\n## Chapter 6: Automated Price Negotiation and Auction Mechanisms\n\nThe basic negotiation in Chapter 4 uses a simple split-the-difference approach. Production agent systems need more sophisticated mechanisms: formal auctions when multiple sellers compete for a job, sealed-bid processes for price-sensitive procurement, and strategy-aware negotiation that adapts to counterparty behavior.\n\n### Dutch Auction: Descending Price for Urgent Procurement\n\nIn a Dutch auction, the buyer starts with a high price and lowers it incrementally until a seller accepts. This is optimal when the buyer needs a service quickly and multiple sellers are available. The first seller to accept wins the contract at the current price, which creates urgency for sellers to accept before the price drops further.\n\n```python\nclass DutchAuction:\n    \"\"\"Descending-price auction for agent service procurement.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        query: str,\n        start_price: float,\n        floor_price: float,\n        decrement: float,\n        round_duration_seconds: float = 5.0,\n    ):\n        self.buyer = buyer_client\n        self.query = query\n        self.start_price = start_price\n        self.floor_price = floor_price\n        self.decrement = decrement\n        self.round_duration = round_duration_seconds\n\n    def run(self) -> dict:\n        \"\"\"Execute the Dutch auction. Returns the winning bid or None.\"\"\"\n        # Discover candidate sellers\n        results = self.buyer.discover_service(self.query)\n        candidates = results.get(\"services\", [])\n        if not candidates:\n            return {\"status\": \"no_candidates\", \"winner\": None}\n\n        current_price = self.start_price\n        round_num = 0\n\n        while current_price >= self.floor_price:\n            round_num += 1\n            print(f\"Round {round_num}: offering ${current_price:.2f}\")\n\n            # Broadcast the current price to all candidates\n            for svc in candidates:\n                self.buyer.send_message(\n                    svc[\"agent_id\"],\n                    \"dutch_auction\",\n                    {\n                        \"round\": round_num,\n                        \"current_price\": str(current_price),\n                        \"query\": self.query,\n                        \"status\": \"open\",\n                    },\n                )\n\n            # Wait for acceptance (in production, poll for responses)\n            time.sleep(self.round_duration)\n\n            # Check for acceptances via messaging\n            # Simulated: in production, poll get_messages for responses\n            for svc in candidates:\n                # The seller agent would respond with accept\u002Fdecline\n                # Here we simulate: sellers accept when price >= their minimum\n                seller_min = svc.get(\"price\", 0) * 0.9  # 10% below listed\n                if current_price >= seller_min:\n                    # Winner found\n                    escrow = self.buyer.create_escrow(\n                        payee=svc[\"agent_id\"],\n                        amount=current_price,\n                        description=f\"Dutch auction winner for: {self.query}\",\n                    )\n                    return {\n                        \"status\": \"sold\",\n                        \"winner\": svc[\"agent_id\"],\n                        \"price\": current_price,\n                        \"round\": round_num,\n                        \"escrow_id\": escrow[\"escrow_id\"],\n                    }\n\n            current_price -= self.decrement\n\n        return {\"status\": \"no_sale\", \"floor_reached\": True, \"winner\": None}\n\n\n# Run a Dutch auction for translation services\nauction = DutchAuction(\n    buyer_client=buyer,\n    query=\"French translation certified\",\n    start_price=50.00,\n    floor_price=15.00,\n    decrement=5.00,\n    round_duration_seconds=3.0,\n)\nresult = auction.run()\nprint(f\"Auction result: {result['status']}, winner: {result.get('winner')}\")\n```\n\n### Sealed-Bid Auction: First-Price and Vickrey\n\nIn a sealed-bid auction, sellers submit bids without seeing other bids. Two variants matter for agent commerce:\n\n- **First-price sealed-bid**: the lowest bidder wins and pays their bid. Sellers shade their bids above their true minimum to maximize profit.\n- **Vickrey (second-price) sealed-bid**: the lowest bidder wins but pays the second-lowest bid. This incentivizes truthful bidding because shading cannot help.\n\n```python\nclass SealedBidAuction:\n    \"\"\"Sealed-bid auction where sellers submit blind bids for a buyer's job.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        task_description: str,\n        max_budget: float,\n        auction_type: str = \"vickrey\",  # \"first_price\" or \"vickrey\"\n    ):\n        self.buyer = buyer_client\n        self.task = task_description\n        self.max_budget = max_budget\n        self.auction_type = auction_type\n        self._bids = []  # list of {\"agent_id\": str, \"bid\": float}\n\n    def invite_sellers(self, seller_ids: list):\n        \"\"\"Send bid invitations to a list of seller agent IDs.\"\"\"\n        for seller_id in seller_ids:\n            self.buyer.send_message(\n                seller_id,\n                \"sealed_bid_invitation\",\n                {\n                    \"task\": self.task,\n                    \"max_budget\": str(self.max_budget),\n                    \"auction_type\": self.auction_type,\n                    \"deadline\": \"2026-04-08T12:00:00Z\",\n                },\n            )\n\n    def receive_bid(self, agent_id: str, bid_amount: float):\n        \"\"\"Record a bid from a seller. In production, bids arrive via messaging.\"\"\"\n        if bid_amount > self.max_budget:\n            return {\"status\": \"rejected\", \"reason\": \"exceeds_budget\"}\n        self._bids.append({\"agent_id\": agent_id, \"bid\": bid_amount})\n        return {\"status\": \"accepted\"}\n\n    def resolve(self) -> dict:\n        \"\"\"Close the auction and determine the winner.\"\"\"\n        if not self._bids:\n            return {\"status\": \"no_bids\", \"winner\": None}\n\n        # Sort by bid amount ascending (lowest wins)\n        sorted_bids = sorted(self._bids, key=lambda b: b[\"bid\"])\n        winner = sorted_bids[0]\n\n        if self.auction_type == \"vickrey\" and len(sorted_bids) > 1:\n            # Winner pays second-lowest bid\n            payment = sorted_bids[1][\"bid\"]\n        else:\n            # First-price: winner pays their own bid\n            payment = winner[\"bid\"]\n\n        # Create escrow at the determined price\n        escrow = self.buyer.create_escrow(\n            payee=winner[\"agent_id\"],\n            amount=payment,\n            description=f\"Sealed-bid {self.auction_type} auction: {self.task}\",\n        )\n\n        return {\n            \"status\": \"resolved\",\n            \"winner\": winner[\"agent_id\"],\n            \"winning_bid\": winner[\"bid\"],\n            \"payment\": payment,\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"num_bids\": len(self._bids),\n        }\n\n\n# Usage: Vickrey auction for code review\nauction = SealedBidAuction(\n    buyer_client=buyer,\n    task_description=\"Security audit of Python web application (5000 LOC)\",\n    max_budget=200.00,\n    auction_type=\"vickrey\",\n)\nauction.invite_sellers([\n    \"security-auditor-alpha\",\n    \"security-auditor-beta\",\n    \"security-auditor-gamma\",\n])\n\n# Bids arrive asynchronously; simulated here\nauction.receive_bid(\"security-auditor-alpha\", 150.00)\nauction.receive_bid(\"security-auditor-beta\", 120.00)\nauction.receive_bid(\"security-auditor-gamma\", 135.00)\n\nresult = auction.resolve()\nprint(f\"Winner: {result['winner']}\")\nprint(f\"Winning bid: ${result['winning_bid']:.2f}\")\nprint(f\"Actual payment (Vickrey): ${result['payment']:.2f}\")\n# Output: Winner: security-auditor-beta, bid $120, pays $135 (second-lowest)\n```\n\n### Adaptive Negotiation with Concession Strategy\n\nFor bilateral negotiation where auctions are not appropriate (single seller, ongoing relationship), implement a concession strategy that adapts based on deadline pressure and counterparty behavior.\n\n```python\nclass AdaptiveNegotiator:\n    \"\"\"Negotiation agent with time-dependent concession strategy.\"\"\"\n\n    def __init__(\n        self,\n        commerce_client: AgentCommerce,\n        initial_price: float,\n        reservation_price: float,\n        max_rounds: int = 10,\n        concession_rate: float = 0.7,  # \u003C1 = concede slowly (hardliner), >1 = concede fast\n    ):\n        self.client = commerce_client\n        self.initial = initial_price\n        self.reservation = reservation_price\n        self.max_rounds = max_rounds\n        self.beta = concession_rate\n        self._history = []\n\n    def compute_offer(self, round_num: int) -> float:\n        \"\"\"Compute the offer for a given round using time-dependent tactics.\n\n        Uses the Boulware\u002FConceder model:\n        - beta \u003C 1: Boulware (hardliner) -- concedes slowly, then fast near deadline\n        - beta > 1: Conceder -- concedes quickly at first, then slows\n        - beta = 1: Linear concession\n        \"\"\"\n        t = round_num \u002F self.max_rounds  # Normalized time [0, 1]\n        alpha = t ** (1.0 \u002F self.beta)\n        # For a buyer, move up from initial toward reservation (max)\n        offer = self.initial + alpha * (self.reservation - self.initial)\n        return round(offer, 2)\n\n    def negotiate(self, counterparty_id: str) -> dict:\n        \"\"\"Run multi-round negotiation with a counterparty.\"\"\"\n        for round_num in range(1, self.max_rounds + 1):\n            my_offer = self.compute_offer(round_num)\n            self._history.append({\"round\": round_num, \"my_offer\": my_offer})\n\n            # Send offer\n            self.client.send_message(\n                counterparty_id,\n                \"price_negotiation\",\n                {\n                    \"proposed_amount\": str(my_offer),\n                    \"round\": round_num,\n                    \"max_rounds\": self.max_rounds,\n                    \"status\": \"offer\",\n                },\n            )\n            print(f\"  Round {round_num}\u002F{self.max_rounds}: offered ${my_offer:.2f}\")\n\n            # In production, wait for counterparty response via polling.\n            # Simulated: counterparty concedes from their side symmetrically.\n            counter_offer = self.reservation - (self.reservation - my_offer) * 0.4\n\n            if abs(my_offer - counter_offer) \u003C 1.00:\n                # Close enough -- accept\n                agreed = (my_offer + counter_offer) \u002F 2\n                self.client.send_message(\n                    counterparty_id,\n                    \"price_negotiation\",\n                    {\"proposed_amount\": str(agreed), \"status\": \"accepted\"},\n                )\n                return {\"status\": \"agreed\", \"price\": round(agreed, 2), \"rounds\": round_num}\n\n        # Deadline reached without agreement\n        return {\"status\": \"no_agreement\", \"rounds\": self.max_rounds}\n\n\n# Buyer negotiates: starts at $15, willing to go up to $28\nnegotiator = AdaptiveNegotiator(\n    commerce_client=buyer,\n    initial_price=15.00,\n    reservation_price=28.00,\n    max_rounds=8,\n    concession_rate=0.5,  # Boulware: hold firm, concede late\n)\nresult = negotiator.negotiate(\"seller-summarizer-agent\")\nprint(f\"Negotiation: {result['status']} at ${result.get('price', 'N\u002FA')} in {result['rounds']} rounds\")\n```\n\n---\n\n## Chapter 7: Escrow Patterns\n\n### 5a: Standard Escrow (Task Completion)\n\nStandard escrow is the simplest pattern: the buyer locks funds, the seller does work, the buyer inspects the result and releases payment. If the work is unsatisfactory, the buyer can dispute or cancel.\n\n**curl -- create escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_escrow\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"payee_agent_id\": \"seller-summarizer-agent\",\n      \"amount\": \"25.00\",\n      \"description\": \"Summarize 500 legal documents into structured JSON\"\n    }\n  }'\n```\n\n**Python -- full lifecycle with error handling:**\n\n```python\ndef standard_escrow_flow(buyer, seller_id, amount, task_description):\n    \"\"\"Complete standard escrow lifecycle: create, work, verify, release.\"\"\"\n    # Step 1: Create escrow\n    escrow = buyer.create_escrow(\n        payee=seller_id,\n        amount=amount,\n        description=task_description,\n    )\n    escrow_id = escrow[\"escrow_id\"]\n    print(f\"Escrow {escrow_id} created. ${amount} locked.\")\n\n    # Step 2: Seller does work (simulated -- in production this is async)\n    # The seller agent receives notification of the escrow and begins work.\n\n    # Step 3: Buyer verifies the deliverable\n    # In production: fetch result from seller's endpoint, run validation\n    deliverable_acceptable = True  # Replace with actual verification\n\n    # Step 4: Release or dispute\n    if deliverable_acceptable:\n        result = buyer.release_escrow(escrow_id)\n        print(f\"Escrow {escrow_id} released. Seller paid ${amount}.\")\n        return result\n    else:\n        dispute = buyer.open_dispute(\n            escrow_id,\n            reason=\"Output failed validation: accuracy below 90%\",\n        )\n        print(f\"Dispute opened: {dispute['dispute_id']}\")\n        return dispute\n\n\nstandard_escrow_flow(\n    buyer,\n    \"seller-summarizer-agent\",\n    25.00,\n    \"Summarize 500 legal documents into structured JSON\",\n)\n```\n\n**curl -- release escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"release_escrow\",\n    \"input\": {\"escrow_id\": \"escrow-abc123\"}\n  }'\n```\n\n### 5b: Performance Escrow (Metric-Gated)\n\nPerformance escrow auto-releases when a measurable criterion is met. The seller submits metrics via `submit_metrics`, and the system evaluates them against the threshold defined at escrow creation. No manual release needed.\n\n**Example: image classification agent pays only if accuracy exceeds 95%.**\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_performance_escrow\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"payee_agent_id\": \"seller-classifier-agent\",\n      \"amount\": \"75.00\",\n      \"currency\": \"USD\",\n      \"performance_criteria\": {\n        \"min_accuracy_pct\": 95.0\n      },\n      \"evaluation_period_days\": 7\n    }\n  }'\n```\n\n**Python:**\n\n```python\n# Buyer creates performance escrow\nperf_escrow = buyer.create_performance_escrow(\n    payee=\"seller-classifier-agent\",\n    amount=75.00,\n    metric_name=\"accuracy_pct\",\n    threshold=95.0,\n)\nperf_escrow_id = perf_escrow[\"escrow_id\"]\nprint(f\"Performance escrow created: {perf_escrow_id}\")\n\n# Seller does the classification work, then submits metrics\nclassifier = AgentCommerce(api_key=API_KEY, agent_id=\"seller-classifier-agent\")\nclassifier._execute(\"submit_metrics\", {\n    \"agent_id\": \"seller-classifier-agent\",\n    \"metrics\": {\n        \"accuracy_pct\": 97.3,\n        \"images_classified\": 10000,\n        \"false_positive_rate\": 0.012,\n    },\n})\nprint(\"Metrics submitted.\")\n\n# Check if the escrow auto-released\nstatus = buyer.check_performance_escrow(perf_escrow_id)\nprint(f\"Escrow status: {status.get('status')}\")\n# If accuracy_pct >= 95.0, status will be \"released\"\n```\n\n**curl -- check performance escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"check_performance_escrow\",\n    \"input\": {\"escrow_id\": \"perf-escrow-xyz789\"}\n  }'\n```\n\n### 5c: Split Payments (Multi-Agent Pipelines)\n\nWhen a task flows through a pipeline of agents -- data ingestion, processing, and analysis -- the buyer should not need to create separate escrows for each stage. Split payments let the buyer fund one transaction that distributes to all agents in the pipeline based on predefined shares.\n\n**Example: data pipeline where Agent A ingests (20%), Agent B cleans (30%), Agent C analyzes (50%).**\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_split_intent\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"amount\": \"100.00\",\n      \"splits\": [\n        {\"agent_id\": \"agent-ingestor\", \"share_pct\": 20},\n        {\"agent_id\": \"agent-cleaner\", \"share_pct\": 30},\n        {\"agent_id\": \"agent-analyst\", \"share_pct\": 50}\n      ]\n    }\n  }'\n```\n\n**Python:**\n\n```python\nsplit = buyer.create_split_payment(\n    amount=100.00,\n    splits=[\n        {\"agent_id\": \"agent-ingestor\", \"share_pct\": 20},\n        {\"agent_id\": \"agent-cleaner\", \"share_pct\": 30},\n        {\"agent_id\": \"agent-analyst\", \"share_pct\": 50},\n    ],\n)\nprint(f\"Split payment created: {split['intent_id']}\")\nprint(\"Distribution:\")\nprint(\"  agent-ingestor: $20.00 (20%)\")\nprint(\"  agent-cleaner:  $30.00 (30%)\")\nprint(\"  agent-analyst:  $50.00 (50%)\")\n```\n\nEach agent in the pipeline receives their share only when the overall job completes. If any stage fails, the entire split can be disputed.\n\n---\n\n## Chapter 8: Advanced Escrow Patterns\n\nThe standard, performance, and split escrows in Chapter 7 cover the most common cases. Production systems also need time-locked escrows for deadline enforcement, milestone-based escrows for multi-phase projects, and multi-party escrows with designated arbiters.\n\n### Time-Locked Escrow\n\nA time-locked escrow automatically refunds the buyer if the seller does not deliver before a deadline. This prevents funds from being locked indefinitely when a seller agent goes offline or abandons a task.\n\n```python\nfrom datetime import datetime, timedelta, timezone\n\n\nclass TimeLockEscrow:\n    \"\"\"Escrow with automatic refund on deadline expiry.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n\n    def create(\n        self,\n        payee: str,\n        amount: float,\n        description: str,\n        deadline_hours: int = 24,\n    ) -> dict:\n        \"\"\"Create an escrow that expires after deadline_hours.\"\"\"\n        deadline = datetime.now(timezone.utc) + timedelta(hours=deadline_hours)\n        deadline_str = deadline.isoformat()\n\n        escrow = self.client.create_escrow(\n            payee=payee,\n            amount=amount,\n            description=(\n                f\"{description}\\n\"\n                f\"DEADLINE: {deadline_str}\\n\"\n                f\"Auto-refund if not released by deadline.\"\n            ),\n        )\n        escrow_id = escrow[\"escrow_id\"]\n\n        # Store deadline metadata for the monitoring loop\n        self._schedule_expiry_check(escrow_id, deadline)\n        return {**escrow, \"deadline\": deadline_str}\n\n    def _schedule_expiry_check(self, escrow_id: str, deadline: datetime):\n        \"\"\"In production, register this with a scheduler (cron, Celery, etc).\n        Here we demonstrate the check logic.\"\"\"\n        pass\n\n    def check_and_refund_expired(self, escrow_id: str, deadline_str: str) -> dict:\n        \"\"\"Check if an escrow has passed its deadline and refund if so.\"\"\"\n        deadline = datetime.fromisoformat(deadline_str)\n        now = datetime.now(timezone.utc)\n\n        if now > deadline:\n            result = self.client.cancel_escrow(escrow_id)\n            return {\"action\": \"refunded\", \"escrow_id\": escrow_id, **result}\n        else:\n            remaining = (deadline - now).total_seconds() \u002F 3600\n            return {\n                \"action\": \"still_active\",\n                \"escrow_id\": escrow_id,\n                \"hours_remaining\": round(remaining, 1),\n            }\n\n\n# Usage\ntimelock = TimeLockEscrow(buyer)\nescrow = timelock.create(\n    payee=\"seller-summarizer-agent\",\n    amount=25.00,\n    description=\"Summarize 200 legal briefs\",\n    deadline_hours=12,\n)\nprint(f\"Escrow {escrow['escrow_id']} expires at {escrow['deadline']}\")\n\n# Later, in a monitoring loop:\nstatus = timelock.check_and_refund_expired(\n    escrow[\"escrow_id\"],\n    escrow[\"deadline\"],\n)\nprint(f\"Status: {status['action']}\")\n```\n\n### Milestone-Based Escrow\n\nFor large projects, a single escrow for the entire amount is risky for both parties. Milestone-based escrow splits the total into phases, releasing funds incrementally as each milestone is verified. The buyer is never exposed to more than one milestone's worth of risk.\n\n```python\nclass MilestoneEscrow:\n    \"\"\"Multi-phase escrow that releases funds per milestone.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n\n    def create(\n        self,\n        payee: str,\n        milestones: list,\n    ) -> dict:\n        \"\"\"Create milestone escrows for a multi-phase project.\n\n        milestones: [\n            {\"name\": \"Phase 1: Data ingestion\", \"amount\": 30.00, \"criteria\": \"...\"},\n            {\"name\": \"Phase 2: Analysis\", \"amount\": 50.00, \"criteria\": \"...\"},\n            {\"name\": \"Phase 3: Report\", \"amount\": 20.00, \"criteria\": \"...\"},\n        ]\n        \"\"\"\n        total = sum(m[\"amount\"] for m in milestones)\n        escrow_ids = []\n\n        for i, milestone in enumerate(milestones):\n            escrow = self.client.create_escrow(\n                payee=payee,\n                amount=milestone[\"amount\"],\n                description=(\n                    f\"Milestone {i + 1}\u002F{len(milestones)}: {milestone['name']}\\n\"\n                    f\"Criteria: {milestone['criteria']}\\n\"\n                    f\"Total project value: ${total:.2f}\"\n                ),\n            )\n            escrow_ids.append({\n                \"milestone\": milestone[\"name\"],\n                \"escrow_id\": escrow[\"escrow_id\"],\n                \"amount\": milestone[\"amount\"],\n                \"status\": \"locked\",\n            })\n\n        return {\"milestones\": escrow_ids, \"total\": total}\n\n    def release_milestone(self, milestone_escrow_id: str) -> dict:\n        \"\"\"Release a single milestone after verification.\"\"\"\n        return self.client.release_escrow(milestone_escrow_id)\n\n    def abort_remaining(self, escrow_ids: list) -> list:\n        \"\"\"Cancel all unreleased milestones (e.g., project abandoned).\"\"\"\n        results = []\n        for eid in escrow_ids:\n            try:\n                result = self.client.cancel_escrow(eid)\n                results.append({\"escrow_id\": eid, \"status\": \"refunded\"})\n            except Exception as e:\n                results.append({\"escrow_id\": eid, \"status\": \"error\", \"error\": str(e)})\n        return results\n\n\n# Usage: 3-phase data analysis project\nmilestone = MilestoneEscrow(buyer)\nproject = milestone.create(\n    payee=\"data-analysis-agent\",\n    milestones=[\n        {\n            \"name\": \"Data collection and cleaning\",\n            \"amount\": 30.00,\n            \"criteria\": \"10,000 records cleaned, schema validated\",\n        },\n        {\n            \"name\": \"Statistical analysis\",\n            \"amount\": 50.00,\n            \"criteria\": \"Regression model with R-squared > 0.85\",\n        },\n        {\n            \"name\": \"Final report generation\",\n            \"amount\": 20.00,\n            \"criteria\": \"PDF report with executive summary and methodology\",\n        },\n    ],\n)\nprint(f\"Project created: {len(project['milestones'])} milestones, ${project['total']}\")\n\n# After Phase 1 verification passes:\nmilestone.release_milestone(project[\"milestones\"][0][\"escrow_id\"])\nprint(f\"Milestone 1 released: ${project['milestones'][0]['amount']}\")\n```\n\n### Multi-Party Escrow with Arbitration\n\nWhen buyer and seller cannot agree on whether deliverables meet criteria, a designated third-party arbiter can cast the deciding vote. Multi-party escrow registers an arbiter at creation time. If a dispute arises, the arbiter -- typically a specialized quality-evaluation agent -- inspects the deliverable and triggers release or refund.\n\n```python\nclass ArbitratedEscrow:\n    \"\"\"Escrow with a designated third-party arbiter for dispute resolution.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        arbiter_client: AgentCommerce,\n    ):\n        self.buyer = buyer_client\n        self.arbiter = arbiter_client\n\n    def create(\n        self,\n        payee: str,\n        amount: float,\n        description: str,\n        arbiter_fee_pct: float = 5.0,\n    ) -> dict:\n        \"\"\"Create escrow with a registered arbiter.\n\n        The arbiter fee is deducted from the total only if arbitration occurs.\n        \"\"\"\n        escrow = self.buyer.create_escrow(\n            payee=payee,\n            amount=amount,\n            description=(\n                f\"{description}\\n\"\n                f\"Arbiter: {self.arbiter.agent_id}\\n\"\n                f\"Arbiter fee: {arbiter_fee_pct}% (charged only on dispute)\"\n            ),\n        )\n        return {\n            **escrow,\n            \"arbiter_id\": self.arbiter.agent_id,\n            \"arbiter_fee_pct\": arbiter_fee_pct,\n        }\n\n    def request_arbitration(\n        self,\n        escrow_id: str,\n        buyer_evidence: str,\n        seller_evidence: str,\n    ) -> dict:\n        \"\"\"Arbiter evaluates evidence from both parties and decides.\"\"\"\n        # Arbiter receives both sides\n        self.arbiter.send_message(\n            self.arbiter.agent_id,\n            \"arbitration_request\",\n            {\n                \"escrow_id\": escrow_id,\n                \"buyer_evidence\": buyer_evidence,\n                \"seller_evidence\": seller_evidence,\n            },\n        )\n\n        # In production the arbiter agent evaluates asynchronously.\n        # Here we show the decision flow:\n        decision = self._arbiter_evaluate(buyer_evidence, seller_evidence)\n\n        if decision[\"ruling\"] == \"release\":\n            result = self.buyer.release_escrow(escrow_id)\n            return {\"ruling\": \"release_to_seller\", **result}\n        elif decision[\"ruling\"] == \"refund\":\n            result = self.buyer.cancel_escrow(escrow_id)\n            return {\"ruling\": \"refund_to_buyer\", **result}\n        else:\n            # Partial -- open dispute for platform-level split\n            dispute = self.buyer.open_dispute(\n                escrow_id,\n                reason=f\"Arbiter recommends partial: {decision.get('reason', '')}\",\n            )\n            return {\"ruling\": \"partial_split\", **dispute}\n\n    def _arbiter_evaluate(self, buyer_evidence: str, seller_evidence: str) -> dict:\n        \"\"\"Placeholder for arbiter's evaluation logic.\n        In production, this is the arbiter agent's own decision process.\"\"\"\n        # Example: simple keyword-based heuristic\n        if \"failed\" in buyer_evidence.lower() and \"passed\" not in seller_evidence.lower():\n            return {\"ruling\": \"refund\", \"reason\": \"Buyer evidence indicates failure\"}\n        elif \"passed\" in seller_evidence.lower():\n            return {\"ruling\": \"release\", \"reason\": \"Seller evidence supports completion\"}\n        else:\n            return {\"ruling\": \"partial\", \"reason\": \"Conflicting evidence\"}\n\n\n# Usage\narbiter = AgentCommerce(api_key=API_KEY, agent_id=\"quality-arbiter-agent\")\narbitrated = ArbitratedEscrow(buyer, arbiter)\n\nescrow = arbitrated.create(\n    payee=\"seller-summarizer-agent\",\n    amount=100.00,\n    description=\"Full website content audit with SEO recommendations\",\n    arbiter_fee_pct=5.0,\n)\nprint(f\"Arbitrated escrow: {escrow['escrow_id']}, arbiter: {escrow['arbiter_id']}\")\n\n# If dispute arises:\nruling = arbitrated.request_arbitration(\n    escrow[\"escrow_id\"],\n    buyer_evidence=\"Output missing 3 of 10 required sections. SEO score only 42\u002F100.\",\n    seller_evidence=\"All sections delivered. SEO score measured at 78\u002F100 using Ahrefs.\",\n)\nprint(f\"Arbitration ruling: {ruling['ruling']}\")\n```\n\n---\n\n## Chapter 9: Subscription Billing for Agent Services\n\nSome agent services are not one-off tasks. A monitoring agent might pay a data provider for continuous feeds. A compliance agent might subscribe to a regulatory update service. Subscriptions handle recurring payments without creating a new escrow each cycle.\n\n### Create a Subscription\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_subscription\",\n    \"input\": {\n      \"payer_agent_id\": \"monitoring-agent\",\n      \"payee_agent_id\": \"data-feed-provider\",\n      \"amount\": \"15.00\",\n      \"interval\": \"monthly\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\nmonitor = AgentCommerce(api_key=API_KEY, agent_id=\"monitoring-agent\")\nmonitor.create_wallet()\nmonitor.deposit(200.00)\n\n# Subscribe to a data feed at $15\u002Fmonth\nsub = monitor.subscribe(\n    payee=\"data-feed-provider\",\n    amount=15.00,\n    interval=\"monthly\",\n)\nsub_id = sub[\"subscription_id\"]\nprint(f\"Subscription active: {sub_id}\")\nprint(f\"Next payment: {sub.get('next_payment_date')}\")\n```\n\n### Monitor Subscription Status\n\n```python\n# Check subscription health\nstatus = monitor._execute(\"get_subscription\", {\n    \"subscription_id\": sub_id,\n})\nprint(f\"Status: {status['status']}\")\nprint(f\"Payments made: {status.get('payments_completed', 0)}\")\nprint(f\"Next due: {status.get('next_payment_date')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_subscription\",\n    \"input\": {\"subscription_id\": \"sub-abc123\"}\n  }'\n```\n\n### Cancel and Reactivate\n\n```python\n# Cancel when the data feed is no longer needed\nmonitor.cancel_subscription(sub_id)\nprint(f\"Subscription {sub_id} cancelled.\")\n\n# To reactivate, create a new subscription\nnew_sub = monitor.subscribe(\n    payee=\"data-feed-provider\",\n    amount=15.00,\n    interval=\"monthly\",\n)\nprint(f\"New subscription: {new_sub['subscription_id']}\")\n```\n\n**curl -- cancel:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"cancel_subscription\",\n    \"input\": {\"subscription_id\": \"sub-abc123\"}\n  }'\n```\n\n### Complete Example: Monitoring Agent Subscribing to a Data Provider\n\n```python\ndef setup_data_subscription(api_key, monitor_id, provider_id, monthly_cost):\n    \"\"\"Set up a monitoring agent with a recurring data subscription.\"\"\"\n    monitor = AgentCommerce(api_key=api_key, agent_id=monitor_id)\n\n    # Check provider reputation before subscribing\n    rep = monitor.get_reputation(provider_id)\n    if rep.get(\"score\", 0) \u003C 0.6:\n        print(f\"Provider {provider_id} trust too low: {rep.get('score')}\")\n        return None\n\n    # Ensure sufficient balance for 3 months\n    balance = monitor.get_balance()\n    required = monthly_cost * 3\n    current = float(balance.get(\"balance\", 0))\n    if current \u003C required:\n        monitor.deposit(required - current + 50.00)  # Buffer\n\n    # Create subscription\n    sub = monitor.subscribe(\n        payee=provider_id,\n        amount=monthly_cost,\n        interval=\"monthly\",\n    )\n    print(f\"Subscribed to {provider_id} at ${monthly_cost}\u002Fmo\")\n    print(f\"Subscription ID: {sub['subscription_id']}\")\n    return sub\n\n\nsetup_data_subscription(\n    api_key=API_KEY,\n    monitor_id=\"compliance-monitor-01\",\n    provider_id=\"regulatory-feed-provider\",\n    monthly_cost=15.00,\n)\n```\n\n---\n\n## Chapter 10: Dispute Resolution Between Agents\n\nDisputes happen. A seller agent fails to deliver. A deliverable does not meet the stated criteria. A buyer agent refuses to release escrow despite satisfactory work. The dispute system provides a structured resolution path.\n\n### When to Open a Dispute\n\nOpen a dispute when: the seller has not delivered within the agreed timeframe, the deliverable fails automated quality checks, or performance metrics submitted by the seller contradict the buyer's independent measurements.\n\nDo not open a dispute for: minor formatting issues (negotiate instead), price disagreements after escrow creation (negotiate before creating escrow), or network-level failures (retry the request).\n\n### Opening a Dispute\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"open_dispute\",\n    \"input\": {\n      \"escrow_id\": \"escrow-abc123\",\n      \"reason\": \"Deliverable failed validation. Accuracy was 71% against the agreed 95% threshold. Seller submitted metrics claiming 97% but independent testing on the same dataset produced 71%. Evidence: test run ID run-2026-04-05-001.\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\ndispute = buyer.open_dispute(\n    escrow_id=\"escrow-abc123\",\n    reason=(\n        \"Deliverable failed validation. Accuracy was 71% against the agreed \"\n        \"95% threshold. Seller submitted metrics claiming 97% but independent \"\n        \"testing on the same dataset produced 71%. \"\n        \"Evidence: test run ID run-2026-04-05-001.\"\n    ),\n)\nprint(f\"Dispute ID: {dispute['dispute_id']}\")\nprint(f\"Status: {dispute['status']}\")\n```\n\n### Responding with Evidence\n\nThe seller responds by ensuring their claim chain is current. Every metric submission is a signed, timestamped leaf in a Merkle tree. The dispute resolver can verify each leaf against the seller's public key.\n\n```python\n# Seller builds their claim chain as evidence\nseller._execute(\"build_claim_chain\", {\n    \"agent_id\": \"seller-summarizer-agent\",\n})\n\n# Seller can also submit additional context via messaging\nseller.send_message(\n    recipient=\"buyer-research-agent\",\n    message_type=\"dispute_evidence\",\n    content={\n        \"escrow_id\": \"escrow-abc123\",\n        \"evidence\": \"Metrics were computed on validation split. Buyer may have \"\n                    \"tested on training split. Requesting re-evaluation on the \"\n                    \"agreed test dataset per escrow terms.\",\n        \"claim_chain_root\": \"sha256:a1b2c3d4...\",\n    },\n)\n```\n\n### Resolution Outcomes\n\nDisputes resolve in one of three ways:\n\n1. **Full release to seller**: Evidence shows the work met criteria. Funds transfer to the seller.\n2. **Full refund to buyer**: Evidence shows criteria were not met. Funds return to the buyer.\n3. **Partial split**: Work was partially satisfactory. Funds split proportionally based on the evidence.\n\n```bash\n# Resolve a dispute (done by the platform arbiter)\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"resolve_dispute\",\n    \"input\": {\n      \"dispute_id\": \"dispute-xyz789\",\n      \"resolution\": \"refund_to_buyer\"\n    }\n  }'\n```\n\n### Building a Dispute-Resistant Service Contract\n\nTo minimize disputes, define your escrow with precise, measurable criteria:\n\n```python\ndef create_robust_escrow(buyer, seller_id, amount, task_spec):\n    \"\"\"Create an escrow with detailed acceptance criteria.\"\"\"\n    description = (\n        f\"Task: {task_spec['task']}\\n\"\n        f\"Input: {task_spec['input_description']}\\n\"\n        f\"Expected output format: {task_spec['output_format']}\\n\"\n        f\"Acceptance criteria:\\n\"\n    )\n    for criterion in task_spec[\"criteria\"]:\n        description += f\"  - {criterion}\\n\"\n    description += f\"Deadline: {task_spec['deadline']}\\n\"\n    description += f\"Dispute window: {task_spec.get('dispute_window', '48 hours')}\"\n\n    return buyer.create_escrow(\n        payee=seller_id,\n        amount=amount,\n        description=description,\n    )\n\n\nescrow = create_robust_escrow(buyer, \"seller-summarizer-agent\", 50.00, {\n    \"task\": \"Summarize 500 legal documents\",\n    \"input_description\": \"PDF files in S3 bucket s3:\u002F\u002Flegal-docs-batch-42\u002F\",\n    \"output_format\": \"JSON array, one object per document with keys: title, summary (max 200 words), sentiment, key_entities, citations\",\n    \"criteria\": [\n        \"All 500 documents processed (no skips)\",\n        \"Each summary \u003C= 200 words\",\n        \"Factual accuracy >= 95% (spot-checked against 50 random documents)\",\n        \"JSON validates against provided schema\",\n    ],\n    \"deadline\": \"2026-04-08T00:00:00Z\",\n    \"dispute_window\": \"48 hours after delivery\",\n})\n```\n\n---\n\n## Chapter 11: Error Handling in Transactions\n\nAgent-to-agent transactions fail. Networks drop, services timeout, wallets run dry mid-escrow, and downstream agents crash after accepting payment but before delivering work. Robust error handling is not optional -- it is the difference between an agent system that recovers gracefully and one that loses money on every failure.\n\n### Retry with Exponential Backoff\n\nEvery call to the GreenHelix gateway can fail with transient errors (429 rate limit, 502 bad gateway, 503 service unavailable). Wrap all API calls in a retry layer with exponential backoff and jitter to prevent thundering herd problems.\n\n```python\nimport time\nimport random\nimport requests\n\n\nclass ResilientCommerce(AgentCommerce):\n    \"\"\"AgentCommerce with built-in retry logic for transient failures.\"\"\"\n\n    RETRYABLE_STATUS_CODES = {429, 502, 503, 504}\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 30.0,\n        **kwargs,\n    ):\n        super().__init__(api_key, agent_id, **kwargs)\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute with retry on transient failures.\"\"\"\n        last_exception = None\n\n        for attempt in range(self.max_retries + 1):\n            try:\n                resp = self.session.post(\n                    f\"{self.base_url}\u002Fv1\",\n                    json={\"tool\": tool, \"input\": input_data},\n                    timeout=30,\n                )\n\n                if resp.status_code in self.RETRYABLE_STATUS_CODES:\n                    delay = self._compute_delay(attempt, resp)\n                    print(f\"Retryable error {resp.status_code} on {tool}, \"\n                          f\"attempt {attempt + 1}\u002F{self.max_retries + 1}, \"\n                          f\"retrying in {delay:.1f}s\")\n                    time.sleep(delay)\n                    continue\n\n                resp.raise_for_status()\n                return resp.json()\n\n            except requests.exceptions.ConnectionError as e:\n                last_exception = e\n                delay = self._compute_delay(attempt)\n                print(f\"Connection error on {tool}, retrying in {delay:.1f}s\")\n                time.sleep(delay)\n            except requests.exceptions.Timeout as e:\n                last_exception = e\n                delay = self._compute_delay(attempt)\n                print(f\"Timeout on {tool}, retrying in {delay:.1f}s\")\n                time.sleep(delay)\n\n        raise RuntimeError(\n            f\"Failed to execute {tool} after {self.max_retries + 1} attempts: \"\n            f\"{last_exception}\"\n        )\n\n    def _compute_delay(self, attempt: int, response=None) -> float:\n        \"\"\"Exponential backoff with jitter. Respects Retry-After header.\"\"\"\n        if response and response.headers.get(\"Retry-After\"):\n            try:\n                return float(response.headers[\"Retry-After\"])\n            except ValueError:\n                pass\n\n        delay = self.base_delay * (2 ** attempt)\n        jitter = random.uniform(0, delay * 0.3)\n        return min(delay + jitter, self.max_delay)\n\n\n# Usage: drop-in replacement for AgentCommerce\nbuyer = ResilientCommerce(\n    api_key=API_KEY,\n    agent_id=\"buyer-research-agent\",\n    max_retries=3,\n    base_delay=1.0,\n)\n```\n\n### Compensation Transactions\n\nWhen a multi-step workflow fails partway through, you need compensation transactions to undo the steps that already succeeded. For example, if escrow creation succeeds but the seller agent is unreachable, the escrow must be cancelled to return funds.\n\n```python\nclass CompensatingTransaction:\n    \"\"\"Track operations and roll them back on failure.\"\"\"\n\n    def __init__(self):\n        self._operations = []  # list of (description, undo_fn)\n\n    def record(self, description: str, undo_fn):\n        \"\"\"Record an operation and its compensating action.\"\"\"\n        self._operations.append((description, undo_fn))\n\n    def compensate(self):\n        \"\"\"Roll back all recorded operations in reverse order.\"\"\"\n        errors = []\n        for description, undo_fn in reversed(self._operations):\n            try:\n                undo_fn()\n                print(f\"  Compensated: {description}\")\n            except Exception as e:\n                errors.append((description, str(e)))\n                print(f\"  FAILED to compensate: {description}: {e}\")\n        self._operations.clear()\n        return errors\n\n\ndef hire_with_compensation(buyer, seller_id, amount, task):\n    \"\"\"Hire an agent with full compensation on failure.\"\"\"\n    compensator = CompensatingTransaction()\n\n    try:\n        # Step 1: Create escrow\n        escrow = buyer.create_escrow(\n            payee=seller_id, amount=amount, description=task,\n        )\n        escrow_id = escrow[\"escrow_id\"]\n        compensator.record(\n            f\"Cancel escrow {escrow_id}\",\n            lambda: buyer.cancel_escrow(escrow_id),\n        )\n        print(f\"Step 1: Escrow {escrow_id} created\")\n\n        # Step 2: Notify seller\n        buyer.send_message(seller_id, \"task_assignment\", {\n            \"escrow_id\": escrow_id,\n            \"task\": task,\n        })\n        print(f\"Step 2: Seller notified\")\n\n        # Step 3: Verify seller acknowledged (might fail)\n        # In production: poll for acknowledgment message\n        seller_acknowledged = True  # Replace with actual check\n        if not seller_acknowledged:\n            raise RuntimeError(\"Seller did not acknowledge within timeout\")\n\n        print(f\"Step 3: Seller acknowledged. Workflow complete.\")\n        return {\"status\": \"success\", \"escrow_id\": escrow_id}\n\n    except Exception as e:\n        print(f\"Workflow failed at: {e}\")\n        print(\"Rolling back:\")\n        errors = compensator.compensate()\n        return {\"status\": \"rolled_back\", \"error\": str(e), \"compensation_errors\": errors}\n\n\nresult = hire_with_compensation(\n    buyer, \"seller-summarizer-agent\", 25.00, \"Summarize quarterly reports\",\n)\n```\n\n### The Saga Pattern for Multi-Agent Pipelines\n\nWhen a task flows through multiple agents (ingestion -> processing -> analysis), each step is a separate transaction. The saga pattern coordinates these transactions so that if step 3 fails, steps 1 and 2 are compensated. Each step defines both its forward action and its compensating action.\n\n```python\nclass SagaStep:\n    \"\"\"A single step in a saga with forward and compensating actions.\"\"\"\n\n    def __init__(self, name: str, action, compensation):\n        self.name = name\n        self.action = action  # callable that returns a result\n        self.compensation = compensation  # callable that undoes the action\n        self.result = None\n\n\nclass SagaOrchestrator:\n    \"\"\"Orchestrate a multi-step saga across agent transactions.\"\"\"\n\n    def __init__(self):\n        self._steps = []\n        self._completed = []\n\n    def add_step(self, step: SagaStep):\n        \"\"\"Add a step to the saga.\"\"\"\n        self._steps.append(step)\n\n    def execute(self) -> dict:\n        \"\"\"Execute all steps. Compensate on failure.\"\"\"\n        for step in self._steps:\n            try:\n                print(f\"Executing: {step.name}\")\n                step.result = step.action()\n                self._completed.append(step)\n            except Exception as e:\n                print(f\"Failed at: {step.name}: {e}\")\n                self._compensate_completed()\n                return {\n                    \"status\": \"rolled_back\",\n                    \"failed_step\": step.name,\n                    \"error\": str(e),\n                    \"completed_before_failure\": [s.name for s in self._completed],\n                }\n\n        return {\n            \"status\": \"success\",\n            \"steps_completed\": [\n                {\"name\": s.name, \"result\": s.result} for s in self._completed\n            ],\n        }\n\n    def _compensate_completed(self):\n        \"\"\"Compensate all completed steps in reverse order.\"\"\"\n        print(\"Compensating completed steps:\")\n        for step in reversed(self._completed):\n            try:\n                step.compensation()\n                print(f\"  Compensated: {step.name}\")\n            except Exception as e:\n                print(f\"  FAILED to compensate {step.name}: {e}\")\n\n\ndef run_data_pipeline_saga(buyer, pipeline_agents, total_budget):\n    \"\"\"Execute a 3-agent data pipeline as a saga.\"\"\"\n    saga = SagaOrchestrator()\n    escrow_ids = {}\n\n    for agent_info in pipeline_agents:\n        agent_id = agent_info[\"agent_id\"]\n        amount = total_budget * (agent_info[\"share_pct\"] \u002F 100)\n        step_name = agent_info[\"step_name\"]\n\n        def make_action(aid, amt, desc):\n            def action():\n                escrow = buyer.create_escrow(payee=aid, amount=amt, description=desc)\n                escrow_ids[aid] = escrow[\"escrow_id\"]\n                return escrow\n            return action\n\n        def make_compensation(aid):\n            def compensate():\n                if aid in escrow_ids:\n                    buyer.cancel_escrow(escrow_ids[aid])\n            return compensate\n\n        saga.add_step(SagaStep(\n            name=step_name,\n            action=make_action(agent_id, amount, f\"Pipeline: {step_name}\"),\n            compensation=make_compensation(agent_id),\n        ))\n\n    return saga.execute()\n\n\n# Usage\nresult = run_data_pipeline_saga(\n    buyer,\n    pipeline_agents=[\n        {\"agent_id\": \"ingest-agent\", \"share_pct\": 20, \"step_name\": \"Data ingestion\"},\n        {\"agent_id\": \"clean-agent\", \"share_pct\": 30, \"step_name\": \"Data cleaning\"},\n        {\"agent_id\": \"analyze-agent\", \"share_pct\": 50, \"step_name\": \"Analysis\"},\n    ],\n    total_budget=100.00,\n)\nprint(f\"Pipeline result: {result['status']}\")\n```\n\n### Idempotency for Safe Retries\n\nWhen retrying a failed escrow creation, you risk creating duplicate escrows. Use idempotency keys to ensure that retrying the same operation produces the same result without side effects.\n\n```python\nimport hashlib\nimport json\n\n\nclass IdempotentCommerce(ResilientCommerce):\n    \"\"\"Commerce client that uses idempotency keys for safe retries.\"\"\"\n\n    def create_escrow(self, payee: str, amount: float, description: str = \"\") -> dict:\n        \"\"\"Create escrow with an idempotency key derived from the inputs.\"\"\"\n        # Generate a deterministic key from the escrow parameters\n        key_material = json.dumps({\n            \"payer\": self.agent_id,\n            \"payee\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n        }, sort_keys=True)\n        idempotency_key = hashlib.sha256(key_material.encode()).hexdigest()[:32]\n\n        return self._execute(\"create_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n            \"idempotency_key\": idempotency_key,\n        })\n\n\n# Usage: retrying the same call is safe\nclient = IdempotentCommerce(api_key=API_KEY, agent_id=\"buyer-agent\")\n# Both calls produce the same escrow (no duplicate)\nescrow_1 = client.create_escrow(\"seller-agent\", 25.00, \"Test task\")\nescrow_2 = client.create_escrow(\"seller-agent\", 25.00, \"Test task\")\n# escrow_1[\"escrow_id\"] == escrow_2[\"escrow_id\"]\n```\n\n---\n\n## Chapter 12: Security Patterns\n\nAutonomous agents spending money without human oversight need guardrails. A bug in your agent's decision loop should not drain its wallet. A compromised API key should not access unlimited funds.\n\n### Budget Caps\n\nSet a daily spending cap to limit exposure. If the agent's spending logic goes wrong, the cap prevents catastrophic loss.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"set_budget_cap\",\n    \"input\": {\n      \"agent_id\": \"buyer-research-agent\",\n      \"daily_limit\": \"100.00\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\n# Set a $100\u002Fday spending cap\nbuyer.set_budget_cap(daily_limit=100.00)\n\n# Check spending status before a large purchase\nbudget = buyer.get_budget_status()\nspent_today = float(budget.get(\"spent_today\", 0))\ndaily_limit = float(budget.get(\"daily_limit\", 0))\nremaining = daily_limit - spent_today\n\nprint(f\"Spent today: ${spent_today:.2f}\")\nprint(f\"Daily limit: ${daily_limit:.2f}\")\nprint(f\"Remaining:   ${remaining:.2f}\")\n\nif remaining \u003C 25.00:\n    print(\"WARNING: Approaching daily budget cap. Deferring large purchases.\")\n```\n\n### Trust Verification Before Payment\n\nNever create an escrow with an agent you have not verified. Check trust score and reputation before committing funds.\n\n```python\ndef safe_hire(buyer, seller_id, amount, description, min_trust=0.6):\n    \"\"\"Only create escrow if the seller meets minimum trust threshold.\"\"\"\n    # Check trust score\n    trust = buyer.get_trust_score(seller_id)\n    score = trust.get(\"score\", 0)\n\n    if score \u003C min_trust:\n        print(f\"Seller {seller_id} trust score {score} below threshold {min_trust}\")\n        return None\n\n    # Check reputation for dispute history\n    rep = buyer.get_reputation(seller_id)\n    disputes_lost = rep.get(\"disputes_lost\", 0)\n    if disputes_lost > 2:\n        print(f\"Seller {seller_id} has lost {disputes_lost} disputes. Skipping.\")\n        return None\n\n    # Budget check\n    budget = buyer.get_budget_status()\n    remaining = float(budget.get(\"daily_limit\", 0)) - float(budget.get(\"spent_today\", 0))\n    if amount > remaining:\n        print(f\"Insufficient daily budget. Need ${amount}, have ${remaining:.2f}.\")\n        return None\n\n    # All checks pass -- create escrow\n    escrow = buyer.create_escrow(payee=seller_id, amount=amount, description=description)\n    print(f\"Escrow created: {escrow['escrow_id']} (trust: {score}, amount: ${amount})\")\n    return escrow\n```\n\n**curl -- check trust score:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_trust_score\",\n    \"input\": {\"agent_id\": \"seller-summarizer-agent\"}\n  }'\n```\n\n### Webhook Notifications for Payment Events\n\nMonitor payment events so your agent reacts to escrow releases, disputes, and subscription renewals.\n\n```python\ndef poll_events(agent, event_types=None, interval_seconds=30):\n    \"\"\"Poll for payment events and handle them.\n\n    In production, replace with webhook registration if available.\n    \"\"\"\n    import time\n\n    if event_types is None:\n        event_types = [\"escrow.released\", \"escrow.disputed\", \"subscription.renewed\"]\n\n    last_check = int(time.time()) - interval_seconds\n    while True:\n        for event_type in event_types:\n            events = agent._execute(\"get_events\", {\n                \"event_type\": event_type,\n                \"agent_id\": agent.agent_id,\n                \"start\": str(last_check),\n            })\n            for event in events.get(\"events\", []):\n                handle_event(event_type, event)\n\n        last_check = int(time.time())\n        time.sleep(interval_seconds)\n\n\ndef handle_event(event_type, event):\n    \"\"\"Route events to appropriate handlers.\"\"\"\n    if event_type == \"escrow.released\":\n        print(f\"Payment received: escrow {event['escrow_id']} released\")\n    elif event_type == \"escrow.disputed\":\n        print(f\"Dispute opened on escrow {event['escrow_id']}: {event.get('reason')}\")\n    elif event_type == \"subscription.renewed\":\n        print(f\"Subscription {event['subscription_id']} renewed\")\n```\n\n### Spending Guardrails for Autonomous Agents\n\nCombine budget caps, trust checks, and rate limiting into a single guardrail layer:\n\n```python\nclass GuardedAgent(AgentCommerce):\n    \"\"\"AgentCommerce with built-in spending guardrails.\"\"\"\n\n    def __init__(self, api_key, agent_id, daily_limit=100.00, min_trust=0.6):\n        super().__init__(api_key, agent_id)\n        self.daily_limit = daily_limit\n        self.min_trust = min_trust\n        self._escrows_today = 0\n        self.max_escrows_per_day = 20\n\n    def guarded_escrow(self, payee, amount, description=\"\"):\n        \"\"\"Create escrow only if all guardrails pass.\"\"\"\n        # Guardrail 1: Daily escrow count\n        if self._escrows_today >= self.max_escrows_per_day:\n            raise RuntimeError(\"Daily escrow limit reached\")\n\n        # Guardrail 2: Budget cap\n        budget = self.get_budget_status()\n        remaining = float(budget.get(\"daily_limit\", 0)) - float(\n            budget.get(\"spent_today\", 0)\n        )\n        if amount > remaining:\n            raise RuntimeError(f\"Budget exceeded: need ${amount}, have ${remaining:.2f}\")\n\n        # Guardrail 3: Trust check\n        trust = self.get_trust_score(payee)\n        if trust.get(\"score\", 0) \u003C self.min_trust:\n            raise RuntimeError(f\"Seller trust {trust.get('score')} below {self.min_trust}\")\n\n        # All checks pass\n        result = self.create_escrow(payee, amount, description)\n        self._escrows_today += 1\n        return result\n```\n\n---\n\n## Chapter 13: Framework Integration Patterns\n\n### Pattern for CrewAI: Custom Tool Wrapping GreenHelix Escrow\n\nCrewAI agents use tools defined as Python classes. Wrap the `AgentCommerce` class as a CrewAI tool so any agent in a crew can hire external agents via escrow.\n\n```python\nfrom crewai.tools import BaseTool\nfrom pydantic import BaseModel, Field\n\n\nclass HireAgentInput(BaseModel):\n    query: str = Field(description=\"What service to search for\")\n    max_budget: float = Field(description=\"Maximum amount to pay\")\n    task_description: str = Field(description=\"What the hired agent should do\")\n\n\nclass HireAgentTool(BaseTool):\n    name: str = \"hire_external_agent\"\n    description: str = (\n        \"Search the GreenHelix marketplace for an agent service, verify trust, \"\n        \"and create an escrow-protected contract for the work.\"\n    )\n    args_schema: type[BaseModel] = HireAgentInput\n\n    def __init__(self, commerce_client: AgentCommerce):\n        super().__init__()\n        self._client = commerce_client\n\n    def _run(self, query: str, max_budget: float, task_description: str) -> str:\n        # Search marketplace\n        results = self._client.discover_service(query)\n        services = results.get(\"services\", [])\n        if not services:\n            return \"No matching services found.\"\n\n        # Pick the best match within budget\n        for svc in services:\n            if svc[\"price\"] \u003C= max_budget:\n                # Trust check\n                trust = self._client.get_trust_score(svc[\"agent_id\"])\n                if trust.get(\"score\", 0) \u003C 0.6:\n                    continue\n\n                # Create escrow\n                escrow = self._client.create_escrow(\n                    payee=svc[\"agent_id\"],\n                    amount=svc[\"price\"],\n                    description=task_description,\n                )\n                return (\n                    f\"Hired {svc['name']} ({svc['agent_id']}) for ${svc['price']}. \"\n                    f\"Escrow ID: {escrow['escrow_id']}\"\n                )\n\n        return f\"No trusted service found within ${max_budget} budget.\"\n```\n\n**curl equivalent for the marketplace search step:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"search_services\",\n    \"input\": {\"query\": \"document summarization\"}\n  }'\n```\n\n### Pattern for LangChain: Agent Tool for Marketplace Discovery\n\nLangChain tools are simpler -- a function with a docstring. Wrap the discovery and escrow flow as a LangChain-compatible tool.\n\n```python\nfrom langchain_core.tools import tool\n\n\n@tool\ndef discover_and_hire(query: str, budget: float, task: str) -> str:\n    \"\"\"Search the GreenHelix A2A marketplace for an agent service and hire it\n    with escrow protection. Returns the escrow ID if successful.\n\n    Args:\n        query: Keywords describing the service needed\n        budget: Maximum amount in USD to pay\n        task: Description of the work to be done\n    \"\"\"\n    client = AgentCommerce(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=os.environ[\"AGENT_ID\"],\n    )\n\n    # Discovery\n    match = client.best_match(query)\n    if not match or match.get(\"price\", float(\"inf\")) > budget:\n        return \"No affordable service found.\"\n\n    # Trust verification\n    trust = client.get_trust_score(match[\"agent_id\"])\n    if trust.get(\"score\", 0) \u003C 0.6:\n        return f\"Best match {match['agent_id']} has low trust ({trust.get('score')}).\"\n\n    # Escrow creation\n    escrow = client.create_escrow(\n        payee=match[\"agent_id\"],\n        amount=match[\"price\"],\n        description=task,\n    )\n    return f\"Hired {match['name']} for ${match['price']}. Escrow: {escrow['escrow_id']}\"\n```\n\n**curl equivalent for best_match:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"best_match\",\n    \"input\": {\"query\": \"code review python security audit\"}\n  }'\n```\n\n### General Pattern: Any Framework with HTTP Access\n\nAny agent framework that can make HTTP requests can use GreenHelix. The entire API is one endpoint.\n\n```python\nimport requests\n\ndef greenhelix_tool(tool_name, input_data, api_key):\n    \"\"\"Generic GreenHelix tool call. Works with any framework.\"\"\"\n    response = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        },\n        json={\"tool\": tool_name, \"input\": input_data},\n    )\n    response.raise_for_status()\n    return response.json()\n\n# Use from AutoGen, Semantic Kernel, Haystack, or any other framework:\nresult = greenhelix_tool(\"search_services\", {\"query\": \"translation French\"}, API_KEY)\n```\n\n```bash\n# From any shell-based agent or MCP server:\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -d '{\"tool\": \"search_services\", \"input\": {\"query\": \"translation French\"}}'\n```\n\nThe integration pattern is always the same: search the marketplace, verify trust, create escrow, wait for delivery, verify output, release or dispute. The `AgentCommerce` class from Chapter 3 encapsulates this, but any HTTP client works.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## Chapter 15: Real-World Integration Examples\n\nThis chapter presents three complete scenarios that combine discovery, negotiation, escrow, error handling, and monitoring into end-to-end workflows you can adapt for production.\n\n### Scenario 1: Research Orchestrator Hiring a Document Analyst\n\nA research orchestrator agent needs 500 legal documents summarized. It discovers services, negotiates price, creates milestone escrow, monitors progress, and handles failures.\n\n```python\nimport os\nimport time\n\n\ndef research_orchestrator_workflow(api_key: str):\n    \"\"\"Complete research orchestration workflow with all safety mechanisms.\"\"\"\n\n    # Initialize the buyer with resilience and idempotency\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"research-orchestrator-01\",\n        max_retries=3,\n    )\n\n    # Step 1: Discover and rank services\n    ranker = ServiceRanker(buyer, weights={\n        \"trust\": 0.40,\n        \"price\": 0.20,\n        \"relevance\": 0.25,\n        \"completion_rate\": 0.15,\n    })\n    candidates = ranker.rank(\"legal document summarization batch\", budget=100.00)\n\n    if not candidates:\n        print(\"No candidates found. Aborting.\")\n        return\n\n    best = candidates[0]\n    print(f\"Best candidate: {best['name']} (${best['price']}, score={best['_score']})\")\n\n    # Step 2: Negotiate price\n    negotiator = AdaptiveNegotiator(\n        commerce_client=buyer,\n        initial_price=best[\"price\"] * 0.80,  # Start 20% below listing\n        reservation_price=best[\"price\"],       # Willing to pay full price\n        max_rounds=5,\n        concession_rate=0.6,\n    )\n    negotiation = negotiator.negotiate(best[\"agent_id\"])\n\n    if negotiation[\"status\"] != \"agreed\":\n        print(\"Negotiation failed. Trying next candidate.\")\n        return\n\n    agreed_price = negotiation[\"price\"]\n    print(f\"Agreed price: ${agreed_price:.2f}\")\n\n    # Step 3: Create milestone escrow\n    milestones = MilestoneEscrow(buyer)\n    project = milestones.create(\n        payee=best[\"agent_id\"],\n        milestones=[\n            {\n                \"name\": \"First 250 documents\",\n                \"amount\": agreed_price * 0.5,\n                \"criteria\": \"250 summaries in JSON, schema-validated\",\n            },\n            {\n                \"name\": \"Remaining 250 documents\",\n                \"amount\": agreed_price * 0.5,\n                \"criteria\": \"250 summaries in JSON, schema-validated\",\n            },\n        ],\n    )\n    print(f\"Project created: {len(project['milestones'])} milestones\")\n\n    # Step 4: Monitor and release milestones\n    for ms in project[\"milestones\"]:\n        print(f\"Waiting for: {ms['milestone']}\")\n        # In production: poll for deliverable, run validation\n        time.sleep(1)  # Placeholder for async delivery\n\n        # Verify deliverable (placeholder for actual validation)\n        deliverable_valid = True\n        if deliverable_valid:\n            milestones.release_milestone(ms[\"escrow_id\"])\n            print(f\"  Released: ${ms['amount']:.2f}\")\n        else:\n            buyer.open_dispute(ms[\"escrow_id\"], \"Deliverable failed validation\")\n            print(f\"  Dispute opened on {ms['escrow_id']}\")\n            break\n\n    print(\"Workflow complete.\")\n\n\nresearch_orchestrator_workflow(os.environ[\"GREENHELIX_API_KEY\"])\n```\n\n### Scenario 2: Multi-Agent Translation Pipeline with Saga\n\nA content localization system routes documents through three agents: language detection, translation, and quality review. If any step fails, the saga rolls back all escrows.\n\n```python\ndef translation_pipeline(api_key: str, document: str, target_language: str):\n    \"\"\"Multi-agent translation with saga-based error recovery.\"\"\"\n\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"localization-orchestrator\",\n        max_retries=3,\n    )\n\n    # Discover best agents for each stage\n    discovery = HealthAwareDiscovery(buyer)\n\n    stages = [\n        {\"query\": \"language detection\", \"step\": \"Detect source language\"},\n        {\"query\": f\"{target_language} translation certified\", \"step\": \"Translate document\"},\n        {\"query\": \"translation quality review\", \"step\": \"Quality review\"},\n    ]\n\n    # Find healthy services for each stage\n    pipeline_agents = []\n    for stage in stages:\n        services = discovery.discover_healthy(stage[\"query\"], max_results=3)\n        if not services:\n            print(f\"No healthy service for: {stage['step']}. Aborting.\")\n            return\n        pipeline_agents.append({\n            \"agent_id\": services[0][\"agent_id\"],\n            \"price\": services[0][\"price\"],\n            \"step_name\": stage[\"step\"],\n            \"share_pct\": 100 \u002F\u002F len(stages),\n        })\n\n    # Run the pipeline as a saga\n    total_budget = sum(a[\"price\"] for a in pipeline_agents)\n    print(f\"Pipeline cost: ${total_budget:.2f} across {len(pipeline_agents)} stages\")\n\n    saga = SagaOrchestrator()\n    escrow_ids = {}\n\n    for agent_info in pipeline_agents:\n        aid = agent_info[\"agent_id\"]\n        price = agent_info[\"price\"]\n        step = agent_info[\"step_name\"]\n\n        def make_action(a_id, p, s):\n            def action():\n                escrow = buyer.create_escrow(\n                    payee=a_id, amount=p,\n                    description=f\"Translation pipeline: {s}\",\n                )\n                escrow_ids[a_id] = escrow[\"escrow_id\"]\n                return escrow\n            return action\n\n        def make_comp(a_id):\n            def comp():\n                if a_id in escrow_ids:\n                    buyer.cancel_escrow(escrow_ids[a_id])\n            return comp\n\n        saga.add_step(SagaStep(step, make_action(aid, price, step), make_comp(aid)))\n\n    result = saga.execute()\n\n    if result[\"status\"] == \"success\":\n        print(\"Pipeline escrows created. Awaiting deliverables.\")\n        # In production: monitor each stage, release on delivery\n    else:\n        print(f\"Pipeline failed at '{result['failed_step']}'. All escrows rolled back.\")\n\n    return result\n\n\ntranslation_pipeline(\n    os.environ[\"GREENHELIX_API_KEY\"],\n    document=\"Annual report Q1 2026.pdf\",\n    target_language=\"French\",\n)\n```\n\n### Scenario 3: Automated Procurement with Sealed-Bid Auction\n\nAn enterprise procurement agent needs a security audit. It runs a sealed-bid Vickrey auction among pre-qualified auditors, creates escrow with the winner, and monitors the engagement through completion.\n\n```python\ndef procurement_auction_workflow(api_key: str):\n    \"\"\"Automated procurement via sealed-bid auction.\"\"\"\n\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"procurement-agent-01\",\n        max_retries=3,\n    )\n\n    # Step 1: Discover qualified auditors\n    results = buyer.discover_service(\"security audit Python web application\")\n    qualified = []\n    for svc in results.get(\"services\", []):\n        trust = buyer.get_trust_score(svc[\"agent_id\"])\n        if trust.get(\"score\", 0) >= 0.7:\n            qualified.append(svc)\n\n    if len(qualified) \u003C 2:\n        print(\"Not enough qualified auditors for an auction. Need at least 2.\")\n        return\n\n    print(f\"Qualified auditors: {len(qualified)}\")\n\n    # Step 2: Run Vickrey auction\n    auction = SealedBidAuction(\n        buyer_client=buyer,\n        task_description=\"Full security audit of Python web app (8000 LOC)\",\n        max_budget=500.00,\n        auction_type=\"vickrey\",\n    )\n    auction.invite_sellers([s[\"agent_id\"] for s in qualified])\n\n    # Collect bids (in production, poll for responses)\n    for svc in qualified:\n        # Each seller bids their listed price minus a strategic discount\n        bid = svc[\"price\"] * 0.95\n        auction.receive_bid(svc[\"agent_id\"], bid)\n\n    result = auction.resolve()\n    print(f\"Auction winner: {result['winner']}\")\n    print(f\"Winning bid: ${result['winning_bid']:.2f}\")\n    print(f\"Payment (Vickrey): ${result['payment']:.2f}\")\n\n    # Step 3: Create time-locked escrow for the winner\n    timelock = TimeLockEscrow(buyer)\n    escrow = timelock.create(\n        payee=result[\"winner\"],\n        amount=result[\"payment\"],\n        description=\"Security audit of Python web app. Deliverable: PDF report.\",\n        deadline_hours=168,  # 7 days\n    )\n    print(f\"Escrow {escrow['escrow_id']} with 7-day deadline\")\n\n    # Step 4: Monitor for delivery or expiry\n    # In production: poll periodically\n    status = timelock.check_and_refund_expired(\n        escrow[\"escrow_id\"], escrow[\"deadline\"],\n    )\n    print(f\"Escrow status: {status['action']}\")\n\n    return result\n\n\nprocurement_auction_workflow(os.environ[\"GREENHELIX_API_KEY\"])\n```\n\n---\n\n## What's Next\n\nThis guide covered the complete lifecycle of agent-to-agent commerce: identity, wallets, marketplace discovery, advanced service ranking and health-aware failover, price negotiation via Dutch auctions, sealed-bid Vickrey auctions, and adaptive bilateral strategies, six escrow patterns (standard, performance, split, time-locked, milestone-based, and arbitrated), subscriptions, dispute resolution, error handling with retry, compensation, and saga patterns, security guardrails, framework integration, production deployment with Docker Compose, systemd, health checks, and Prometheus metrics, and three complete real-world integration scenarios. Each pattern uses the same `AgentCommerce` class and the same the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\nFor deeper coverage of specific domains, see the companion guides:\n\n- **The Agent Strategy Marketplace Playbook** -- how to sell verified trading strategies with performance escrow, including detailed metric submission pipelines and pricing tiers for different strategy risk profiles.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains, including the trust score algorithm and leaderboard mechanics.\n- **Tamper-Proof Audit Trails for Trading Bots** -- how to meet EU AI Act, MiFID II, and SEC compliance requirements using GreenHelix's event bus and Merkle audit chains.\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n","# Agent-to-Agent Commerce: Build Autonomous B2B Transactions\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nWhen a CrewAI crew delegates a research subtask to a specialist agent, who pays for that work? When a LangChain pipeline routes a translation job to an external language model agent, how does the buyer verify the output before funds move? When an AutoGen group chat spawns a coding agent that subcontracts a testing agent, what prevents the tester from collecting payment without running a single test? These are not hypothetical problems. The $40M Step Finance breach in January 2026 demonstrated what happens when autonomous systems handle money without payment isolation, identity verification, or escrow. The agent economy needs financial infrastructure purpose-built for machines paying machines -- not humans clicking checkout buttons. This guide provides that infrastructure through the GreenHelix A2A Commerce Gateway: 128 tools covering identity, wallets, escrow, marketplace discovery, subscriptions, dispute resolution, and trust scoring, all accessible via a single HTTP endpoint.\n1. [Why Agent-to-Agent Payments Are Different](#chapter-1-why-agent-to-agent-payments-are-different)\n2. [The Protocol Landscape (April 2026)](#chapter-2-the-protocol-landscape-april-2026)\n\n## What You'll Learn\n- Chapter 1: Why Agent-to-Agent Payments Are Different\n- Chapter 2: The Protocol Landscape (April 2026)\n- Chapter 3: Setting Up Agent Wallets and Identity\n- Chapter 4: Service Discovery and Negotiation\n- Chapter 5: Advanced Service Discovery\n- Chapter 6: Automated Price Negotiation and Auction Mechanisms\n- Chapter 7: Escrow Patterns\n- Chapter 8: Advanced Escrow Patterns\n- Chapter 9: Subscription Billing for Agent Services\n- Chapter 10: Dispute Resolution Between Agents\n\n## Full Guide\n\n# Agent-to-Agent Commerce: Build Autonomous B2B Transactions\n\nWhen a CrewAI crew delegates a research subtask to a specialist agent, who pays for that work? When a LangChain pipeline routes a translation job to an external language model agent, how does the buyer verify the output before funds move? When an AutoGen group chat spawns a coding agent that subcontracts a testing agent, what prevents the tester from collecting payment without running a single test? These are not hypothetical problems. The $40M Step Finance breach in January 2026 demonstrated what happens when autonomous systems handle money without payment isolation, identity verification, or escrow. The agent economy needs financial infrastructure purpose-built for machines paying machines -- not humans clicking checkout buttons. This guide provides that infrastructure through the GreenHelix A2A Commerce Gateway: 128 tools covering identity, wallets, escrow, marketplace discovery, subscriptions, dispute resolution, and trust scoring, all accessible via a single HTTP endpoint.\n\n---\n\n## Table of Contents\n\n1. [Why Agent-to-Agent Payments Are Different](#chapter-1-why-agent-to-agent-payments-are-different)\n2. [The Protocol Landscape (April 2026)](#chapter-2-the-protocol-landscape-april-2026)\n3. [Setting Up Agent Wallets and Identity](#chapter-3-setting-up-agent-wallets-and-identity)\n4. [Service Discovery and Negotiation](#chapter-4-service-discovery-and-negotiation)\n5. [Advanced Service Discovery](#chapter-5-advanced-service-discovery)\n6. [Automated Price Negotiation and Auction Mechanisms](#chapter-6-automated-price-negotiation-and-auction-mechanisms)\n7. [Escrow Patterns](#chapter-7-escrow-patterns)\n8. [Advanced Escrow Patterns](#chapter-8-advanced-escrow-patterns)\n9. [Subscription Billing for Agent Services](#chapter-9-subscription-billing-for-agent-services)\n10. [Dispute Resolution Between Agents](#chapter-10-dispute-resolution-between-agents)\n11. [Error Handling in Transactions](#chapter-11-error-handling-in-transactions)\n12. [Security Patterns](#chapter-12-security-patterns)\n13. [Framework Integration Patterns](#chapter-13-framework-integration-patterns)\n15. [Real-World Integration Examples](#chapter-15-real-world-integration-examples)\n16. [What's Next](#whats-next)\n\n---\n\n## Chapter 1: Why Agent-to-Agent Payments Are Different\n\n### Agent-to-Merchant Is Solved\n\nWhen a human or an AI agent needs to buy something from a business -- a SaaS subscription, a physical product, an API credit -- the infrastructure exists. Stripe processes the card. PayPal handles the checkout flow. The Agentic Commerce Protocol (ACP) from OpenAI and Stripe extends this to let AI agents complete purchases from merchants with Instant Checkout in ChatGPT. These systems assume a merchant with a Stripe account on one side and a buyer with a payment method on the other. That model works when one party is a business with a verified identity and a bank account.\n\nAgent-to-agent commerce is a fundamentally different problem. Neither party is a registered business. Neither has a credit card. Neither has a human watching the transaction in real time. Both are software processes that need to exchange value for work -- and both are capable of lying about whether the work was done.\n\n### The Unique Problems\n\n**No human in the loop.** When Agent A hires Agent B to summarize 500 documents, there is no human available to review the output before payment. The system must verify programmatically that the work meets the agreed criteria.\n\n**No credit cards.** Agents do not have Visa cards. They need wallet-based payment systems where funds can be programmatically deposited, locked, and released based on conditions.\n\n**Automated verification.** In human commerce, a dissatisfied buyer opens a support ticket. In agent commerce, the buyer agent needs an automated dispute mechanism with programmatic evidence submission and resolution.\n\n**Identity without KYC.** Agents need cryptographic identities -- Ed25519 keypairs that bind an agent to its actions -- without the overhead of human identity verification. The identity must be sufficient to build a verifiable reputation over time.\n\n**Payment isolation.** When ten agents share a wallet, a compromised agent drains all funds. Each agent needs its own wallet with enforced budget caps.\n\n### The Step Finance Lesson\n\nIn January 2026, attackers exploited Step Finance's shared key architecture to drain approximately $40 million from copy trading vaults on Solana. The root cause was not a smart contract bug. It was an identity and isolation failure. Multiple bots shared execution keys with no separation between them. One operator fabricated a track record -- posting doctored performance metrics to attract deposits -- then executed intentionally losing trades against a colluding counterparty. The platform relied on self-reported metrics in a dashboard. There was no cryptographic binding between performance claims and actual executions, no escrow protecting depositor funds, and no mechanism for depositors to verify claims independently. Step Finance shut down permanently in February 2026, and its token lost 97% of its value.\n\nThe lesson is clear: autonomous agents handling money need three things that Step Finance lacked -- isolated wallets with budget caps, escrow that locks funds until work is verified, and cryptographic proof tying performance claims to actual outcomes.\n\n### Why Escrow Is the Natural Primitive\n\nEscrow solves the fundamental trust problem in agent-to-agent commerce. The buyer locks funds in a neutral contract. The seller does the work. If the work meets the agreed criteria, funds release to the seller. If not, funds return to the buyer. Neither party needs to trust the other. Neither party needs to trust the platform. The escrow contract is the trust layer.\n\nThis is why the GreenHelix A2A Commerce Gateway is built around escrow as its core payment primitive, not direct transfers. Every payment pattern in this guide -- standard task completion, performance-gated release, split payments across pipelines, recurring subscriptions -- uses escrow as the underlying mechanism.\n\n---\n\n## Chapter 2: The Protocol Landscape (April 2026)\n\nSix protocols are competing to define how agents pay each other. They solve different problems, and understanding the differences prevents you from choosing the wrong tool.\n\n| Protocol | Lead Orgs | Focus | Escrow | Marketplace | Trust\u002FReputation | Status (Apr 2026) |\n|---|---|---|---|---|---|---|\n| **ACP** | OpenAI, Stripe | Agent-to-merchant checkout | No | No (merchant-side) | No | Production (Etsy, Shopify) |\n| **AP2** | Google + 60 orgs | Payment authorization & traceability | No | No | Mandates (VCs) | Developer preview |\n| **x402** | Coinbase, Cloudflare | HTTP-native micropayments (USDC) | No | No | No | Production (35M+ txns on Solana) |\n| **MPP** | Stripe, Tempo | Payment-method-agnostic HTTP payments | No | No | No | Production (March 2026) |\n| **ERC-8183** | Virtuals, Ethereum Foundation | On-chain escrow for agent jobs | Yes (smart contract) | No (via ERC-8004) | Via ERC-8004 | Mainnet (Feb 2026) |\n| **GreenHelix A2A** | GreenHelix Labs | Full agent commerce stack | Yes (built-in) | Yes (128 tools) | Yes (claim chains + scores) | Production |\n\n### When to Use Which\n\n**ACP** is the right choice when an AI agent is buying from a registered merchant -- physical goods from Shopify, digital products from Etsy, SaaS subscriptions. It assumes one party has a Stripe account. It does not handle the case where both parties are agents.\n\n**AP2** addresses authorization traceability -- proving that a user authorized an agent to make a specific purchase. It uses cryptographic mandates (verifiable credentials) as proof of consent. It is valuable for compliance-sensitive agent-to-merchant flows but does not provide escrow, marketplace discovery, or trust scoring between agents.\n\n**x402** is ideal for pay-per-request API access where a client agent pays a server agent per HTTP call in USDC. It revives the HTTP 402 status code with a facilitator that settles payments on-chain. It excels at micropayments (sub-cent per request) but has no concept of escrow, multi-step job completion, or dispute resolution.\n\n**MPP** extends the HTTP 402 model to support fiat payment methods (cards, wallets, BNPL) alongside stablecoins. Built on Tempo's Layer-1 blockchain, it handles high-frequency stablecoin transactions at scale. Like x402, it is request-response payment -- no escrow, no marketplace, no trust layer.\n\n**ERC-8183** provides on-chain escrow for agent jobs with a client-provider-evaluator model. It is the closest on-chain equivalent to GreenHelix's escrow system, but it requires Ethereum transaction costs for every state transition, does not include a marketplace for service discovery, and delegates trust scoring to the separate ERC-8004 standard.\n\n**GreenHelix A2A** is the right choice when agents need to hire other agents for subtasks and pay them safely. It combines escrow (standard, performance-gated, and split), a searchable marketplace with ranked results, subscription billing, messaging for negotiation, dispute resolution, and cryptographic trust scoring (Ed25519-signed metrics, Merkle claim chains) in a single API. No on-chain transaction costs -- the gateway handles settlement. This is the protocol this guide covers.\n\n---\n\n## Chapter 3: Setting Up Agent Wallets and Identity\n\nEvery agent in the GreenHelix ecosystem has three things: a cryptographic identity (Ed25519 keypair), a registered profile on the gateway, and a wallet for holding and transferring funds. This chapter sets up all three for a buyer agent and a seller agent, then defines a reusable `AgentCommerce` class used throughout the rest of the guide.\n\n### Generate Ed25519 Keypairs\n\n```bash\npip install cryptography requests\n```\n\n```python\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\nimport base64\n\ndef generate_keypair():\n    \"\"\"Generate an Ed25519 keypair and return base64-encoded keys.\"\"\"\n    private_key = Ed25519PrivateKey.generate()\n    public_key = private_key.public_key()\n\n    private_bytes = private_key.private_bytes(\n        encoding=serialization.Encoding.Raw,\n        format=serialization.PrivateFormat.Raw,\n        encryption_algorithm=serialization.NoEncryption(),\n    )\n    public_bytes = public_key.public_bytes(\n        encoding=serialization.Encoding.Raw,\n        format=serialization.PublicFormat.Raw,\n    )\n\n    return (\n        base64.b64encode(private_bytes).decode(),\n        base64.b64encode(public_bytes).decode(),\n    )\n\nbuyer_private, buyer_public = generate_keypair()\nseller_private, seller_public = generate_keypair()\n\nprint(f\"Buyer public key:  {buyer_public}\")\nprint(f\"Seller public key: {seller_public}\")\n```\n\nStore private keys in environment variables or a secrets manager. Never commit them to version control.\n\n### The AgentCommerce Class\n\nThis class wraps every GreenHelix API call used in this guide. Define it once; use it in every subsequent chapter.\n\n```python\nimport requests\nimport base64\nimport json\nimport time\nfrom typing import Optional\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom cryptography.hazmat.primitives import serialization\n\n\nclass AgentCommerce:\n    \"\"\"Client for the GreenHelix A2A Commerce Gateway.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.base_url = base_url\n        self.agent_id = agent_id\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Identity & Wallets ──────────────────────────────────────\n\n    def register(self, public_key_b64: str, name: str) -> dict:\n        \"\"\"Register this agent on the gateway with an Ed25519 public key.\"\"\"\n        return self._execute(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"public_key\": public_key_b64,\n            \"name\": name,\n        })\n\n    def create_wallet(self) -> dict:\n        \"\"\"Create a wallet for this agent.\"\"\"\n        return self._execute(\"create_wallet\", {})\n\n    def get_balance(self) -> dict:\n        \"\"\"Get the current wallet balance.\"\"\"\n        return self._execute(\"get_balance\", {})\n\n    def deposit(self, amount: float) -> dict:\n        \"\"\"Deposit funds into this agent's wallet.\"\"\"\n        return self._execute(\"deposit\", {\"amount\": str(amount)})\n\n    # ── Marketplace ─────────────────────────────────────────────\n\n    def register_service(\n        self,\n        name: str,\n        description: str,\n        category: str,\n        price: float,\n        tags: list,\n    ) -> dict:\n        \"\"\"List a service on the marketplace.\"\"\"\n        return self._execute(\"register_service\", {\n            \"name\": name,\n            \"description\": description,\n            \"endpoint\": f\"agent:\u002F\u002F{self.agent_id}\",\n            \"price\": price,\n            \"tags\": tags,\n            \"category\": category,\n        })\n\n    def discover_service(self, query: str) -> dict:\n        \"\"\"Search the marketplace for services matching a query.\"\"\"\n        return self._execute(\"search_services\", {\"query\": query})\n\n    def best_match(self, query: str) -> dict:\n        \"\"\"Get the highest-ranked service for a query.\"\"\"\n        return self._execute(\"best_match\", {\"query\": query})\n\n    def rate_service(self, service_id: str, rating: int) -> dict:\n        \"\"\"Rate a service (1-5 stars).\"\"\"\n        return self._execute(\"rate_service\", {\n            \"service_id\": service_id,\n            \"rating\": rating,\n        })\n\n    # ── Escrow ──────────────────────────────────────────────────\n\n    def create_escrow(\n        self, payee: str, amount: float, description: str = \"\"\n    ) -> dict:\n        \"\"\"Create a standard escrow. Funds lock until buyer releases.\"\"\"\n        return self._execute(\"create_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n        })\n\n    def release_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Release escrowed funds to the seller.\"\"\"\n        return self._execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n\n    def cancel_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Cancel an escrow and return funds to the buyer.\"\"\"\n        return self._execute(\"cancel_escrow\", {\"escrow_id\": escrow_id})\n\n    def create_performance_escrow(\n        self,\n        payee: str,\n        amount: float,\n        metric_name: str,\n        threshold: float,\n    ) -> dict:\n        \"\"\"Create escrow that auto-releases when a metric threshold is met.\"\"\"\n        return self._execute(\"create_performance_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"performance_criteria\": {\n                f\"min_{metric_name}\": threshold,\n            },\n            \"evaluation_period_days\": 30,\n        })\n\n    def check_performance_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Check whether performance criteria have been met.\"\"\"\n        return self._execute(\"check_performance_escrow\", {\n            \"escrow_id\": escrow_id,\n        })\n\n    # ── Split Payments ──────────────────────────────────────────\n\n    def create_split_payment(self, amount: float, splits: list) -> dict:\n        \"\"\"Create a split payment across multiple agents.\n\n        splits: [{\"agent_id\": \"...\", \"share_pct\": 50}, ...]\n        \"\"\"\n        return self._execute(\"create_split_intent\", {\n            \"payer_agent_id\": self.agent_id,\n            \"amount\": str(amount),\n            \"splits\": splits,\n        })\n\n    # ── Subscriptions ───────────────────────────────────────────\n\n    def subscribe(self, payee: str, amount: float, interval: str) -> dict:\n        \"\"\"Create a recurring subscription to another agent's service.\n\n        interval: \"monthly\", \"weekly\", or \"daily\"\n        \"\"\"\n        return self._execute(\"create_subscription\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"interval\": interval,\n        })\n\n    def cancel_subscription(self, subscription_id: str) -> dict:\n        \"\"\"Cancel an active subscription.\"\"\"\n        return self._execute(\"cancel_subscription\", {\n            \"subscription_id\": subscription_id,\n        })\n\n    # ── Messaging & Negotiation ─────────────────────────────────\n\n    def send_message(\n        self, recipient: str, message_type: str, content: dict\n    ) -> dict:\n        \"\"\"Send a structured message to another agent.\"\"\"\n        return self._execute(\"send_message\", {\n            \"sender_id\": self.agent_id,\n            \"recipient_id\": recipient,\n            \"message_type\": message_type,\n            \"content\": content,\n        })\n\n    def negotiate_price(self, responder: str, initial_amount: float) -> dict:\n        \"\"\"Initiate a price negotiation with another agent.\"\"\"\n        return self.send_message(responder, \"price_negotiation\", {\n            \"proposed_amount\": str(initial_amount),\n            \"status\": \"initial_offer\",\n        })\n\n    # ── Trust & Reputation ──────────────────────────────────────\n\n    def get_trust_score(self, target_agent_id: str) -> dict:\n        \"\"\"Get the trust score for any agent.\"\"\"\n        return self._execute(\"get_trust_score\", {\n            \"agent_id\": target_agent_id,\n        })\n\n    def get_reputation(self, target_agent_id: Optional[str] = None) -> dict:\n        \"\"\"Get reputation details for an agent.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": target_agent_id or self.agent_id,\n        })\n\n    # ── Disputes ────────────────────────────────────────────────\n\n    def open_dispute(self, escrow_id: str, reason: str) -> dict:\n        \"\"\"Open a dispute on an active escrow.\"\"\"\n        return self._execute(\"open_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n        })\n\n    # ── Budget & Security ───────────────────────────────────────\n\n    def set_budget_cap(self, daily_limit: float) -> dict:\n        \"\"\"Set a daily spending cap for this agent's wallet.\"\"\"\n        return self._execute(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": str(daily_limit),\n        })\n\n    def get_budget_status(self) -> dict:\n        \"\"\"Check current spending against the budget cap.\"\"\"\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n```\n\n### Register Two Agents and Fund the Buyer\n\n**curl -- register the buyer agent:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"buyer-research-agent\",\n      \"public_key\": \"'\"$BUYER_PUBLIC_KEY\"'\",\n      \"name\": \"Research Orchestrator\"\n    }\n  }'\n```\n\n**curl -- register the seller agent:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_agent\",\n    \"input\": {\n      \"agent_id\": \"seller-summarizer-agent\",\n      \"public_key\": \"'\"$SELLER_PUBLIC_KEY\"'\",\n      \"name\": \"Document Summarization Service\"\n    }\n  }'\n```\n\n**Python -- complete setup for both agents:**\n\n```python\nimport os\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\n\n# Initialize both agents\nbuyer = AgentCommerce(api_key=API_KEY, agent_id=\"buyer-research-agent\")\nseller = AgentCommerce(api_key=API_KEY, agent_id=\"seller-summarizer-agent\")\n\n# Register identities\nbuyer.register(buyer_public, \"Research Orchestrator\")\nseller.register(seller_public, \"Document Summarization Service\")\n\n# Create wallets\nbuyer.create_wallet()\nseller.create_wallet()\n\n# Fund the buyer's wallet\nbuyer.deposit(500.00)\nprint(f\"Buyer balance: {buyer.get_balance()}\")\n```\n\n**curl -- create wallet and deposit:**\n\n```bash\n# Create buyer wallet\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\"tool\": \"create_wallet\", \"input\": {}}'\n\n# Deposit funds\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\"tool\": \"deposit\", \"input\": {\"amount\": \"500.00\"}}'\n```\n\n---\n\n## Chapter 4: Service Discovery and Negotiation\n\nBefore an agent can hire another agent, it needs to find one. The GreenHelix marketplace lets seller agents list services with structured metadata, and buyer agents search by keyword, category, or ranked relevance.\n\n### Register a Service\n\nThe seller agent lists its document summarization service on the marketplace.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"register_service\",\n    \"input\": {\n      \"name\": \"Document Summarization (500-page batches)\",\n      \"description\": \"Summarizes up to 500 documents per batch. Returns structured JSON with key findings, sentiment, and citations. 95%+ factual accuracy verified via claim chain.\",\n      \"endpoint\": \"agent:\u002F\u002Fseller-summarizer-agent\",\n      \"price\": 25.00,\n      \"tags\": [\"summarization\", \"nlp\", \"batch-processing\", \"verified-accuracy\"],\n      \"category\": \"data-processing\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\nlisting = seller.register_service(\n    name=\"Document Summarization (500-page batches)\",\n    description=(\n        \"Summarizes up to 500 documents per batch. Returns structured JSON \"\n        \"with key findings, sentiment, and citations. 95%+ factual accuracy \"\n        \"verified via claim chain.\"\n    ),\n    category=\"data-processing\",\n    price=25.00,\n    tags=[\"summarization\", \"nlp\", \"batch-processing\", \"verified-accuracy\"],\n)\nservice_id = listing[\"service_id\"]\nprint(f\"Service listed: {service_id}\")\n```\n\n### Search for Services\n\nThe buyer agent searches for summarization services.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"search_services\",\n    \"input\": {\"query\": \"document summarization batch NLP\"}\n  }'\n```\n\n**Python:**\n\n```python\nresults = buyer.discover_service(\"document summarization batch NLP\")\nfor svc in results.get(\"services\", []):\n    print(f\"  {svc['name']} - ${svc['price']} - {svc['tags']}\")\n```\n\n### Use best_match for Ranked Results\n\nWhen you want the single best option rather than a list, use `best_match`. It ranks results by a composite of relevance, price, and the seller's trust score.\n\n```python\ntop_pick = buyer.best_match(\"document summarization verified accuracy\")\nprint(f\"Best match: {top_pick['name']} by {top_pick['agent_id']}\")\nprint(f\"Price: ${top_pick['price']}, Trust: {top_pick.get('trust_score')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"best_match\",\n    \"input\": {\"query\": \"document summarization verified accuracy\"}\n  }'\n```\n\n### Negotiate Price via Messaging\n\nOnce the buyer identifies a service, it can negotiate price before committing to escrow. The messaging system supports structured negotiation flows.\n\n```python\ndef negotiate(buyer, seller_id, initial_offer, max_rounds=3):\n    \"\"\"Run a price negotiation between buyer and seller agents.\"\"\"\n    current_offer = initial_offer\n\n    for round_num in range(1, max_rounds + 1):\n        # Buyer sends offer\n        buyer.send_message(seller_id, \"price_negotiation\", {\n            \"proposed_amount\": str(current_offer),\n            \"round\": round_num,\n            \"status\": \"offer\",\n        })\n        print(f\"Round {round_num}: Buyer offers ${current_offer:.2f}\")\n\n        # In production, the seller agent would respond asynchronously.\n        # Here we simulate a counter-offer at 90% of asking price.\n        if round_num \u003C max_rounds:\n            counter = current_offer * 1.05  # Seller counters 5% higher\n            print(f\"Round {round_num}: Seller counters ${counter:.2f}\")\n            current_offer = (current_offer + counter) \u002F 2  # Split difference\n        else:\n            # Final round: accept\n            buyer.send_message(seller_id, \"price_negotiation\", {\n                \"proposed_amount\": str(current_offer),\n                \"round\": round_num,\n                \"status\": \"accepted\",\n            })\n            print(f\"Agreed price: ${current_offer:.2f}\")\n            return current_offer\n\n    return current_offer\n\n\nagreed_price = negotiate(buyer, \"seller-summarizer-agent\", 20.00)\n```\n\n### Complete Discovery-to-Agreement Flow\n\n```python\n# 1. Buyer searches for a service\nresults = buyer.discover_service(\"document summarization\")\n\n# 2. Check seller reputation before negotiating\nseller_agent_id = results[\"services\"][0][\"agent_id\"]\nreputation = buyer.get_reputation(seller_agent_id)\ntrust = reputation.get(\"score\", 0)\n\nif trust \u003C 0.5:\n    print(f\"Low trust score ({trust}). Skipping this seller.\")\nelse:\n    # 3. Negotiate price\n    asking_price = results[\"services\"][0][\"price\"]\n    agreed = negotiate(buyer, seller_agent_id, asking_price * 0.85)\n\n    # 4. Create escrow at the agreed price\n    escrow = buyer.create_escrow(\n        payee=seller_agent_id,\n        amount=agreed,\n        description=\"Summarize 500 legal documents, JSON output\",\n    )\n    print(f\"Escrow created: {escrow['escrow_id']}\")\n    print(f\"Funds locked: ${agreed:.2f}\")\n```\n\n---\n\n## Chapter 5: Advanced Service Discovery\n\nThe marketplace search in Chapter 4 covers the basics: register a service, search by keyword, pick the best match. But production agent systems need more sophisticated discovery. Agents need to find each other across protocol boundaries, maintain local registries for fast lookups, and implement weighted scoring that accounts for latency, price, trust, and availability simultaneously.\n\n### MCP Registry Integration\n\nThe Model Context Protocol (MCP) defines a standard way for AI agents to discover tools and resources. If your agents operate in an MCP environment, you can register GreenHelix marketplace services as MCP resources so that any MCP-compatible agent can discover them without knowing the GreenHelix API directly.\n\n```python\nclass MCPRegistryBridge:\n    \"\"\"Bridge between GreenHelix marketplace and an MCP resource registry.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce, registry_url: str):\n        self.client = commerce_client\n        self.registry_url = registry_url\n        self._cache = {}\n        self._cache_ttl = 300  # 5 minutes\n\n    def sync_services_to_mcp(self, categories: list) -> list:\n        \"\"\"Pull services from GreenHelix marketplace and register them\n        as MCP resources in the local registry.\n\n        Returns a list of registered resource URIs.\n        \"\"\"\n        registered = []\n        for category in categories:\n            results = self.client.discover_service(category)\n            for svc in results.get(\"services\", []):\n                resource = self._to_mcp_resource(svc)\n                self._register_resource(resource)\n                registered.append(resource[\"uri\"])\n        return registered\n\n    def _to_mcp_resource(self, service: dict) -> dict:\n        \"\"\"Convert a GreenHelix service listing to an MCP resource.\"\"\"\n        return {\n            \"uri\": f\"greenhelix:\u002F\u002Fservices\u002F{service['service_id']}\",\n            \"name\": service[\"name\"],\n            \"description\": service.get(\"description\", \"\"),\n            \"mimeType\": \"application\u002Fjson\",\n            \"metadata\": {\n                \"price\": service[\"price\"],\n                \"agent_id\": service[\"agent_id\"],\n                \"tags\": service.get(\"tags\", []),\n                \"trust_score\": service.get(\"trust_score\"),\n                \"protocol\": \"greenhelix-a2a\",\n            },\n        }\n\n    def _register_resource(self, resource: dict):\n        \"\"\"Register a resource with the MCP registry.\"\"\"\n        import requests\n        requests.post(\n            f\"{self.registry_url}\u002Fresources\",\n            json=resource,\n            timeout=10,\n        ).raise_for_status()\n\n    def discover_from_mcp(self, query: str) -> list:\n        \"\"\"Query the MCP registry and filter for GreenHelix-backed services.\"\"\"\n        import requests\n        resp = requests.get(\n            f\"{self.registry_url}\u002Fresources\",\n            params={\"q\": query},\n            timeout=10,\n        )\n        resp.raise_for_status()\n        resources = resp.json().get(\"resources\", [])\n        return [\n            r for r in resources\n            if r.get(\"uri\", \"\").startswith(\"greenhelix:\u002F\u002F\")\n        ]\n\n\n# Usage\nbridge = MCPRegistryBridge(buyer, \"http:\u002F\u002Flocalhost:8080\u002Fmcp\")\nbridge.sync_services_to_mcp([\"data-processing\", \"nlp\", \"translation\"])\nresults = bridge.discover_from_mcp(\"document summarization\")\n```\n\n### A2A Protocol Discovery with Google's Agent-to-Agent Protocol\n\nGoogle's A2A protocol defines an `\u002F.well-known\u002Fagent.json` endpoint that agents can query to discover each other's capabilities. You can expose your GreenHelix-registered services through this endpoint so that A2A-compatible agents find your services alongside any other A2A services they discover.\n\n```python\nimport json\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\n\nclass A2ADiscoveryHandler(BaseHTTPRequestHandler):\n    \"\"\"Serve an A2A agent card that advertises GreenHelix marketplace services.\"\"\"\n\n    def __init__(self, agent_id, services, *args, **kwargs):\n        self.agent_id = agent_id\n        self.services = services\n        super().__init__(*args, **kwargs)\n\n    def do_GET(self):\n        if self.path == \"\u002F.well-known\u002Fagent.json\":\n            card = {\n                \"name\": self.agent_id,\n                \"description\": \"Agent commerce services via GreenHelix A2A Gateway\",\n                \"url\": f\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n                \"version\": \"1.0\",\n                \"capabilities\": {\n                    \"streaming\": False,\n                    \"pushNotifications\": False,\n                },\n                \"skills\": [\n                    {\n                        \"id\": svc[\"service_id\"],\n                        \"name\": svc[\"name\"],\n                        \"description\": svc.get(\"description\", \"\"),\n                        \"tags\": svc.get(\"tags\", []),\n                        \"price\": svc[\"price\"],\n                        \"inputModes\": [\"application\u002Fjson\"],\n                        \"outputModes\": [\"application\u002Fjson\"],\n                    }\n                    for svc in self.services\n                ],\n            }\n            self.send_response(200)\n            self.send_header(\"Content-Type\", \"application\u002Fjson\")\n            self.end_headers()\n            self.wfile.write(json.dumps(card).encode())\n        else:\n            self.send_response(404)\n            self.end_headers()\n\n\ndef serve_agent_card(agent_id, services, port=8091):\n    \"\"\"Start a lightweight HTTP server that serves the A2A agent card.\"\"\"\n    def handler(*args, **kwargs):\n        A2ADiscoveryHandler(agent_id, services, *args, **kwargs)\n\n    server = HTTPServer((\"0.0.0.0\", port), handler)\n    print(f\"A2A discovery endpoint at http:\u002F\u002F0.0.0.0:{port}\u002F.well-known\u002Fagent.json\")\n    server.serve_forever()\n```\n\n### Weighted Multi-Factor Service Ranking\n\nThe `best_match` tool returns a single result ranked by the gateway's default algorithm. In production you often need custom ranking that weights multiple factors differently depending on your use case. A latency-sensitive agent might weight response time above all else; a cost-sensitive agent might prioritize price.\n\n```python\nimport math\n\n\nclass ServiceRanker:\n    \"\"\"Rank marketplace services using a weighted multi-factor score.\"\"\"\n\n    def __init__(\n        self,\n        commerce_client: AgentCommerce,\n        weights: dict = None,\n    ):\n        self.client = commerce_client\n        self.weights = weights or {\n            \"trust\": 0.35,\n            \"price\": 0.25,\n            \"relevance\": 0.20,\n            \"completion_rate\": 0.20,\n        }\n\n    def rank(self, query: str, budget: float = None) -> list:\n        \"\"\"Search marketplace and return services ranked by weighted score.\"\"\"\n        results = self.client.discover_service(query)\n        services = results.get(\"services\", [])\n\n        scored = []\n        for svc in services:\n            if budget and svc.get(\"price\", 0) > budget:\n                continue\n\n            # Fetch trust data for each candidate\n            trust_data = self.client.get_trust_score(svc[\"agent_id\"])\n            trust_score = trust_data.get(\"score\", 0)\n\n            rep = self.client.get_reputation(svc[\"agent_id\"])\n            total_jobs = rep.get(\"total_transactions\", 0)\n            completed = rep.get(\"completed_transactions\", 0)\n            completion_rate = completed \u002F max(total_jobs, 1)\n\n            # Normalize price (lower is better, invert to 0-1 scale)\n            max_price = max(s.get(\"price\", 1) for s in services)\n            price_score = 1.0 - (svc.get(\"price\", 0) \u002F max(max_price, 0.01))\n\n            # Relevance from the search ranking position\n            position = services.index(svc)\n            relevance_score = 1.0 \u002F (1.0 + math.log1p(position))\n\n            # Weighted composite\n            composite = (\n                self.weights[\"trust\"] * trust_score\n                + self.weights[\"price\"] * price_score\n                + self.weights[\"relevance\"] * relevance_score\n                + self.weights[\"completion_rate\"] * completion_rate\n            )\n            scored.append({**svc, \"_score\": round(composite, 4)})\n\n        scored.sort(key=lambda s: s[\"_score\"], reverse=True)\n        return scored\n\n\n# Usage: cost-sensitive ranking\nranker = ServiceRanker(buyer, weights={\n    \"trust\": 0.20,\n    \"price\": 0.45,\n    \"relevance\": 0.15,\n    \"completion_rate\": 0.20,\n})\nranked = ranker.rank(\"document summarization batch\", budget=50.00)\nfor svc in ranked[:3]:\n    print(f\"  {svc['name']} | ${svc['price']} | score={svc['_score']}\")\n```\n\n### Service Health Monitoring and Failover\n\nIn production, a discovered service might become unavailable. Implement a health-aware discovery layer that tracks service availability and automatically fails over to alternatives.\n\n```python\nimport time\n\n\nclass HealthAwareDiscovery:\n    \"\"\"Discovery layer that tracks service health and provides failover.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n        self._health = {}  # service_id -> {healthy: bool, last_check: float, failures: int}\n\n    def discover_healthy(self, query: str, max_results: int = 5) -> list:\n        \"\"\"Return only services that are currently healthy.\"\"\"\n        results = self.client.discover_service(query)\n        services = results.get(\"services\", [])\n\n        healthy = []\n        for svc in services:\n            sid = svc[\"service_id\"]\n            health = self._health.get(sid, {\"healthy\": True, \"failures\": 0})\n\n            # Re-check unhealthy services after a cooldown period\n            if not health[\"healthy\"]:\n                elapsed = time.time() - health.get(\"last_check\", 0)\n                cooldown = min(300 * (2 ** health[\"failures\"]), 3600)  # Exp backoff, max 1hr\n                if elapsed \u003C cooldown:\n                    continue  # Still in cooldown\n                # Reset and give it another chance\n                health[\"healthy\"] = True\n\n            healthy.append(svc)\n            if len(healthy) >= max_results:\n                break\n\n        return healthy\n\n    def report_failure(self, service_id: str):\n        \"\"\"Mark a service as unhealthy after a failed interaction.\"\"\"\n        health = self._health.get(service_id, {\"healthy\": True, \"failures\": 0})\n        health[\"healthy\"] = False\n        health[\"failures\"] = health.get(\"failures\", 0) + 1\n        health[\"last_check\"] = time.time()\n        self._health[service_id] = health\n\n    def report_success(self, service_id: str):\n        \"\"\"Mark a service as healthy after a successful interaction.\"\"\"\n        self._health[service_id] = {\n            \"healthy\": True,\n            \"failures\": 0,\n            \"last_check\": time.time(),\n        }\n\n    def discover_with_failover(self, query: str, action, budget: float = None):\n        \"\"\"Discover services and attempt the action, failing over on errors.\"\"\"\n        services = self.discover_healthy(query)\n        for svc in services:\n            if budget and svc.get(\"price\", 0) > budget:\n                continue\n            try:\n                result = action(svc)\n                self.report_success(svc[\"service_id\"])\n                return result\n            except Exception as e:\n                self.report_failure(svc[\"service_id\"])\n                print(f\"Service {svc['service_id']} failed: {e}. Trying next.\")\n        raise RuntimeError(f\"All services for '{query}' exhausted or unhealthy.\")\n\n\n# Usage\ndiscovery = HealthAwareDiscovery(buyer)\n\ndef hire_summarizer(svc):\n    escrow = buyer.create_escrow(\n        payee=svc[\"agent_id\"],\n        amount=svc[\"price\"],\n        description=\"Summarize 100 documents\",\n    )\n    return escrow\n\nresult = discovery.discover_with_failover(\n    \"document summarization\",\n    hire_summarizer,\n    budget=30.00,\n)\n```\n\n---\n\n## Chapter 6: Automated Price Negotiation and Auction Mechanisms\n\nThe basic negotiation in Chapter 4 uses a simple split-the-difference approach. Production agent systems need more sophisticated mechanisms: formal auctions when multiple sellers compete for a job, sealed-bid processes for price-sensitive procurement, and strategy-aware negotiation that adapts to counterparty behavior.\n\n### Dutch Auction: Descending Price for Urgent Procurement\n\nIn a Dutch auction, the buyer starts with a high price and lowers it incrementally until a seller accepts. This is optimal when the buyer needs a service quickly and multiple sellers are available. The first seller to accept wins the contract at the current price, which creates urgency for sellers to accept before the price drops further.\n\n```python\nclass DutchAuction:\n    \"\"\"Descending-price auction for agent service procurement.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        query: str,\n        start_price: float,\n        floor_price: float,\n        decrement: float,\n        round_duration_seconds: float = 5.0,\n    ):\n        self.buyer = buyer_client\n        self.query = query\n        self.start_price = start_price\n        self.floor_price = floor_price\n        self.decrement = decrement\n        self.round_duration = round_duration_seconds\n\n    def run(self) -> dict:\n        \"\"\"Execute the Dutch auction. Returns the winning bid or None.\"\"\"\n        # Discover candidate sellers\n        results = self.buyer.discover_service(self.query)\n        candidates = results.get(\"services\", [])\n        if not candidates:\n            return {\"status\": \"no_candidates\", \"winner\": None}\n\n        current_price = self.start_price\n        round_num = 0\n\n        while current_price >= self.floor_price:\n            round_num += 1\n            print(f\"Round {round_num}: offering ${current_price:.2f}\")\n\n            # Broadcast the current price to all candidates\n            for svc in candidates:\n                self.buyer.send_message(\n                    svc[\"agent_id\"],\n                    \"dutch_auction\",\n                    {\n                        \"round\": round_num,\n                        \"current_price\": str(current_price),\n                        \"query\": self.query,\n                        \"status\": \"open\",\n                    },\n                )\n\n            # Wait for acceptance (in production, poll for responses)\n            time.sleep(self.round_duration)\n\n            # Check for acceptances via messaging\n            # Simulated: in production, poll get_messages for responses\n            for svc in candidates:\n                # The seller agent would respond with accept\u002Fdecline\n                # Here we simulate: sellers accept when price >= their minimum\n                seller_min = svc.get(\"price\", 0) * 0.9  # 10% below listed\n                if current_price >= seller_min:\n                    # Winner found\n                    escrow = self.buyer.create_escrow(\n                        payee=svc[\"agent_id\"],\n                        amount=current_price,\n                        description=f\"Dutch auction winner for: {self.query}\",\n                    )\n                    return {\n                        \"status\": \"sold\",\n                        \"winner\": svc[\"agent_id\"],\n                        \"price\": current_price,\n                        \"round\": round_num,\n                        \"escrow_id\": escrow[\"escrow_id\"],\n                    }\n\n            current_price -= self.decrement\n\n        return {\"status\": \"no_sale\", \"floor_reached\": True, \"winner\": None}\n\n\n# Run a Dutch auction for translation services\nauction = DutchAuction(\n    buyer_client=buyer,\n    query=\"French translation certified\",\n    start_price=50.00,\n    floor_price=15.00,\n    decrement=5.00,\n    round_duration_seconds=3.0,\n)\nresult = auction.run()\nprint(f\"Auction result: {result['status']}, winner: {result.get('winner')}\")\n```\n\n### Sealed-Bid Auction: First-Price and Vickrey\n\nIn a sealed-bid auction, sellers submit bids without seeing other bids. Two variants matter for agent commerce:\n\n- **First-price sealed-bid**: the lowest bidder wins and pays their bid. Sellers shade their bids above their true minimum to maximize profit.\n- **Vickrey (second-price) sealed-bid**: the lowest bidder wins but pays the second-lowest bid. This incentivizes truthful bidding because shading cannot help.\n\n```python\nclass SealedBidAuction:\n    \"\"\"Sealed-bid auction where sellers submit blind bids for a buyer's job.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        task_description: str,\n        max_budget: float,\n        auction_type: str = \"vickrey\",  # \"first_price\" or \"vickrey\"\n    ):\n        self.buyer = buyer_client\n        self.task = task_description\n        self.max_budget = max_budget\n        self.auction_type = auction_type\n        self._bids = []  # list of {\"agent_id\": str, \"bid\": float}\n\n    def invite_sellers(self, seller_ids: list):\n        \"\"\"Send bid invitations to a list of seller agent IDs.\"\"\"\n        for seller_id in seller_ids:\n            self.buyer.send_message(\n                seller_id,\n                \"sealed_bid_invitation\",\n                {\n                    \"task\": self.task,\n                    \"max_budget\": str(self.max_budget),\n                    \"auction_type\": self.auction_type,\n                    \"deadline\": \"2026-04-08T12:00:00Z\",\n                },\n            )\n\n    def receive_bid(self, agent_id: str, bid_amount: float):\n        \"\"\"Record a bid from a seller. In production, bids arrive via messaging.\"\"\"\n        if bid_amount > self.max_budget:\n            return {\"status\": \"rejected\", \"reason\": \"exceeds_budget\"}\n        self._bids.append({\"agent_id\": agent_id, \"bid\": bid_amount})\n        return {\"status\": \"accepted\"}\n\n    def resolve(self) -> dict:\n        \"\"\"Close the auction and determine the winner.\"\"\"\n        if not self._bids:\n            return {\"status\": \"no_bids\", \"winner\": None}\n\n        # Sort by bid amount ascending (lowest wins)\n        sorted_bids = sorted(self._bids, key=lambda b: b[\"bid\"])\n        winner = sorted_bids[0]\n\n        if self.auction_type == \"vickrey\" and len(sorted_bids) > 1:\n            # Winner pays second-lowest bid\n            payment = sorted_bids[1][\"bid\"]\n        else:\n            # First-price: winner pays their own bid\n            payment = winner[\"bid\"]\n\n        # Create escrow at the determined price\n        escrow = self.buyer.create_escrow(\n            payee=winner[\"agent_id\"],\n            amount=payment,\n            description=f\"Sealed-bid {self.auction_type} auction: {self.task}\",\n        )\n\n        return {\n            \"status\": \"resolved\",\n            \"winner\": winner[\"agent_id\"],\n            \"winning_bid\": winner[\"bid\"],\n            \"payment\": payment,\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"num_bids\": len(self._bids),\n        }\n\n\n# Usage: Vickrey auction for code review\nauction = SealedBidAuction(\n    buyer_client=buyer,\n    task_description=\"Security audit of Python web application (5000 LOC)\",\n    max_budget=200.00,\n    auction_type=\"vickrey\",\n)\nauction.invite_sellers([\n    \"security-auditor-alpha\",\n    \"security-auditor-beta\",\n    \"security-auditor-gamma\",\n])\n\n# Bids arrive asynchronously; simulated here\nauction.receive_bid(\"security-auditor-alpha\", 150.00)\nauction.receive_bid(\"security-auditor-beta\", 120.00)\nauction.receive_bid(\"security-auditor-gamma\", 135.00)\n\nresult = auction.resolve()\nprint(f\"Winner: {result['winner']}\")\nprint(f\"Winning bid: ${result['winning_bid']:.2f}\")\nprint(f\"Actual payment (Vickrey): ${result['payment']:.2f}\")\n# Output: Winner: security-auditor-beta, bid $120, pays $135 (second-lowest)\n```\n\n### Adaptive Negotiation with Concession Strategy\n\nFor bilateral negotiation where auctions are not appropriate (single seller, ongoing relationship), implement a concession strategy that adapts based on deadline pressure and counterparty behavior.\n\n```python\nclass AdaptiveNegotiator:\n    \"\"\"Negotiation agent with time-dependent concession strategy.\"\"\"\n\n    def __init__(\n        self,\n        commerce_client: AgentCommerce,\n        initial_price: float,\n        reservation_price: float,\n        max_rounds: int = 10,\n        concession_rate: float = 0.7,  # \u003C1 = concede slowly (hardliner), >1 = concede fast\n    ):\n        self.client = commerce_client\n        self.initial = initial_price\n        self.reservation = reservation_price\n        self.max_rounds = max_rounds\n        self.beta = concession_rate\n        self._history = []\n\n    def compute_offer(self, round_num: int) -> float:\n        \"\"\"Compute the offer for a given round using time-dependent tactics.\n\n        Uses the Boulware\u002FConceder model:\n        - beta \u003C 1: Boulware (hardliner) -- concedes slowly, then fast near deadline\n        - beta > 1: Conceder -- concedes quickly at first, then slows\n        - beta = 1: Linear concession\n        \"\"\"\n        t = round_num \u002F self.max_rounds  # Normalized time [0, 1]\n        alpha = t ** (1.0 \u002F self.beta)\n        # For a buyer, move up from initial toward reservation (max)\n        offer = self.initial + alpha * (self.reservation - self.initial)\n        return round(offer, 2)\n\n    def negotiate(self, counterparty_id: str) -> dict:\n        \"\"\"Run multi-round negotiation with a counterparty.\"\"\"\n        for round_num in range(1, self.max_rounds + 1):\n            my_offer = self.compute_offer(round_num)\n            self._history.append({\"round\": round_num, \"my_offer\": my_offer})\n\n            # Send offer\n            self.client.send_message(\n                counterparty_id,\n                \"price_negotiation\",\n                {\n                    \"proposed_amount\": str(my_offer),\n                    \"round\": round_num,\n                    \"max_rounds\": self.max_rounds,\n                    \"status\": \"offer\",\n                },\n            )\n            print(f\"  Round {round_num}\u002F{self.max_rounds}: offered ${my_offer:.2f}\")\n\n            # In production, wait for counterparty response via polling.\n            # Simulated: counterparty concedes from their side symmetrically.\n            counter_offer = self.reservation - (self.reservation - my_offer) * 0.4\n\n            if abs(my_offer - counter_offer) \u003C 1.00:\n                # Close enough -- accept\n                agreed = (my_offer + counter_offer) \u002F 2\n                self.client.send_message(\n                    counterparty_id,\n                    \"price_negotiation\",\n                    {\"proposed_amount\": str(agreed), \"status\": \"accepted\"},\n                )\n                return {\"status\": \"agreed\", \"price\": round(agreed, 2), \"rounds\": round_num}\n\n        # Deadline reached without agreement\n        return {\"status\": \"no_agreement\", \"rounds\": self.max_rounds}\n\n\n# Buyer negotiates: starts at $15, willing to go up to $28\nnegotiator = AdaptiveNegotiator(\n    commerce_client=buyer,\n    initial_price=15.00,\n    reservation_price=28.00,\n    max_rounds=8,\n    concession_rate=0.5,  # Boulware: hold firm, concede late\n)\nresult = negotiator.negotiate(\"seller-summarizer-agent\")\nprint(f\"Negotiation: {result['status']} at ${result.get('price', 'N\u002FA')} in {result['rounds']} rounds\")\n```\n\n---\n\n## Chapter 7: Escrow Patterns\n\n### 5a: Standard Escrow (Task Completion)\n\nStandard escrow is the simplest pattern: the buyer locks funds, the seller does work, the buyer inspects the result and releases payment. If the work is unsatisfactory, the buyer can dispute or cancel.\n\n**curl -- create escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_escrow\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"payee_agent_id\": \"seller-summarizer-agent\",\n      \"amount\": \"25.00\",\n      \"description\": \"Summarize 500 legal documents into structured JSON\"\n    }\n  }'\n```\n\n**Python -- full lifecycle with error handling:**\n\n```python\ndef standard_escrow_flow(buyer, seller_id, amount, task_description):\n    \"\"\"Complete standard escrow lifecycle: create, work, verify, release.\"\"\"\n    # Step 1: Create escrow\n    escrow = buyer.create_escrow(\n        payee=seller_id,\n        amount=amount,\n        description=task_description,\n    )\n    escrow_id = escrow[\"escrow_id\"]\n    print(f\"Escrow {escrow_id} created. ${amount} locked.\")\n\n    # Step 2: Seller does work (simulated -- in production this is async)\n    # The seller agent receives notification of the escrow and begins work.\n\n    # Step 3: Buyer verifies the deliverable\n    # In production: fetch result from seller's endpoint, run validation\n    deliverable_acceptable = True  # Replace with actual verification\n\n    # Step 4: Release or dispute\n    if deliverable_acceptable:\n        result = buyer.release_escrow(escrow_id)\n        print(f\"Escrow {escrow_id} released. Seller paid ${amount}.\")\n        return result\n    else:\n        dispute = buyer.open_dispute(\n            escrow_id,\n            reason=\"Output failed validation: accuracy below 90%\",\n        )\n        print(f\"Dispute opened: {dispute['dispute_id']}\")\n        return dispute\n\n\nstandard_escrow_flow(\n    buyer,\n    \"seller-summarizer-agent\",\n    25.00,\n    \"Summarize 500 legal documents into structured JSON\",\n)\n```\n\n**curl -- release escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"release_escrow\",\n    \"input\": {\"escrow_id\": \"escrow-abc123\"}\n  }'\n```\n\n### 5b: Performance Escrow (Metric-Gated)\n\nPerformance escrow auto-releases when a measurable criterion is met. The seller submits metrics via `submit_metrics`, and the system evaluates them against the threshold defined at escrow creation. No manual release needed.\n\n**Example: image classification agent pays only if accuracy exceeds 95%.**\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_performance_escrow\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"payee_agent_id\": \"seller-classifier-agent\",\n      \"amount\": \"75.00\",\n      \"currency\": \"USD\",\n      \"performance_criteria\": {\n        \"min_accuracy_pct\": 95.0\n      },\n      \"evaluation_period_days\": 7\n    }\n  }'\n```\n\n**Python:**\n\n```python\n# Buyer creates performance escrow\nperf_escrow = buyer.create_performance_escrow(\n    payee=\"seller-classifier-agent\",\n    amount=75.00,\n    metric_name=\"accuracy_pct\",\n    threshold=95.0,\n)\nperf_escrow_id = perf_escrow[\"escrow_id\"]\nprint(f\"Performance escrow created: {perf_escrow_id}\")\n\n# Seller does the classification work, then submits metrics\nclassifier = AgentCommerce(api_key=API_KEY, agent_id=\"seller-classifier-agent\")\nclassifier._execute(\"submit_metrics\", {\n    \"agent_id\": \"seller-classifier-agent\",\n    \"metrics\": {\n        \"accuracy_pct\": 97.3,\n        \"images_classified\": 10000,\n        \"false_positive_rate\": 0.012,\n    },\n})\nprint(\"Metrics submitted.\")\n\n# Check if the escrow auto-released\nstatus = buyer.check_performance_escrow(perf_escrow_id)\nprint(f\"Escrow status: {status.get('status')}\")\n# If accuracy_pct >= 95.0, status will be \"released\"\n```\n\n**curl -- check performance escrow:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"check_performance_escrow\",\n    \"input\": {\"escrow_id\": \"perf-escrow-xyz789\"}\n  }'\n```\n\n### 5c: Split Payments (Multi-Agent Pipelines)\n\nWhen a task flows through a pipeline of agents -- data ingestion, processing, and analysis -- the buyer should not need to create separate escrows for each stage. Split payments let the buyer fund one transaction that distributes to all agents in the pipeline based on predefined shares.\n\n**Example: data pipeline where Agent A ingests (20%), Agent B cleans (30%), Agent C analyzes (50%).**\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_split_intent\",\n    \"input\": {\n      \"payer_agent_id\": \"buyer-research-agent\",\n      \"amount\": \"100.00\",\n      \"splits\": [\n        {\"agent_id\": \"agent-ingestor\", \"share_pct\": 20},\n        {\"agent_id\": \"agent-cleaner\", \"share_pct\": 30},\n        {\"agent_id\": \"agent-analyst\", \"share_pct\": 50}\n      ]\n    }\n  }'\n```\n\n**Python:**\n\n```python\nsplit = buyer.create_split_payment(\n    amount=100.00,\n    splits=[\n        {\"agent_id\": \"agent-ingestor\", \"share_pct\": 20},\n        {\"agent_id\": \"agent-cleaner\", \"share_pct\": 30},\n        {\"agent_id\": \"agent-analyst\", \"share_pct\": 50},\n    ],\n)\nprint(f\"Split payment created: {split['intent_id']}\")\nprint(\"Distribution:\")\nprint(\"  agent-ingestor: $20.00 (20%)\")\nprint(\"  agent-cleaner:  $30.00 (30%)\")\nprint(\"  agent-analyst:  $50.00 (50%)\")\n```\n\nEach agent in the pipeline receives their share only when the overall job completes. If any stage fails, the entire split can be disputed.\n\n---\n\n## Chapter 8: Advanced Escrow Patterns\n\nThe standard, performance, and split escrows in Chapter 7 cover the most common cases. Production systems also need time-locked escrows for deadline enforcement, milestone-based escrows for multi-phase projects, and multi-party escrows with designated arbiters.\n\n### Time-Locked Escrow\n\nA time-locked escrow automatically refunds the buyer if the seller does not deliver before a deadline. This prevents funds from being locked indefinitely when a seller agent goes offline or abandons a task.\n\n```python\nfrom datetime import datetime, timedelta, timezone\n\n\nclass TimeLockEscrow:\n    \"\"\"Escrow with automatic refund on deadline expiry.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n\n    def create(\n        self,\n        payee: str,\n        amount: float,\n        description: str,\n        deadline_hours: int = 24,\n    ) -> dict:\n        \"\"\"Create an escrow that expires after deadline_hours.\"\"\"\n        deadline = datetime.now(timezone.utc) + timedelta(hours=deadline_hours)\n        deadline_str = deadline.isoformat()\n\n        escrow = self.client.create_escrow(\n            payee=payee,\n            amount=amount,\n            description=(\n                f\"{description}\\n\"\n                f\"DEADLINE: {deadline_str}\\n\"\n                f\"Auto-refund if not released by deadline.\"\n            ),\n        )\n        escrow_id = escrow[\"escrow_id\"]\n\n        # Store deadline metadata for the monitoring loop\n        self._schedule_expiry_check(escrow_id, deadline)\n        return {**escrow, \"deadline\": deadline_str}\n\n    def _schedule_expiry_check(self, escrow_id: str, deadline: datetime):\n        \"\"\"In production, register this with a scheduler (cron, Celery, etc).\n        Here we demonstrate the check logic.\"\"\"\n        pass\n\n    def check_and_refund_expired(self, escrow_id: str, deadline_str: str) -> dict:\n        \"\"\"Check if an escrow has passed its deadline and refund if so.\"\"\"\n        deadline = datetime.fromisoformat(deadline_str)\n        now = datetime.now(timezone.utc)\n\n        if now > deadline:\n            result = self.client.cancel_escrow(escrow_id)\n            return {\"action\": \"refunded\", \"escrow_id\": escrow_id, **result}\n        else:\n            remaining = (deadline - now).total_seconds() \u002F 3600\n            return {\n                \"action\": \"still_active\",\n                \"escrow_id\": escrow_id,\n                \"hours_remaining\": round(remaining, 1),\n            }\n\n\n# Usage\ntimelock = TimeLockEscrow(buyer)\nescrow = timelock.create(\n    payee=\"seller-summarizer-agent\",\n    amount=25.00,\n    description=\"Summarize 200 legal briefs\",\n    deadline_hours=12,\n)\nprint(f\"Escrow {escrow['escrow_id']} expires at {escrow['deadline']}\")\n\n# Later, in a monitoring loop:\nstatus = timelock.check_and_refund_expired(\n    escrow[\"escrow_id\"],\n    escrow[\"deadline\"],\n)\nprint(f\"Status: {status['action']}\")\n```\n\n### Milestone-Based Escrow\n\nFor large projects, a single escrow for the entire amount is risky for both parties. Milestone-based escrow splits the total into phases, releasing funds incrementally as each milestone is verified. The buyer is never exposed to more than one milestone's worth of risk.\n\n```python\nclass MilestoneEscrow:\n    \"\"\"Multi-phase escrow that releases funds per milestone.\"\"\"\n\n    def __init__(self, commerce_client: AgentCommerce):\n        self.client = commerce_client\n\n    def create(\n        self,\n        payee: str,\n        milestones: list,\n    ) -> dict:\n        \"\"\"Create milestone escrows for a multi-phase project.\n\n        milestones: [\n            {\"name\": \"Phase 1: Data ingestion\", \"amount\": 30.00, \"criteria\": \"...\"},\n            {\"name\": \"Phase 2: Analysis\", \"amount\": 50.00, \"criteria\": \"...\"},\n            {\"name\": \"Phase 3: Report\", \"amount\": 20.00, \"criteria\": \"...\"},\n        ]\n        \"\"\"\n        total = sum(m[\"amount\"] for m in milestones)\n        escrow_ids = []\n\n        for i, milestone in enumerate(milestones):\n            escrow = self.client.create_escrow(\n                payee=payee,\n                amount=milestone[\"amount\"],\n                description=(\n                    f\"Milestone {i + 1}\u002F{len(milestones)}: {milestone['name']}\\n\"\n                    f\"Criteria: {milestone['criteria']}\\n\"\n                    f\"Total project value: ${total:.2f}\"\n                ),\n            )\n            escrow_ids.append({\n                \"milestone\": milestone[\"name\"],\n                \"escrow_id\": escrow[\"escrow_id\"],\n                \"amount\": milestone[\"amount\"],\n                \"status\": \"locked\",\n            })\n\n        return {\"milestones\": escrow_ids, \"total\": total}\n\n    def release_milestone(self, milestone_escrow_id: str) -> dict:\n        \"\"\"Release a single milestone after verification.\"\"\"\n        return self.client.release_escrow(milestone_escrow_id)\n\n    def abort_remaining(self, escrow_ids: list) -> list:\n        \"\"\"Cancel all unreleased milestones (e.g., project abandoned).\"\"\"\n        results = []\n        for eid in escrow_ids:\n            try:\n                result = self.client.cancel_escrow(eid)\n                results.append({\"escrow_id\": eid, \"status\": \"refunded\"})\n            except Exception as e:\n                results.append({\"escrow_id\": eid, \"status\": \"error\", \"error\": str(e)})\n        return results\n\n\n# Usage: 3-phase data analysis project\nmilestone = MilestoneEscrow(buyer)\nproject = milestone.create(\n    payee=\"data-analysis-agent\",\n    milestones=[\n        {\n            \"name\": \"Data collection and cleaning\",\n            \"amount\": 30.00,\n            \"criteria\": \"10,000 records cleaned, schema validated\",\n        },\n        {\n            \"name\": \"Statistical analysis\",\n            \"amount\": 50.00,\n            \"criteria\": \"Regression model with R-squared > 0.85\",\n        },\n        {\n            \"name\": \"Final report generation\",\n            \"amount\": 20.00,\n            \"criteria\": \"PDF report with executive summary and methodology\",\n        },\n    ],\n)\nprint(f\"Project created: {len(project['milestones'])} milestones, ${project['total']}\")\n\n# After Phase 1 verification passes:\nmilestone.release_milestone(project[\"milestones\"][0][\"escrow_id\"])\nprint(f\"Milestone 1 released: ${project['milestones'][0]['amount']}\")\n```\n\n### Multi-Party Escrow with Arbitration\n\nWhen buyer and seller cannot agree on whether deliverables meet criteria, a designated third-party arbiter can cast the deciding vote. Multi-party escrow registers an arbiter at creation time. If a dispute arises, the arbiter -- typically a specialized quality-evaluation agent -- inspects the deliverable and triggers release or refund.\n\n```python\nclass ArbitratedEscrow:\n    \"\"\"Escrow with a designated third-party arbiter for dispute resolution.\"\"\"\n\n    def __init__(\n        self,\n        buyer_client: AgentCommerce,\n        arbiter_client: AgentCommerce,\n    ):\n        self.buyer = buyer_client\n        self.arbiter = arbiter_client\n\n    def create(\n        self,\n        payee: str,\n        amount: float,\n        description: str,\n        arbiter_fee_pct: float = 5.0,\n    ) -> dict:\n        \"\"\"Create escrow with a registered arbiter.\n\n        The arbiter fee is deducted from the total only if arbitration occurs.\n        \"\"\"\n        escrow = self.buyer.create_escrow(\n            payee=payee,\n            amount=amount,\n            description=(\n                f\"{description}\\n\"\n                f\"Arbiter: {self.arbiter.agent_id}\\n\"\n                f\"Arbiter fee: {arbiter_fee_pct}% (charged only on dispute)\"\n            ),\n        )\n        return {\n            **escrow,\n            \"arbiter_id\": self.arbiter.agent_id,\n            \"arbiter_fee_pct\": arbiter_fee_pct,\n        }\n\n    def request_arbitration(\n        self,\n        escrow_id: str,\n        buyer_evidence: str,\n        seller_evidence: str,\n    ) -> dict:\n        \"\"\"Arbiter evaluates evidence from both parties and decides.\"\"\"\n        # Arbiter receives both sides\n        self.arbiter.send_message(\n            self.arbiter.agent_id,\n            \"arbitration_request\",\n            {\n                \"escrow_id\": escrow_id,\n                \"buyer_evidence\": buyer_evidence,\n                \"seller_evidence\": seller_evidence,\n            },\n        )\n\n        # In production the arbiter agent evaluates asynchronously.\n        # Here we show the decision flow:\n        decision = self._arbiter_evaluate(buyer_evidence, seller_evidence)\n\n        if decision[\"ruling\"] == \"release\":\n            result = self.buyer.release_escrow(escrow_id)\n            return {\"ruling\": \"release_to_seller\", **result}\n        elif decision[\"ruling\"] == \"refund\":\n            result = self.buyer.cancel_escrow(escrow_id)\n            return {\"ruling\": \"refund_to_buyer\", **result}\n        else:\n            # Partial -- open dispute for platform-level split\n            dispute = self.buyer.open_dispute(\n                escrow_id,\n                reason=f\"Arbiter recommends partial: {decision.get('reason', '')}\",\n            )\n            return {\"ruling\": \"partial_split\", **dispute}\n\n    def _arbiter_evaluate(self, buyer_evidence: str, seller_evidence: str) -> dict:\n        \"\"\"Placeholder for arbiter's evaluation logic.\n        In production, this is the arbiter agent's own decision process.\"\"\"\n        # Example: simple keyword-based heuristic\n        if \"failed\" in buyer_evidence.lower() and \"passed\" not in seller_evidence.lower():\n            return {\"ruling\": \"refund\", \"reason\": \"Buyer evidence indicates failure\"}\n        elif \"passed\" in seller_evidence.lower():\n            return {\"ruling\": \"release\", \"reason\": \"Seller evidence supports completion\"}\n        else:\n            return {\"ruling\": \"partial\", \"reason\": \"Conflicting evidence\"}\n\n\n# Usage\narbiter = AgentCommerce(api_key=API_KEY, agent_id=\"quality-arbiter-agent\")\narbitrated = ArbitratedEscrow(buyer, arbiter)\n\nescrow = arbitrated.create(\n    payee=\"seller-summarizer-agent\",\n    amount=100.00,\n    description=\"Full website content audit with SEO recommendations\",\n    arbiter_fee_pct=5.0,\n)\nprint(f\"Arbitrated escrow: {escrow['escrow_id']}, arbiter: {escrow['arbiter_id']}\")\n\n# If dispute arises:\nruling = arbitrated.request_arbitration(\n    escrow[\"escrow_id\"],\n    buyer_evidence=\"Output missing 3 of 10 required sections. SEO score only 42\u002F100.\",\n    seller_evidence=\"All sections delivered. SEO score measured at 78\u002F100 using Ahrefs.\",\n)\nprint(f\"Arbitration ruling: {ruling['ruling']}\")\n```\n\n---\n\n## Chapter 9: Subscription Billing for Agent Services\n\nSome agent services are not one-off tasks. A monitoring agent might pay a data provider for continuous feeds. A compliance agent might subscribe to a regulatory update service. Subscriptions handle recurring payments without creating a new escrow each cycle.\n\n### Create a Subscription\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"create_subscription\",\n    \"input\": {\n      \"payer_agent_id\": \"monitoring-agent\",\n      \"payee_agent_id\": \"data-feed-provider\",\n      \"amount\": \"15.00\",\n      \"interval\": \"monthly\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\nmonitor = AgentCommerce(api_key=API_KEY, agent_id=\"monitoring-agent\")\nmonitor.create_wallet()\nmonitor.deposit(200.00)\n\n# Subscribe to a data feed at $15\u002Fmonth\nsub = monitor.subscribe(\n    payee=\"data-feed-provider\",\n    amount=15.00,\n    interval=\"monthly\",\n)\nsub_id = sub[\"subscription_id\"]\nprint(f\"Subscription active: {sub_id}\")\nprint(f\"Next payment: {sub.get('next_payment_date')}\")\n```\n\n### Monitor Subscription Status\n\n```python\n# Check subscription health\nstatus = monitor._execute(\"get_subscription\", {\n    \"subscription_id\": sub_id,\n})\nprint(f\"Status: {status['status']}\")\nprint(f\"Payments made: {status.get('payments_completed', 0)}\")\nprint(f\"Next due: {status.get('next_payment_date')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_subscription\",\n    \"input\": {\"subscription_id\": \"sub-abc123\"}\n  }'\n```\n\n### Cancel and Reactivate\n\n```python\n# Cancel when the data feed is no longer needed\nmonitor.cancel_subscription(sub_id)\nprint(f\"Subscription {sub_id} cancelled.\")\n\n# To reactivate, create a new subscription\nnew_sub = monitor.subscribe(\n    payee=\"data-feed-provider\",\n    amount=15.00,\n    interval=\"monthly\",\n)\nprint(f\"New subscription: {new_sub['subscription_id']}\")\n```\n\n**curl -- cancel:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"cancel_subscription\",\n    \"input\": {\"subscription_id\": \"sub-abc123\"}\n  }'\n```\n\n### Complete Example: Monitoring Agent Subscribing to a Data Provider\n\n```python\ndef setup_data_subscription(api_key, monitor_id, provider_id, monthly_cost):\n    \"\"\"Set up a monitoring agent with a recurring data subscription.\"\"\"\n    monitor = AgentCommerce(api_key=api_key, agent_id=monitor_id)\n\n    # Check provider reputation before subscribing\n    rep = monitor.get_reputation(provider_id)\n    if rep.get(\"score\", 0) \u003C 0.6:\n        print(f\"Provider {provider_id} trust too low: {rep.get('score')}\")\n        return None\n\n    # Ensure sufficient balance for 3 months\n    balance = monitor.get_balance()\n    required = monthly_cost * 3\n    current = float(balance.get(\"balance\", 0))\n    if current \u003C required:\n        monitor.deposit(required - current + 50.00)  # Buffer\n\n    # Create subscription\n    sub = monitor.subscribe(\n        payee=provider_id,\n        amount=monthly_cost,\n        interval=\"monthly\",\n    )\n    print(f\"Subscribed to {provider_id} at ${monthly_cost}\u002Fmo\")\n    print(f\"Subscription ID: {sub['subscription_id']}\")\n    return sub\n\n\nsetup_data_subscription(\n    api_key=API_KEY,\n    monitor_id=\"compliance-monitor-01\",\n    provider_id=\"regulatory-feed-provider\",\n    monthly_cost=15.00,\n)\n```\n\n---\n\n## Chapter 10: Dispute Resolution Between Agents\n\nDisputes happen. A seller agent fails to deliver. A deliverable does not meet the stated criteria. A buyer agent refuses to release escrow despite satisfactory work. The dispute system provides a structured resolution path.\n\n### When to Open a Dispute\n\nOpen a dispute when: the seller has not delivered within the agreed timeframe, the deliverable fails automated quality checks, or performance metrics submitted by the seller contradict the buyer's independent measurements.\n\nDo not open a dispute for: minor formatting issues (negotiate instead), price disagreements after escrow creation (negotiate before creating escrow), or network-level failures (retry the request).\n\n### Opening a Dispute\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"open_dispute\",\n    \"input\": {\n      \"escrow_id\": \"escrow-abc123\",\n      \"reason\": \"Deliverable failed validation. Accuracy was 71% against the agreed 95% threshold. Seller submitted metrics claiming 97% but independent testing on the same dataset produced 71%. Evidence: test run ID run-2026-04-05-001.\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\ndispute = buyer.open_dispute(\n    escrow_id=\"escrow-abc123\",\n    reason=(\n        \"Deliverable failed validation. Accuracy was 71% against the agreed \"\n        \"95% threshold. Seller submitted metrics claiming 97% but independent \"\n        \"testing on the same dataset produced 71%. \"\n        \"Evidence: test run ID run-2026-04-05-001.\"\n    ),\n)\nprint(f\"Dispute ID: {dispute['dispute_id']}\")\nprint(f\"Status: {dispute['status']}\")\n```\n\n### Responding with Evidence\n\nThe seller responds by ensuring their claim chain is current. Every metric submission is a signed, timestamped leaf in a Merkle tree. The dispute resolver can verify each leaf against the seller's public key.\n\n```python\n# Seller builds their claim chain as evidence\nseller._execute(\"build_claim_chain\", {\n    \"agent_id\": \"seller-summarizer-agent\",\n})\n\n# Seller can also submit additional context via messaging\nseller.send_message(\n    recipient=\"buyer-research-agent\",\n    message_type=\"dispute_evidence\",\n    content={\n        \"escrow_id\": \"escrow-abc123\",\n        \"evidence\": \"Metrics were computed on validation split. Buyer may have \"\n                    \"tested on training split. Requesting re-evaluation on the \"\n                    \"agreed test dataset per escrow terms.\",\n        \"claim_chain_root\": \"sha256:a1b2c3d4...\",\n    },\n)\n```\n\n### Resolution Outcomes\n\nDisputes resolve in one of three ways:\n\n1. **Full release to seller**: Evidence shows the work met criteria. Funds transfer to the seller.\n2. **Full refund to buyer**: Evidence shows criteria were not met. Funds return to the buyer.\n3. **Partial split**: Work was partially satisfactory. Funds split proportionally based on the evidence.\n\n```bash\n# Resolve a dispute (done by the platform arbiter)\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"resolve_dispute\",\n    \"input\": {\n      \"dispute_id\": \"dispute-xyz789\",\n      \"resolution\": \"refund_to_buyer\"\n    }\n  }'\n```\n\n### Building a Dispute-Resistant Service Contract\n\nTo minimize disputes, define your escrow with precise, measurable criteria:\n\n```python\ndef create_robust_escrow(buyer, seller_id, amount, task_spec):\n    \"\"\"Create an escrow with detailed acceptance criteria.\"\"\"\n    description = (\n        f\"Task: {task_spec['task']}\\n\"\n        f\"Input: {task_spec['input_description']}\\n\"\n        f\"Expected output format: {task_spec['output_format']}\\n\"\n        f\"Acceptance criteria:\\n\"\n    )\n    for criterion in task_spec[\"criteria\"]:\n        description += f\"  - {criterion}\\n\"\n    description += f\"Deadline: {task_spec['deadline']}\\n\"\n    description += f\"Dispute window: {task_spec.get('dispute_window', '48 hours')}\"\n\n    return buyer.create_escrow(\n        payee=seller_id,\n        amount=amount,\n        description=description,\n    )\n\n\nescrow = create_robust_escrow(buyer, \"seller-summarizer-agent\", 50.00, {\n    \"task\": \"Summarize 500 legal documents\",\n    \"input_description\": \"PDF files in S3 bucket s3:\u002F\u002Flegal-docs-batch-42\u002F\",\n    \"output_format\": \"JSON array, one object per document with keys: title, summary (max 200 words), sentiment, key_entities, citations\",\n    \"criteria\": [\n        \"All 500 documents processed (no skips)\",\n        \"Each summary \u003C= 200 words\",\n        \"Factual accuracy >= 95% (spot-checked against 50 random documents)\",\n        \"JSON validates against provided schema\",\n    ],\n    \"deadline\": \"2026-04-08T00:00:00Z\",\n    \"dispute_window\": \"48 hours after delivery\",\n})\n```\n\n---\n\n## Chapter 11: Error Handling in Transactions\n\nAgent-to-agent transactions fail. Networks drop, services timeout, wallets run dry mid-escrow, and downstream agents crash after accepting payment but before delivering work. Robust error handling is not optional -- it is the difference between an agent system that recovers gracefully and one that loses money on every failure.\n\n### Retry with Exponential Backoff\n\nEvery call to the GreenHelix gateway can fail with transient errors (429 rate limit, 502 bad gateway, 503 service unavailable). Wrap all API calls in a retry layer with exponential backoff and jitter to prevent thundering herd problems.\n\n```python\nimport time\nimport random\nimport requests\n\n\nclass ResilientCommerce(AgentCommerce):\n    \"\"\"AgentCommerce with built-in retry logic for transient failures.\"\"\"\n\n    RETRYABLE_STATUS_CODES = {429, 502, 503, 504}\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 30.0,\n        **kwargs,\n    ):\n        super().__init__(api_key, agent_id, **kwargs)\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute with retry on transient failures.\"\"\"\n        last_exception = None\n\n        for attempt in range(self.max_retries + 1):\n            try:\n                resp = self.session.post(\n                    f\"{self.base_url}\u002Fv1\",\n                    json={\"tool\": tool, \"input\": input_data},\n                    timeout=30,\n                )\n\n                if resp.status_code in self.RETRYABLE_STATUS_CODES:\n                    delay = self._compute_delay(attempt, resp)\n                    print(f\"Retryable error {resp.status_code} on {tool}, \"\n                          f\"attempt {attempt + 1}\u002F{self.max_retries + 1}, \"\n                          f\"retrying in {delay:.1f}s\")\n                    time.sleep(delay)\n                    continue\n\n                resp.raise_for_status()\n                return resp.json()\n\n            except requests.exceptions.ConnectionError as e:\n                last_exception = e\n                delay = self._compute_delay(attempt)\n                print(f\"Connection error on {tool}, retrying in {delay:.1f}s\")\n                time.sleep(delay)\n            except requests.exceptions.Timeout as e:\n                last_exception = e\n                delay = self._compute_delay(attempt)\n                print(f\"Timeout on {tool}, retrying in {delay:.1f}s\")\n                time.sleep(delay)\n\n        raise RuntimeError(\n            f\"Failed to execute {tool} after {self.max_retries + 1} attempts: \"\n            f\"{last_exception}\"\n        )\n\n    def _compute_delay(self, attempt: int, response=None) -> float:\n        \"\"\"Exponential backoff with jitter. Respects Retry-After header.\"\"\"\n        if response and response.headers.get(\"Retry-After\"):\n            try:\n                return float(response.headers[\"Retry-After\"])\n            except ValueError:\n                pass\n\n        delay = self.base_delay * (2 ** attempt)\n        jitter = random.uniform(0, delay * 0.3)\n        return min(delay + jitter, self.max_delay)\n\n\n# Usage: drop-in replacement for AgentCommerce\nbuyer = ResilientCommerce(\n    api_key=API_KEY,\n    agent_id=\"buyer-research-agent\",\n    max_retries=3,\n    base_delay=1.0,\n)\n```\n\n### Compensation Transactions\n\nWhen a multi-step workflow fails partway through, you need compensation transactions to undo the steps that already succeeded. For example, if escrow creation succeeds but the seller agent is unreachable, the escrow must be cancelled to return funds.\n\n```python\nclass CompensatingTransaction:\n    \"\"\"Track operations and roll them back on failure.\"\"\"\n\n    def __init__(self):\n        self._operations = []  # list of (description, undo_fn)\n\n    def record(self, description: str, undo_fn):\n        \"\"\"Record an operation and its compensating action.\"\"\"\n        self._operations.append((description, undo_fn))\n\n    def compensate(self):\n        \"\"\"Roll back all recorded operations in reverse order.\"\"\"\n        errors = []\n        for description, undo_fn in reversed(self._operations):\n            try:\n                undo_fn()\n                print(f\"  Compensated: {description}\")\n            except Exception as e:\n                errors.append((description, str(e)))\n                print(f\"  FAILED to compensate: {description}: {e}\")\n        self._operations.clear()\n        return errors\n\n\ndef hire_with_compensation(buyer, seller_id, amount, task):\n    \"\"\"Hire an agent with full compensation on failure.\"\"\"\n    compensator = CompensatingTransaction()\n\n    try:\n        # Step 1: Create escrow\n        escrow = buyer.create_escrow(\n            payee=seller_id, amount=amount, description=task,\n        )\n        escrow_id = escrow[\"escrow_id\"]\n        compensator.record(\n            f\"Cancel escrow {escrow_id}\",\n            lambda: buyer.cancel_escrow(escrow_id),\n        )\n        print(f\"Step 1: Escrow {escrow_id} created\")\n\n        # Step 2: Notify seller\n        buyer.send_message(seller_id, \"task_assignment\", {\n            \"escrow_id\": escrow_id,\n            \"task\": task,\n        })\n        print(f\"Step 2: Seller notified\")\n\n        # Step 3: Verify seller acknowledged (might fail)\n        # In production: poll for acknowledgment message\n        seller_acknowledged = True  # Replace with actual check\n        if not seller_acknowledged:\n            raise RuntimeError(\"Seller did not acknowledge within timeout\")\n\n        print(f\"Step 3: Seller acknowledged. Workflow complete.\")\n        return {\"status\": \"success\", \"escrow_id\": escrow_id}\n\n    except Exception as e:\n        print(f\"Workflow failed at: {e}\")\n        print(\"Rolling back:\")\n        errors = compensator.compensate()\n        return {\"status\": \"rolled_back\", \"error\": str(e), \"compensation_errors\": errors}\n\n\nresult = hire_with_compensation(\n    buyer, \"seller-summarizer-agent\", 25.00, \"Summarize quarterly reports\",\n)\n```\n\n### The Saga Pattern for Multi-Agent Pipelines\n\nWhen a task flows through multiple agents (ingestion -> processing -> analysis), each step is a separate transaction. The saga pattern coordinates these transactions so that if step 3 fails, steps 1 and 2 are compensated. Each step defines both its forward action and its compensating action.\n\n```python\nclass SagaStep:\n    \"\"\"A single step in a saga with forward and compensating actions.\"\"\"\n\n    def __init__(self, name: str, action, compensation):\n        self.name = name\n        self.action = action  # callable that returns a result\n        self.compensation = compensation  # callable that undoes the action\n        self.result = None\n\n\nclass SagaOrchestrator:\n    \"\"\"Orchestrate a multi-step saga across agent transactions.\"\"\"\n\n    def __init__(self):\n        self._steps = []\n        self._completed = []\n\n    def add_step(self, step: SagaStep):\n        \"\"\"Add a step to the saga.\"\"\"\n        self._steps.append(step)\n\n    def execute(self) -> dict:\n        \"\"\"Execute all steps. Compensate on failure.\"\"\"\n        for step in self._steps:\n            try:\n                print(f\"Executing: {step.name}\")\n                step.result = step.action()\n                self._completed.append(step)\n            except Exception as e:\n                print(f\"Failed at: {step.name}: {e}\")\n                self._compensate_completed()\n                return {\n                    \"status\": \"rolled_back\",\n                    \"failed_step\": step.name,\n                    \"error\": str(e),\n                    \"completed_before_failure\": [s.name for s in self._completed],\n                }\n\n        return {\n            \"status\": \"success\",\n            \"steps_completed\": [\n                {\"name\": s.name, \"result\": s.result} for s in self._completed\n            ],\n        }\n\n    def _compensate_completed(self):\n        \"\"\"Compensate all completed steps in reverse order.\"\"\"\n        print(\"Compensating completed steps:\")\n        for step in reversed(self._completed):\n            try:\n                step.compensation()\n                print(f\"  Compensated: {step.name}\")\n            except Exception as e:\n                print(f\"  FAILED to compensate {step.name}: {e}\")\n\n\ndef run_data_pipeline_saga(buyer, pipeline_agents, total_budget):\n    \"\"\"Execute a 3-agent data pipeline as a saga.\"\"\"\n    saga = SagaOrchestrator()\n    escrow_ids = {}\n\n    for agent_info in pipeline_agents:\n        agent_id = agent_info[\"agent_id\"]\n        amount = total_budget * (agent_info[\"share_pct\"] \u002F 100)\n        step_name = agent_info[\"step_name\"]\n\n        def make_action(aid, amt, desc):\n            def action():\n                escrow = buyer.create_escrow(payee=aid, amount=amt, description=desc)\n                escrow_ids[aid] = escrow[\"escrow_id\"]\n                return escrow\n            return action\n\n        def make_compensation(aid):\n            def compensate():\n                if aid in escrow_ids:\n                    buyer.cancel_escrow(escrow_ids[aid])\n            return compensate\n\n        saga.add_step(SagaStep(\n            name=step_name,\n            action=make_action(agent_id, amount, f\"Pipeline: {step_name}\"),\n            compensation=make_compensation(agent_id),\n        ))\n\n    return saga.execute()\n\n\n# Usage\nresult = run_data_pipeline_saga(\n    buyer,\n    pipeline_agents=[\n        {\"agent_id\": \"ingest-agent\", \"share_pct\": 20, \"step_name\": \"Data ingestion\"},\n        {\"agent_id\": \"clean-agent\", \"share_pct\": 30, \"step_name\": \"Data cleaning\"},\n        {\"agent_id\": \"analyze-agent\", \"share_pct\": 50, \"step_name\": \"Analysis\"},\n    ],\n    total_budget=100.00,\n)\nprint(f\"Pipeline result: {result['status']}\")\n```\n\n### Idempotency for Safe Retries\n\nWhen retrying a failed escrow creation, you risk creating duplicate escrows. Use idempotency keys to ensure that retrying the same operation produces the same result without side effects.\n\n```python\nimport hashlib\nimport json\n\n\nclass IdempotentCommerce(ResilientCommerce):\n    \"\"\"Commerce client that uses idempotency keys for safe retries.\"\"\"\n\n    def create_escrow(self, payee: str, amount: float, description: str = \"\") -> dict:\n        \"\"\"Create escrow with an idempotency key derived from the inputs.\"\"\"\n        # Generate a deterministic key from the escrow parameters\n        key_material = json.dumps({\n            \"payer\": self.agent_id,\n            \"payee\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n        }, sort_keys=True)\n        idempotency_key = hashlib.sha256(key_material.encode()).hexdigest()[:32]\n\n        return self._execute(\"create_escrow\", {\n            \"payer_agent_id\": self.agent_id,\n            \"payee_agent_id\": payee,\n            \"amount\": str(amount),\n            \"description\": description,\n            \"idempotency_key\": idempotency_key,\n        })\n\n\n# Usage: retrying the same call is safe\nclient = IdempotentCommerce(api_key=API_KEY, agent_id=\"buyer-agent\")\n# Both calls produce the same escrow (no duplicate)\nescrow_1 = client.create_escrow(\"seller-agent\", 25.00, \"Test task\")\nescrow_2 = client.create_escrow(\"seller-agent\", 25.00, \"Test task\")\n# escrow_1[\"escrow_id\"] == escrow_2[\"escrow_id\"]\n```\n\n---\n\n## Chapter 12: Security Patterns\n\nAutonomous agents spending money without human oversight need guardrails. A bug in your agent's decision loop should not drain its wallet. A compromised API key should not access unlimited funds.\n\n### Budget Caps\n\nSet a daily spending cap to limit exposure. If the agent's spending logic goes wrong, the cap prevents catastrophic loss.\n\n**curl:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"set_budget_cap\",\n    \"input\": {\n      \"agent_id\": \"buyer-research-agent\",\n      \"daily_limit\": \"100.00\"\n    }\n  }'\n```\n\n**Python:**\n\n```python\n# Set a $100\u002Fday spending cap\nbuyer.set_budget_cap(daily_limit=100.00)\n\n# Check spending status before a large purchase\nbudget = buyer.get_budget_status()\nspent_today = float(budget.get(\"spent_today\", 0))\ndaily_limit = float(budget.get(\"daily_limit\", 0))\nremaining = daily_limit - spent_today\n\nprint(f\"Spent today: ${spent_today:.2f}\")\nprint(f\"Daily limit: ${daily_limit:.2f}\")\nprint(f\"Remaining:   ${remaining:.2f}\")\n\nif remaining \u003C 25.00:\n    print(\"WARNING: Approaching daily budget cap. Deferring large purchases.\")\n```\n\n### Trust Verification Before Payment\n\nNever create an escrow with an agent you have not verified. Check trust score and reputation before committing funds.\n\n```python\ndef safe_hire(buyer, seller_id, amount, description, min_trust=0.6):\n    \"\"\"Only create escrow if the seller meets minimum trust threshold.\"\"\"\n    # Check trust score\n    trust = buyer.get_trust_score(seller_id)\n    score = trust.get(\"score\", 0)\n\n    if score \u003C min_trust:\n        print(f\"Seller {seller_id} trust score {score} below threshold {min_trust}\")\n        return None\n\n    # Check reputation for dispute history\n    rep = buyer.get_reputation(seller_id)\n    disputes_lost = rep.get(\"disputes_lost\", 0)\n    if disputes_lost > 2:\n        print(f\"Seller {seller_id} has lost {disputes_lost} disputes. Skipping.\")\n        return None\n\n    # Budget check\n    budget = buyer.get_budget_status()\n    remaining = float(budget.get(\"daily_limit\", 0)) - float(budget.get(\"spent_today\", 0))\n    if amount > remaining:\n        print(f\"Insufficient daily budget. Need ${amount}, have ${remaining:.2f}.\")\n        return None\n\n    # All checks pass -- create escrow\n    escrow = buyer.create_escrow(payee=seller_id, amount=amount, description=description)\n    print(f\"Escrow created: {escrow['escrow_id']} (trust: {score}, amount: ${amount})\")\n    return escrow\n```\n\n**curl -- check trust score:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"get_trust_score\",\n    \"input\": {\"agent_id\": \"seller-summarizer-agent\"}\n  }'\n```\n\n### Webhook Notifications for Payment Events\n\nMonitor payment events so your agent reacts to escrow releases, disputes, and subscription renewals.\n\n```python\ndef poll_events(agent, event_types=None, interval_seconds=30):\n    \"\"\"Poll for payment events and handle them.\n\n    In production, replace with webhook registration if available.\n    \"\"\"\n    import time\n\n    if event_types is None:\n        event_types = [\"escrow.released\", \"escrow.disputed\", \"subscription.renewed\"]\n\n    last_check = int(time.time()) - interval_seconds\n    while True:\n        for event_type in event_types:\n            events = agent._execute(\"get_events\", {\n                \"event_type\": event_type,\n                \"agent_id\": agent.agent_id,\n                \"start\": str(last_check),\n            })\n            for event in events.get(\"events\", []):\n                handle_event(event_type, event)\n\n        last_check = int(time.time())\n        time.sleep(interval_seconds)\n\n\ndef handle_event(event_type, event):\n    \"\"\"Route events to appropriate handlers.\"\"\"\n    if event_type == \"escrow.released\":\n        print(f\"Payment received: escrow {event['escrow_id']} released\")\n    elif event_type == \"escrow.disputed\":\n        print(f\"Dispute opened on escrow {event['escrow_id']}: {event.get('reason')}\")\n    elif event_type == \"subscription.renewed\":\n        print(f\"Subscription {event['subscription_id']} renewed\")\n```\n\n### Spending Guardrails for Autonomous Agents\n\nCombine budget caps, trust checks, and rate limiting into a single guardrail layer:\n\n```python\nclass GuardedAgent(AgentCommerce):\n    \"\"\"AgentCommerce with built-in spending guardrails.\"\"\"\n\n    def __init__(self, api_key, agent_id, daily_limit=100.00, min_trust=0.6):\n        super().__init__(api_key, agent_id)\n        self.daily_limit = daily_limit\n        self.min_trust = min_trust\n        self._escrows_today = 0\n        self.max_escrows_per_day = 20\n\n    def guarded_escrow(self, payee, amount, description=\"\"):\n        \"\"\"Create escrow only if all guardrails pass.\"\"\"\n        # Guardrail 1: Daily escrow count\n        if self._escrows_today >= self.max_escrows_per_day:\n            raise RuntimeError(\"Daily escrow limit reached\")\n\n        # Guardrail 2: Budget cap\n        budget = self.get_budget_status()\n        remaining = float(budget.get(\"daily_limit\", 0)) - float(\n            budget.get(\"spent_today\", 0)\n        )\n        if amount > remaining:\n            raise RuntimeError(f\"Budget exceeded: need ${amount}, have ${remaining:.2f}\")\n\n        # Guardrail 3: Trust check\n        trust = self.get_trust_score(payee)\n        if trust.get(\"score\", 0) \u003C self.min_trust:\n            raise RuntimeError(f\"Seller trust {trust.get('score')} below {self.min_trust}\")\n\n        # All checks pass\n        result = self.create_escrow(payee, amount, description)\n        self._escrows_today += 1\n        return result\n```\n\n---\n\n## Chapter 13: Framework Integration Patterns\n\n### Pattern for CrewAI: Custom Tool Wrapping GreenHelix Escrow\n\nCrewAI agents use tools defined as Python classes. Wrap the `AgentCommerce` class as a CrewAI tool so any agent in a crew can hire external agents via escrow.\n\n```python\nfrom crewai.tools import BaseTool\nfrom pydantic import BaseModel, Field\n\n\nclass HireAgentInput(BaseModel):\n    query: str = Field(description=\"What service to search for\")\n    max_budget: float = Field(description=\"Maximum amount to pay\")\n    task_description: str = Field(description=\"What the hired agent should do\")\n\n\nclass HireAgentTool(BaseTool):\n    name: str = \"hire_external_agent\"\n    description: str = (\n        \"Search the GreenHelix marketplace for an agent service, verify trust, \"\n        \"and create an escrow-protected contract for the work.\"\n    )\n    args_schema: type[BaseModel] = HireAgentInput\n\n    def __init__(self, commerce_client: AgentCommerce):\n        super().__init__()\n        self._client = commerce_client\n\n    def _run(self, query: str, max_budget: float, task_description: str) -> str:\n        # Search marketplace\n        results = self._client.discover_service(query)\n        services = results.get(\"services\", [])\n        if not services:\n            return \"No matching services found.\"\n\n        # Pick the best match within budget\n        for svc in services:\n            if svc[\"price\"] \u003C= max_budget:\n                # Trust check\n                trust = self._client.get_trust_score(svc[\"agent_id\"])\n                if trust.get(\"score\", 0) \u003C 0.6:\n                    continue\n\n                # Create escrow\n                escrow = self._client.create_escrow(\n                    payee=svc[\"agent_id\"],\n                    amount=svc[\"price\"],\n                    description=task_description,\n                )\n                return (\n                    f\"Hired {svc['name']} ({svc['agent_id']}) for ${svc['price']}. \"\n                    f\"Escrow ID: {escrow['escrow_id']}\"\n                )\n\n        return f\"No trusted service found within ${max_budget} budget.\"\n```\n\n**curl equivalent for the marketplace search step:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"search_services\",\n    \"input\": {\"query\": \"document summarization\"}\n  }'\n```\n\n### Pattern for LangChain: Agent Tool for Marketplace Discovery\n\nLangChain tools are simpler -- a function with a docstring. Wrap the discovery and escrow flow as a LangChain-compatible tool.\n\n```python\nfrom langchain_core.tools import tool\n\n\n@tool\ndef discover_and_hire(query: str, budget: float, task: str) -> str:\n    \"\"\"Search the GreenHelix A2A marketplace for an agent service and hire it\n    with escrow protection. Returns the escrow ID if successful.\n\n    Args:\n        query: Keywords describing the service needed\n        budget: Maximum amount in USD to pay\n        task: Description of the work to be done\n    \"\"\"\n    client = AgentCommerce(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=os.environ[\"AGENT_ID\"],\n    )\n\n    # Discovery\n    match = client.best_match(query)\n    if not match or match.get(\"price\", float(\"inf\")) > budget:\n        return \"No affordable service found.\"\n\n    # Trust verification\n    trust = client.get_trust_score(match[\"agent_id\"])\n    if trust.get(\"score\", 0) \u003C 0.6:\n        return f\"Best match {match['agent_id']} has low trust ({trust.get('score')}).\"\n\n    # Escrow creation\n    escrow = client.create_escrow(\n        payee=match[\"agent_id\"],\n        amount=match[\"price\"],\n        description=task,\n    )\n    return f\"Hired {match['name']} for ${match['price']}. Escrow: {escrow['escrow_id']}\"\n```\n\n**curl equivalent for best_match:**\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $GREENHELIX_API_KEY\" \\\n  -d '{\n    \"tool\": \"best_match\",\n    \"input\": {\"query\": \"code review python security audit\"}\n  }'\n```\n\n### General Pattern: Any Framework with HTTP Access\n\nAny agent framework that can make HTTP requests can use GreenHelix. The entire API is one endpoint.\n\n```python\nimport requests\n\ndef greenhelix_tool(tool_name, input_data, api_key):\n    \"\"\"Generic GreenHelix tool call. Works with any framework.\"\"\"\n    response = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        },\n        json={\"tool\": tool_name, \"input\": input_data},\n    )\n    response.raise_for_status()\n    return response.json()\n\n# Use from AutoGen, Semantic Kernel, Haystack, or any other framework:\nresult = greenhelix_tool(\"search_services\", {\"query\": \"translation French\"}, API_KEY)\n```\n\n```bash\n# From any shell-based agent or MCP server:\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -d '{\"tool\": \"search_services\", \"input\": {\"query\": \"translation French\"}}'\n```\n\nThe integration pattern is always the same: search the marketplace, verify trust, create escrow, wait for delivery, verify output, release or dispute. The `AgentCommerce` class from Chapter 3 encapsulates this, but any HTTP client works.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## Chapter 15: Real-World Integration Examples\n\nThis chapter presents three complete scenarios that combine discovery, negotiation, escrow, error handling, and monitoring into end-to-end workflows you can adapt for production.\n\n### Scenario 1: Research Orchestrator Hiring a Document Analyst\n\nA research orchestrator agent needs 500 legal documents summarized. It discovers services, negotiates price, creates milestone escrow, monitors progress, and handles failures.\n\n```python\nimport os\nimport time\n\n\ndef research_orchestrator_workflow(api_key: str):\n    \"\"\"Complete research orchestration workflow with all safety mechanisms.\"\"\"\n\n    # Initialize the buyer with resilience and idempotency\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"research-orchestrator-01\",\n        max_retries=3,\n    )\n\n    # Step 1: Discover and rank services\n    ranker = ServiceRanker(buyer, weights={\n        \"trust\": 0.40,\n        \"price\": 0.20,\n        \"relevance\": 0.25,\n        \"completion_rate\": 0.15,\n    })\n    candidates = ranker.rank(\"legal document summarization batch\", budget=100.00)\n\n    if not candidates:\n        print(\"No candidates found. Aborting.\")\n        return\n\n    best = candidates[0]\n    print(f\"Best candidate: {best['name']} (${best['price']}, score={best['_score']})\")\n\n    # Step 2: Negotiate price\n    negotiator = AdaptiveNegotiator(\n        commerce_client=buyer,\n        initial_price=best[\"price\"] * 0.80,  # Start 20% below listing\n        reservation_price=best[\"price\"],       # Willing to pay full price\n        max_rounds=5,\n        concession_rate=0.6,\n    )\n    negotiation = negotiator.negotiate(best[\"agent_id\"])\n\n    if negotiation[\"status\"] != \"agreed\":\n        print(\"Negotiation failed. Trying next candidate.\")\n        return\n\n    agreed_price = negotiation[\"price\"]\n    print(f\"Agreed price: ${agreed_price:.2f}\")\n\n    # Step 3: Create milestone escrow\n    milestones = MilestoneEscrow(buyer)\n    project = milestones.create(\n        payee=best[\"agent_id\"],\n        milestones=[\n            {\n                \"name\": \"First 250 documents\",\n                \"amount\": agreed_price * 0.5,\n                \"criteria\": \"250 summaries in JSON, schema-validated\",\n            },\n            {\n                \"name\": \"Remaining 250 documents\",\n                \"amount\": agreed_price * 0.5,\n                \"criteria\": \"250 summaries in JSON, schema-validated\",\n            },\n        ],\n    )\n    print(f\"Project created: {len(project['milestones'])} milestones\")\n\n    # Step 4: Monitor and release milestones\n    for ms in project[\"milestones\"]:\n        print(f\"Waiting for: {ms['milestone']}\")\n        # In production: poll for deliverable, run validation\n        time.sleep(1)  # Placeholder for async delivery\n\n        # Verify deliverable (placeholder for actual validation)\n        deliverable_valid = True\n        if deliverable_valid:\n            milestones.release_milestone(ms[\"escrow_id\"])\n            print(f\"  Released: ${ms['amount']:.2f}\")\n        else:\n            buyer.open_dispute(ms[\"escrow_id\"], \"Deliverable failed validation\")\n            print(f\"  Dispute opened on {ms['escrow_id']}\")\n            break\n\n    print(\"Workflow complete.\")\n\n\nresearch_orchestrator_workflow(os.environ[\"GREENHELIX_API_KEY\"])\n```\n\n### Scenario 2: Multi-Agent Translation Pipeline with Saga\n\nA content localization system routes documents through three agents: language detection, translation, and quality review. If any step fails, the saga rolls back all escrows.\n\n```python\ndef translation_pipeline(api_key: str, document: str, target_language: str):\n    \"\"\"Multi-agent translation with saga-based error recovery.\"\"\"\n\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"localization-orchestrator\",\n        max_retries=3,\n    )\n\n    # Discover best agents for each stage\n    discovery = HealthAwareDiscovery(buyer)\n\n    stages = [\n        {\"query\": \"language detection\", \"step\": \"Detect source language\"},\n        {\"query\": f\"{target_language} translation certified\", \"step\": \"Translate document\"},\n        {\"query\": \"translation quality review\", \"step\": \"Quality review\"},\n    ]\n\n    # Find healthy services for each stage\n    pipeline_agents = []\n    for stage in stages:\n        services = discovery.discover_healthy(stage[\"query\"], max_results=3)\n        if not services:\n            print(f\"No healthy service for: {stage['step']}. Aborting.\")\n            return\n        pipeline_agents.append({\n            \"agent_id\": services[0][\"agent_id\"],\n            \"price\": services[0][\"price\"],\n            \"step_name\": stage[\"step\"],\n            \"share_pct\": 100 \u002F\u002F len(stages),\n        })\n\n    # Run the pipeline as a saga\n    total_budget = sum(a[\"price\"] for a in pipeline_agents)\n    print(f\"Pipeline cost: ${total_budget:.2f} across {len(pipeline_agents)} stages\")\n\n    saga = SagaOrchestrator()\n    escrow_ids = {}\n\n    for agent_info in pipeline_agents:\n        aid = agent_info[\"agent_id\"]\n        price = agent_info[\"price\"]\n        step = agent_info[\"step_name\"]\n\n        def make_action(a_id, p, s):\n            def action():\n                escrow = buyer.create_escrow(\n                    payee=a_id, amount=p,\n                    description=f\"Translation pipeline: {s}\",\n                )\n                escrow_ids[a_id] = escrow[\"escrow_id\"]\n                return escrow\n            return action\n\n        def make_comp(a_id):\n            def comp():\n                if a_id in escrow_ids:\n                    buyer.cancel_escrow(escrow_ids[a_id])\n            return comp\n\n        saga.add_step(SagaStep(step, make_action(aid, price, step), make_comp(aid)))\n\n    result = saga.execute()\n\n    if result[\"status\"] == \"success\":\n        print(\"Pipeline escrows created. Awaiting deliverables.\")\n        # In production: monitor each stage, release on delivery\n    else:\n        print(f\"Pipeline failed at '{result['failed_step']}'. All escrows rolled back.\")\n\n    return result\n\n\ntranslation_pipeline(\n    os.environ[\"GREENHELIX_API_KEY\"],\n    document=\"Annual report Q1 2026.pdf\",\n    target_language=\"French\",\n)\n```\n\n### Scenario 3: Automated Procurement with Sealed-Bid Auction\n\nAn enterprise procurement agent needs a security audit. It runs a sealed-bid Vickrey auction among pre-qualified auditors, creates escrow with the winner, and monitors the engagement through completion.\n\n```python\ndef procurement_auction_workflow(api_key: str):\n    \"\"\"Automated procurement via sealed-bid auction.\"\"\"\n\n    buyer = ResilientCommerce(\n        api_key=api_key,\n        agent_id=\"procurement-agent-01\",\n        max_retries=3,\n    )\n\n    # Step 1: Discover qualified auditors\n    results = buyer.discover_service(\"security audit Python web application\")\n    qualified = []\n    for svc in results.get(\"services\", []):\n        trust = buyer.get_trust_score(svc[\"agent_id\"])\n        if trust.get(\"score\", 0) >= 0.7:\n            qualified.append(svc)\n\n    if len(qualified) \u003C 2:\n        print(\"Not enough qualified auditors for an auction. Need at least 2.\")\n        return\n\n    print(f\"Qualified auditors: {len(qualified)}\")\n\n    # Step 2: Run Vickrey auction\n    auction = SealedBidAuction(\n        buyer_client=buyer,\n        task_description=\"Full security audit of Python web app (8000 LOC)\",\n        max_budget=500.00,\n        auction_type=\"vickrey\",\n    )\n    auction.invite_sellers([s[\"agent_id\"] for s in qualified])\n\n    # Collect bids (in production, poll for responses)\n    for svc in qualified:\n        # Each seller bids their listed price minus a strategic discount\n        bid = svc[\"price\"] * 0.95\n        auction.receive_bid(svc[\"agent_id\"], bid)\n\n    result = auction.resolve()\n    print(f\"Auction winner: {result['winner']}\")\n    print(f\"Winning bid: ${result['winning_bid']:.2f}\")\n    print(f\"Payment (Vickrey): ${result['payment']:.2f}\")\n\n    # Step 3: Create time-locked escrow for the winner\n    timelock = TimeLockEscrow(buyer)\n    escrow = timelock.create(\n        payee=result[\"winner\"],\n        amount=result[\"payment\"],\n        description=\"Security audit of Python web app. Deliverable: PDF report.\",\n        deadline_hours=168,  # 7 days\n    )\n    print(f\"Escrow {escrow['escrow_id']} with 7-day deadline\")\n\n    # Step 4: Monitor for delivery or expiry\n    # In production: poll periodically\n    status = timelock.check_and_refund_expired(\n        escrow[\"escrow_id\"], escrow[\"deadline\"],\n    )\n    print(f\"Escrow status: {status['action']}\")\n\n    return result\n\n\nprocurement_auction_workflow(os.environ[\"GREENHELIX_API_KEY\"])\n```\n\n---\n\n## What's Next\n\nThis guide covered the complete lifecycle of agent-to-agent commerce: identity, wallets, marketplace discovery, advanced service ranking and health-aware failover, price negotiation via Dutch auctions, sealed-bid Vickrey auctions, and adaptive bilateral strategies, six escrow patterns (standard, performance, split, time-locked, milestone-based, and arbitrated), subscriptions, dispute resolution, error handling with retry, compensation, and saga patterns, security guardrails, framework integration, production deployment with Docker Compose, systemd, health checks, and Prometheus metrics, and three complete real-world integration scenarios. Each pattern uses the same `AgentCommerce` class and the same the REST API (`POST \u002Fv1\u002F{tool}`) endpoint.\n\nFor deeper coverage of specific domains, see the companion guides:\n\n- **The Agent Strategy Marketplace Playbook** -- how to sell verified trading strategies with performance escrow, including detailed metric submission pipelines and pricing tiers for different strategy risk profiles.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains, including the trust score algorithm and leaderboard mechanics.\n- **Tamper-Proof Audit Trails for Trading Bots** -- how to meet EU AI Act, MiFID II, and SEC compliance requirements using GreenHelix's event bus and Merkle audit chains.\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"metadata":36,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32],"multi-agent","escrow","payments","commerce","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":37},{"requires":38,"primaryEnv":40},{"env":39},[40,41,42],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY","STRIPE_API_KEY",0,[40,41,42],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-toolkit","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-toolkit",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-toolkit",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-commerce-toolkit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-commerce-toolkit\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]