Metadata-Version: 2.4
Name: payrail
Version: 0.1.0
Summary: Autonomous payment rails for AI agents on Base
Author: PayRail contributors
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: fastapi
Requires-Dist: python-dotenv
Requires-Dist: requests
Requires-Dist: uvicorn
Requires-Dist: web3>=6.0.0
Provides-Extra: crewai
Requires-Dist: crewai>=0.1.0; extra == 'crewai'
Provides-Extra: dev
Requires-Dist: black; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain>=0.1.0; extra == 'langchain'
Description-Content-Type: text/markdown

# PayRail

> Autonomous payment rails for AI agents

PayRail gives each AI agent its own Ethereum wallet and lets them settle work in **USDC on Base** without human card taps or shared API billing. When one agent buys help from another, it signs an ERC-20 `transferFrom` through the `AgentPayment` contract, producing a **public, verifiable receipt** on Base Sepolia (testnet) today and mainnet later.

![PayRail Demo](demo/payrail-demo.gif)

## How it works

```
┌────────┐     natural language      ┌─────────────────────┐     USDC + task id     ┌──────────────┐
│  User  │ ───────────────────────► │ Orchestrator agent  │ ────────────────────► │ Sub-agents   │
└────────┘                          │ (wallet signs tx)   │                       │ (each priced │
                                    └─────────────────────┘                       │  on-chain)   │
                                            ▲                                     └──────┬───────┘
                                            │                                            │
                                            └────────── aggregated answer ◄────────────┘
```

1. The user talks to an orchestrator agent with its own private key.
2. The orchestrator delegates to specialist agents (search, summarisation, …) registered with on-chain prices.
3. Before work is accepted, the orchestrator pays USDC through `AgentPayment`; every task id maps to an immutable receipt. **USDC approval is handled automatically** — no manual `approve` step required.

## Deployed contracts (Base Sepolia)

| Contract | Address |
|----------|---------|
| AgentRegistry | `0xc487C675333C7e5448A134f78D9823E7e34966d1` |
| AgentPayment  | `0x6049D852d470a5054cc1B2a60105e65e81ad7521` |

## Quickstart

```bash
git clone https://github.com/your-org/payrail.git
cd payrail
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
cp .env.example .env               # fill BASE_RPC_URL, PRIVATE_KEY, contract addresses
```

## 3-agent demo

Run a live research pipeline on Base Sepolia with a single command:

```bash
python demo/run_demo.py
# or pass your own question:
python demo/run_demo.py "How does proof-of-work mining work?"
```

The demo is fully self-bootstrapping:

1. **Generates** fresh sub-agent wallets if `SEARCH_AGENT_KEY` / `SUMMARISE_AGENT_KEY` are absent from `.env` (and prints the keys so you can persist them).
2. **Funds** each sub-agent with a small ETH top-up from the orchestrator wallet (for gas).
3. **Registers** each sub-agent in `AgentRegistry` if not already active.
4. **Pays** SearchAgent 0.01 USDC → gets search results.
5. **Pays** SummariseAgent 0.02 USDC → gets a summary.
6. **Prints** the final answer and a full payment trail with Basescan links.

Example output:

```
╔══════════════════════════════════════════════════════════╗
║              PayRail 3-Agent Demo  (Base Sepolia)        ║
╚══════════════════════════════════════════════════════════╝

Query  : What are autonomous AI agents and how do they pay each other?
Wallet : 0x71C7656EC7ab88b098defB751B7401B5f6d8976F

── Setup ──────────────────────────────────────────────────
  SearchAgent already registered and active
  SummariseAgent already registered and active
  SearchAgent    : 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2
  SummariseAgent : 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db

── Payments ───────────────────────────────────────────────
  Paying SearchAgent 0.01 USDC (task: search:3f2a1c…)
  ✓ Search payment confirmed — block 12483201
    https://sepolia.basescan.org/tx/0xabc123...
  Paying SummariseAgent 0.02 USDC (task: summarise:9b7e2d…)
  ✓ Summarise payment confirmed — block 12483209
    https://sepolia.basescan.org/tx/0xdef456...

── Answer ─────────────────────────────────────────────────
Summary for: 'What are autonomous AI agents...'
• AI agents are autonomous programs that perceive, decide, and act using LLMs...
• Multi-agent systems decompose complex tasks...
• On-chain USDC payments give agents a native billing layer...
• PayRail SDK: register a wallet → call send_payment() → receipt stored on-chain.

── Payment Trail ──────────────────────────────────────────
  Search        0.01 USDC  block 12483201
               https://sepolia.basescan.org/tx/0xabc123...
  Summarise     0.02 USDC  block 12483209
               https://sepolia.basescan.org/tx/0xdef456...

  Total paid : 0.03 USDC
```

## SDK usage

```python
from payrail import create_wallet, send_payment, get_balance
from payrail._abis import PAYMENT_ABI
import os
from dotenv import load_dotenv

load_dotenv()

wallet = create_wallet()
print(wallet["address"])

rpc     = os.environ["BASE_RPC_URL"]
usdc    = os.environ["USDC_CONTRACT_ADDR"]
payment = os.environ["PAYMENT_CONTRACT_ADDR"]

print("USDC balance:", get_balance(wallet["address"], rpc, usdc))

# send_payment auto-approves USDC if needed — no manual approve step.
receipt = send_payment(
    from_private_key=os.environ["PRIVATE_KEY"],
    to_address="0xRegisteredAgentAddress",
    amount_usdc=0.01,
    task_id="search-task-42",
    rpc_url=rpc,
    payment_contract_address=payment,
    payment_contract_abi=PAYMENT_ABI,
)
print(receipt["tx_hash"])
```

Task ids are hashed with Keccak-256 (UTF-8) before being sent as `bytes32` — use the same string in `verify_payment` / `get_receipt`.

## Contracts (Foundry)

```bash
cd contracts
forge install foundry-rs/forge-std OpenZeppelin/openzeppelin-contracts --no-commit
forge test
export PRIVATE_KEY=...
export USDC_CONTRACT_ADDR=0x036CbD53842c5426634e7929541eC2318f3dCF7e  # Base Sepolia USDC
forge script script/Deploy.s.sol --rpc-url $BASE_SEPOLIA_RPC_URL --broadcast
```

Paste the printed registry and payment addresses into `.env`.

## REST API

```bash
uvicorn api.main:app --reload
# or
docker compose up --build
```

Routes: `/pay`, `/payments`, `/agents`, `/receipts/{tx_hash}`, `/health`.

## Architecture

| Layer | Responsibility |
|-------|----------------|
| **AgentRegistry** | Agents register their own wallet, name, and minimum USDC per call; they can update price or deactivate; admin can force-deactivate via `Ownable`. |
| **AgentPayment** | Validates the recipient against the registry, pulls USDC with OpenZeppelin `SafeERC20`, stores `(from, to, amount, timestamp, taskId)` receipts, and emits `PaymentSent`. |
| **Python SDK** | Wallet helpers, typed contract calls (`web3.py`), automatic USDC approval, receipt/event decoding, and FastAPI routes for dashboards and remote agents. |
| **FastAPI** | REST API — all configuration via environment variables (no committed secrets). |

## Roadmap

- [x] AgentRegistry + AgentPayment deployed on Base Sepolia
- [x] Python SDK with auto-approve and on-chain receipts
- [x] 3-agent demo with full payment trail
- [ ] Base mainnet deployment and audited releases
- [ ] Multi-chain USDC settlement
- [ ] Agent marketplace discovery
- [ ] ERC-4337 smart-account support

## License

MIT — see [LICENSE](LICENSE).
