Skip to content

AaronUppal-AI/Shop3Agent_UIBuild

Repository files navigation

Shop3: Dual-Path X402 Agentic Commerce (Proof of Concept)

Shop3 is a proof-of-concept for agent-native commerce via the x402 micropayment protocol. The thesis: AI agents operating autonomously need a way to pay for services machine-to-machine — no OAuth, no credit cards, no human in the loop. x402 is that protocol. An agent hits an endpoint, receives HTTP 402 Payment Required, pays in USDC on-chain, proves it with a transaction hash, and gets access.

Shop3 demonstrates the full loop: a Claude-powered agent receives a natural-language shopping prompt, evaluates whether to use a real or synthetic payment path, executes the transaction autonomously, and publishes a cryptographically-linked receipt — all autonomously.

User prompt → agent searches (pays 402) → evaluates → pays for product → logs → publishes receipt

Features

🧠 Agent Intelligence

  • Autonomous Agentic Loop: Powered by the Anthropic Claude API, the agent runs a continuous "think-act" loop with a turn cap to prevent runaway execution. It uses native tool-calling to independently decide when to search, evaluate products, or execute payments.
  • Dual-Path Routing: The agent detects intent. Crypto price queries are routed to REAL X402 endpoints (CoinGecko); general web research is routed to a Synthetic X402 middleware (Nimble).
  • Strategic Evaluation: Unlike simple scripts, the agent evaluates search results against user constraints (budget, reputation, and service type) before deciding to complete a task.
  • Structured Search: The agent can request typed JSON from the x402 bridge — specifying fields like name, price, url, rating — instead of re-parsing raw descriptions.
  • Purchase Memory: The agent checks its own ClickHouse purchase history before buying to avoid duplicates across runs.

💸 Web3 Payments & Safety

  • x402 Micropayment Protocol: The core engine. The agent hits an X402 gateway, receives 402 Payment Required, pays 0.001 USDC on-chain, and retries with the x-payment-proof header.
  • Hybrid Signer Architecture:
    • Real X402 Flow: Uses a viem private key signer to pay the CoinGecko production API on Base Mainnet. No API keys needed; the payment IS the authentication.
    • Synthetic Path: Uses Circle Programmable Wallets on ARC-TESTNET to simulate merchant payments.
  • Safety Guards:
    • Spend Guard: A configurable daily spending limit (default $10) backed by ClickHouse so it persists across restarts.
    • Balance Check: Verifies on-chain USDC balance before submitting a payment.
    • Auto-Retry with Backoff: Transaction submissions retry with backoff and idempotency keys to prevent double-spending.
    • Max Turns Guard: Capped at MAX_AGENT_TURNS to prevent runaway API spend.
  • Payment Replay Protection: The x402 bridge tracks used transaction hashes to prevent reuse.

📊 Transparency & Observability

  • Verified Receipts (cited.md): Automatically publishes public markdown receipts via the Senso platform, citeable by search engines and other AI agents.
  • Purchase Audit Log: Every transaction is recorded in ClickHouse Cloud with query, product, price, tx hash, and latency.
  • Analytics CLI: npm run history:stats runs ClickHouse aggregations across the purchase log.
  • Lapdog + Datadog: In development, telemetry streams to a live local dashboard at lapdog.datadoghq.com. In production, spans forward to Datadog.
  • GEO Monitoring: Monitors how major LLMs perceive and cite Shop3 across the web via the Senso platform.

Quick Start

Prerequisites

  • Node.js 18+
  • A funded Circle wallet on ARC-TESTNET (Synthetic X402)
  • An Ethereum private key with ETH on Base mainnet (Real X402 / CoinGecko)
  • ClickHouse Cloud instance

Install

git clone https://github.com/PredictiveMoneyLaunderer/Shop3Agent_UIBuild.git
cd Shop3Agent_UIBuild
npm install

Configure

cp .env.example .env
Variable Required Description
ANTHROPIC_API_KEY Yes Claude API key
NIMBLE_API_KEY Yes Nimble web search API key
CLICKHOUSE_HOST Yes ClickHouse Cloud host (e.g. https://…:8443)
CLICKHOUSE_USER Yes ClickHouse username
CLICKHOUSE_PASSWORD Yes ClickHouse password
CIRCLE_API_KEY Yes* Circle Developer-Controlled Wallets API key
CIRCLE_ENTITY_SECRET Yes* Circle entity secret
CIRCLE_WALLET_ADDRESS Yes* Your Circle wallet address
CIRCLE_WALLET_ID Yes* Your Circle wallet ID
MERCHANT_WALLET_ADDRESS Yes* Destination wallet that receives USDC payments
WALLET_PRIVATE_KEY Yes** Ethereum private key on Base mainnet
CIRCLE_NETWORK No Default: ARC-TESTNET
USDC_TOKEN_ADDRESS No Default: 0x3600000000000000000000000000000000000000
USDC_TOKEN_ID No Circle token UUID fast-path; auto-discovered if omitted
SENSO_API_KEY No Publish to Senso; writes cited.md locally if absent
CMC_API_KEY No CoinMarketCap key for /crypto endpoint; uses demo prices if absent
DD_API_KEY No Datadog API key
DD_AGENT_HOST No Default: localhost
DD_AGENT_PORT No Default: 8125
PORT No Default: 3000
DEMO_MODE No Set true to bypass Circle and use simulated payments

* Required for live Synthetic X402 payments.
** Required for the Real X402 / CoinGecko crypto-price path.

Run

# Start server + serve web UI at http://localhost:3000
npm start

# Watch mode (restarts on file changes)
npm run dev

# Terminal / CLI mode (no server)
npm run cli

Agent Flow

User query
    │
    ▼
Keyword match? (price/value/worth + btc/eth/sol/matic…)
    │
    ├─ YES ──► Real X402 path
    │           x402-fetch + viem, Base mainnet
    │           Payment IS the auth — no API key needed
    │           getCryptoPriceWithX402(symbol) → CoinGecko Pro
    │
    └─ NO  ──► Synthetic X402 path
                GET /search?query=X
                ← 402 Payment Required (0.001 USDC)
                sendUSDC() via Circle, ARC-TESTNET
                Retry with x-payment-proof: <txHash>
    │
    ▼
insertPurchase → ClickHouse (agent_purchases)
    │
    ▼
Claude claude-3-5-sonnet-latest  (max 1024 tokens)
  └─ fallback: synthesizeFromResults (no API credits needed)
    │
    ▼
publishReport → Senso  or  cited.md (local)

Infrastructure

Runtime

Node.js (ESM, "type": "module"), single-process. The web UI, payment, search, logging, and publishing all run in the same Express process — no queue, no workers.

Agentic Pipeline

Anthropic Claude API (@anthropic-ai/sdk)

  • Model: claude-3-5-sonnet-latest
  • Called once per run with system prompt + retrieved search results
  • Not a tool-calling loop — Claude synthesizes answers from pre-fetched data

Search

Nimble API (Synthetic X402 path)

  • Routed through the local /search middleware
  • Returns titles, URLs, descriptions for a query
  • Auth: proof-of-payment header (x-payment-proof: <txHash>)

CoinGecko Pro (Real X402 path)

  • https://pro-api.coingecko.com/api/v3/simple/price
  • Auth: x402-fetch on-chain payment via Base mainnet
  • No API key required

Payment

Circle Developer-Controlled Wallets (@circle-fin/developer-controlled-wallets)

  • Wallet on ARC-TESTNET, funded with USDC
  • createTransaction submits the transfer; polls once after 4 s if txHash not immediately available
  • Falls back to simulated payment if credentials missing or DEMO_MODE=true

x402-fetch + viem

  • Real X402 for CoinGecko: signs payment intent with privateKeyToAccount on Base mainnet
  • WALLET_PRIVATE_KEY must hold ETH on Base for gas

Database

ClickHouse Cloud (@clickhouse/client)

  • Table agent_purchases auto-created on first run
  • Async inserts enabled (async_insert = 1)
  • Schema: timestamp, query, results, tx_hash, tx_id, price, network, result_count, demo_mode, session_id

External Services

Service Purpose Auth
Anthropic API Claude LLM ANTHROPIC_API_KEY
Nimble API Web search (Synthetic X402) NIMBLE_API_KEY
CoinGecko Pro Crypto prices (Real X402) On-chain payment via WALLET_PRIVATE_KEY
CoinMarketCap /crypto endpoint price feed CMC_API_KEY (demo fallback if absent)
Circle Programmable Wallets USDC payments on ARC-TESTNET CIRCLE_API_KEY + CIRCLE_ENTITY_SECRET
ClickHouse Cloud Purchase audit log CLICKHOUSE_*
Senso Report publishing SENSO_API_KEY
Datadog APM + StatsD metrics DD_API_KEY

API Endpoints

Method Path Description
GET / Web UI (ui/index.html)
POST /agent SSE stream — runs the agent; events: status, result, error
GET /search?query=X 402-gated Nimble web search (0.001 USDC)
GET /crypto?symbol=X 402-gated crypto price (0.001 USDC); demo prices if CMC_API_KEY unset
GET /data ClickHouse rows + cited.md as JSON
GET /health { "status": "ok" }

SSE Event Schema (POST /agent)

// status — emitted at each pipeline step
{ "step": "paying", "message": "Sending 0.001 USDC via Circle…", "amount": 0.001 }

// result — emitted when the agent finishes
{ "success": true, "answer": "", "report": {}, "results": [] }

// error — emitted if the agent throws
{ "message": "Circle transfer failed: …" }

Database Schema

CREATE TABLE IF NOT EXISTS agent_purchases (
  timestamp    DateTime DEFAULT now(),
  query        String,
  results      String,         -- JSON array of search results
  tx_hash      String,
  tx_id        String,
  price        Float64,
  network      String,
  result_count UInt32,
  demo_mode    UInt8 DEFAULT 0,
  session_id   String
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (timestamp, query);

Observability

telemetry.js initialises dd-trace and a hot-shots StatsD client at startup.

Function When emitted
trackPaymentMade(txHash, amount) After every USDC payment
trackAgentResponseTime(ms) End of each agent run
trackSearchCompleted(query, count) After a successful search
trackError(err) On any caught error

Metrics are silently dropped if DD_AGENT_HOST is unreachable.


Key Dependencies

Package Version Role
express ^5.2.1 HTTP server + SSE
@anthropic-ai/sdk ^0.98.0 Claude LLM
@circle-fin/developer-controlled-wallets ^10.3.1 USDC payments (Synthetic X402)
@clickhouse/client ^1.18.5 Purchase log
x402-fetch Real X402 HTTP client
viem Ethereum account + Base mainnet signing
dd-trace ^5.104.0 Datadog APM
hot-shots ^14.3.1 StatsD client
uuid ^14.0.0 Session IDs + idempotency keys

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors