Metadata-Version: 2.4
Name: whop-x402
Version: 1.0.0
Summary: Whop x402 Payment Gateway Adapter for AI Agents
Author-email: Veridex Developer <dev@veridex.network>
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: web3>=6.0.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pycryptodome>=3.18.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Dynamic: license-file

# whop-x402

An open-source, framework-agnostic x402-compatible adapter that allows Python-based AI agents to accept payments via Whop (subscriptions, memberships, digital goods) and automatically route native revenue into BNB Chain PancakeSwap on-chain buybacks.

## Features
- **x402 protocol support**: Emits challenge payloads compatible with the x402 agent-to-agent protocol.
- **On-chain routing**: Executes native BNB swaps for utility tokens on PancakeSwap V2 (BSC).
- **Price Oracle**: Automatic CoinGecko USD-to-BNB price tracking.
- **Webhook validation**: Secure HMAC-SHA256 signature verification of Whop payments.
- **Event hooks**: Typed async callbacks for custom triggers.

## Installation
```bash
pip install whop-x402
```

## Quick Start (FastAPI Webhook Example)

Here is how to set up the adapter with a FastAPI server to monetize your AI agent:

```python
import os
from fastapi import FastAPI, Request, HTTPException
from whop_x402 import WhopX402Adapter, WhopConfig, ChainConfig

app = FastAPI()

# 1. Initialize Adapter
whop_config = WhopConfig(
    apiKey=os.getenv("WHOP_API_KEY"),
    webhookSecret=os.getenv("WHOP_WEBHOOK_SECRET")
)

chain_config = ChainConfig(
    rpcUrl=os.getenv("BSC_RPC_URL", "https://bsc-dataseed.binance.org/"),
    chainId=56, # 56 for Mainnet, 97 for Testnet
    walletPrivateKey=os.getenv("WALLET_PRIVATE_KEY"),
    tokenAddress=os.getenv("BUYBACK_TOKEN_ADDRESS"), # Target agent utility token
    buybackPercentage=100.0, # Swap 100% of revenue to token
    slippagePercentage=0.5
)

adapter = WhopX402Adapter(whop_config, chain_config)

# 2. Register Event Hooks
@adapter.on("payment_received")
async def on_payment(event):
    print(f"💰 Payment of {event.amountCents} cents received from {event.payer}")

@adapter.on("buyback_executed")
async def on_buyback(event):
    print(f"🔄 Buyback Executed: Swapped {event.amountBNB} BNB. Tx Hash: {event.txHash}")

@adapter.on("buyback_failed")
async def on_failed(event):
    print(f"❌ Buyback Failed: {event.error}")

# 3. Define Webhook Ingestion Route
@app.post("/whop-webhook")
async def whop_webhook(request: Request):
    # Fetch raw body for signature verification
    body = await request.body()
    signature = request.headers.get("X-Whop-Signature")
    
    if not signature:
        raise HTTPException(status_code=400, detail="Missing X-Whop-Signature header")

    result = await adapter.handle_payment_webhook(body.decode('utf-8'), signature)
    
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result.get("error"))
        
    return {"status": "ok", "txHash": result.get("txHash")}
```

## Fetch.ai & Agentverse (ASI:One Chat Protocol)

`examples/agentverse_chat_agent.py` is a complete, production-grade uAgent that is
discoverable on ASI:One / Agentverse. It runs two components in one process:

1. A **uAgent** using the official ASI:One Chat Protocol
   (`uagents_core.contrib.protocols.chat`). When a user asks for premium access, it
   returns a Whop checkout link (the x402 payment challenge); ask it for "proof" to get
   the latest on-chain buyback tx hash.
2. A **FastAPI webhook server** (`/status`, `/whop-webhook`) that HMAC-verifies incoming
   Whop `payment.succeeded` events and triggers the PancakeSwap buyback.

```bash
pip install uagents==0.23.6 uagents-core==0.4.0 fastapi uvicorn python-dotenv whop-x402
python3 examples/agentverse_chat_agent.py
```

Enable the mailbox (already set with `mailbox=True`), then register the agent on
Agentverse and expose the webhook publicly (e.g. `cloudflared tunnel --url http://localhost:8080`)
as your Whop webhook destination. See the
[ASI:One chat protocol guide](https://innovationlab.fetch.ai/resources/docs/examples/chat-protocol/asi-compatible-uagents).

## License
MIT License.
