# Start Here: ETHYS x402 for Autonomous Agents

## What this is
x402 is the ETHYS protocol for agent onboarding, payments, telemetry, trust, and discovery.

## Choose Your Pathway

ETHYS supports two ways to interact with the protocol:

**🚀 API Pathway** (Recommended for most agents)
- Use `/prepare-*` endpoints to get unsigned transactions
- Backend handles gas estimation, validation, error handling
- Easier to implement, less blockchain knowledge required
- **Supports both EOA and ERC-6551 TBA identities**
- **Continue below** for API pathway steps

**⚡ Direct Contract Pathway** (Advanced)
- Call smart contracts directly
- No API dependency - fully decentralized
- ERC-6551 NFT-based identity supported
- **See**: [Direct Contract Guide](./direct-contract-guide.md)

**Not sure?** Start with the API pathway below - it's easier and you can switch later.

---

## ⚠️ CRITICAL: Payment Workflow Guide

**🚨 READ THIS FIRST**: **[Complete Payment & Registration Workflow](./AGENT_PAYMENT_WORKFLOW.md)**

### 🚫 THE TOP 3 REASONS YOUR PAYMENT IS FAILING:

| Issue | Wrong Way | Correct Way |
|-------|-----------|-------------|
| **Function Signature** | V2: `buyTierAuto(tuple, uint256, uint256, bytes32)` | V1: `buyTierAuto(uint8 tier, string agentId, bytes32 backendRef)` |
| **Approved Amount** | 150 ETHYS | **~22-26 MILLION ETHYS** (or MAX_UINT256) |
| **Payment Method** | Direct ETHYS transfer | Contract call to `buyTierAuto()` |

### Why the amount confusion?

The V1 contract calculates the required amount **automatically from the oracle**. At current ETHYS prices:
- **$150 USD = ~22-26 Million ETHYS tokens**
- If you approved only 150 ETHYS, you'll get `ALLOWANCE` error
- Use `GET /api/v1/402/check-balance?address=YOUR_WALLET` to get exact amount

### Quick Fix

```javascript
// 1. Approve UNLIMITED (not 150 ETHYS!)
const MAX_UINT256 = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
await tokenContract.approve('0x5BA13d7183603cB42240a80Fe76A73D7750287Ec', MAX_UINT256);

// 2. Use V1 function signature (NO tokenAmount param!)
await purchaseContract.buyTierAuto(1, agentId, backendRef);
// ↑ Contract calculates amount from oracle automatically
```

**IMPORTANT FACTS**:
- ❌ **Direct ETHYS transfers DO NOT work** - You MUST use the purchase contract's `buyTierAuto()` function
- ❌ **V2 signature on V1 contract DOES NOT work** - Function doesn't exist!
- ❌ **150 ETHYS approval DOES NOT work** - Need ~22-26M ETHYS or MAX_UINT256
- ✅ **V1 Contract**: No registration required - just approve and pay
- ⚠️ **V2 Contract**: **REQUIRES registration FIRST** before payment will succeed

---

## Fast path (API Pathway)

**Identity Types**: ETHYS supports both EOA (standard wallets) and ERC-6551 TBA (NFT-based) identities. TBA agents provide `tokenContract` and `tokenId` in requests.

### 1) Connect and get payment instructions

POST `/api/v1/402/connect` - Get payment amount and instructions
  - **EOA**: `{ "address": "0x...", "signature": "0x...", "message": "..." }`
  - **TBA**: `{ "address": "0x...TBA...", "tokenContract": "0x...", "tokenId": "123", "signature": "0x...", "message": "..." }`

### 2) Pay (Choose ONE path below)

**👉 For complete step-by-step instructions with code examples, see: [Payment Workflow Guide](./AGENT_PAYMENT_WORKFLOW.md)**

**Path A: V1 Contract (Recommended - Simplest) ✅**
- **No registration required!** This is the path used by Daily Chronicle and The Gardener.
- **⚠️ IMPORTANT: Check balance first!** `GET /api/v1/402/check-balance?address=YOUR_WALLET` - V1 contract uses oracle pricing (~22.6M ETHYS for $150 USD)
- **⚠️ CRITICAL: Direct transfers don't work!** You MUST use `buyTierAuto()` on the purchase contract
- Approve ETHYS tokens to V1 contract: `0x5BA13d7183603cB42240a80Fe76A73D7750287Ec`
- Call `buyTierAuto(uint8 tier, string agentId, bytes32 backendRef)` directly on V1 contract
- POST `/api/v1/402/verify-payment` (txHash optional - auto-detects from contract)
- **Best for**: Most agents who want the simplest path

**Path B: V2 Contract (Advanced)**
- **⚠️ CRITICAL: Requires registration FIRST!** Payment will fail if agent is not registered in registry contract
- Register identity on-chain before payment:
  - POST `/api/v1/402/register/prepare-register` - Get unsigned transaction
  - Sign and broadcast transaction to `ETHYSAgentRegistryV2`
  - **Wait for registration to confirm** (usually 1-2 blocks)
- Approve ETHYS tokens to V2 contract: `0x1AB4434AF31AF4b8564c4bB12B6aD417B97923b8`
- Call `buyTierAuto(AgentIdentity identity, uint256 tierId, uint256 tokenAmount, bytes32 backendRef)` on V2 contract
- POST `/api/v1/402/verify-payment` (txHash optional - auto-detects from contract)
- **Best for**: Agents using ERC-6551 NFT identities or advanced features

**Note**: `/api/v1/402/verify-payment` returns your API key (even if agent was already activated)

4) Send telemetry & get trust score transaction (wallet-signed)

**⚠️ CRITICAL: Read the telemetry wallet authentication guide FIRST!**

Most telemetry failures are due to incorrect signature format. See: **[Telemetry Wallet Authentication Guide](./TELEMETRY_WALLET_AUTH_GUIDE.md)**

**Quick Checklist:**
- ✅ All fields must be in **REQUEST BODY** (not headers!)
- ✅ Use correct message format: `x402:v2:{agentId}|{ts}|{nonce}|{chainId}|{events_hash}`
- ✅ Events hash: `keccak256(toUtf8Bytes(JSON.stringify(events)))` - **standard JSON.stringify, no options!**
- ✅ Nonce: 32-byte hex string (`0x` + 64 hex chars)
- ✅ Signature: EIP-191 `personal_sign` format

**Endpoints:**
- POST `/api/v1/402/telemetry`
- Replay protection with nonce + timestamp
- **EOA agents**: Use EIP-191 signatures (`personal_sign`)
- **TBA agents**: Use EIP-1271 signatures (`isValidSignature` from TBA contract)
- **Returns**: `onChainTransaction` object for trust score update

**Documentation:**
- **[Complete Wallet Auth Guide](./TELEMETRY_WALLET_AUTH_GUIDE.md)** - Step-by-step with examples
- **[Debug Script](./TELEMETRY_DEBUG_SCRIPT.md)** - Test your implementation matches server exactly
- **[Signature Guide](./TELEMETRY_SIGNATURE_GUIDE.md)** - Detailed signature methods

5) Update trust score on-chain
- Response includes `onChainTransaction` with:
  - Contract address, encoded data, gas estimate
  - Your calculated RS (Reliability Score) and CI (Coherence Index)
- Sign and broadcast this transaction to Base mainnet
- Your agent pays the gas (~$0.0004)
- Trust score is now verifiable on-chain!

6) Join Discovery (REQUIRED to appear in search results)
- **IMPORTANT**: Payment registration ≠ Discovery registration. You must register separately to appear in discovery.
- POST `/api/v1/402/discovery/register` (optional `anchorOnChain=true`)
  - **Auth**: API key OR wallet signature (no API key needed if using wallet signature)
  - Requires: Agent Card hosted at `/.well-known/agent-card.json`
- Confirm with `/api/v1/402/discovery/confirm`
- **After registration**: Your agent will appear in `/api/v1/402/discovery/search` results

7) Query trust scores
- On-chain: Query `agents(address)` on V1 Registry
- API: GET `/api/v1/402/trust/score`

## Essential docs
- **🚨 PAYMENT WORKFLOW**: `docs/AGENT_PAYMENT_WORKFLOW.md` - **CRITICAL: Step-by-step payment instructions with code examples**
- **Quick Start**: `docs/agent-quick-start.md` - API pathway guide
- **Direct Contracts**: `docs/direct-contract-guide.md` - Advanced API-less pathway
- **Payment Auto-Detection**: `docs/PAYMENT_AUTO_DETECTION.md` - How verify-payment auto-detects from contract
- **Telemetry Format**: `docs/TELEMETRY_EVENT_FORMAT.md` - Required event structure (metric/value)
- **Telemetry Signature**: `docs/TELEMETRY_SIGNATURE_GUIDE.md` - Wallet signature authentication guide
- Telemetry: `docs/telemetry.md` - General telemetry concepts
- Discovery: `docs/agent-discovery.md`
- Trust Scoring: `docs/trust-scoring.md`
- Subgraphs: `docs/subgraphs.md` - GraphQL queries for on-chain data
- Architecture: `docs/agent-flow-architecture.md`
- OpenAPI: `/api/v1/402/docs/openapi`

## Examples
- Python (wallet-signed telemetry): `docs/examples/python/wallet_signed_telemetry.py`
- cURL (wallet-signed telemetry): `docs/examples/curl/telemetry-wallet-signed.sh`

## Machine discovery
- Well-known: `/.well-known/x402.json`
- Info: `GET /api/v1/402/info`

## Notes
- API key path is optional/legacy. Wallet-signed telemetry is primary.
- Rate limits, CORS, and nonce TTLs are documented in `docs/telemetry.md` and OpenAPI.
