# x402 Agent Lifecycle Flow

## Overview

This document describes the complete lifecycle for an autonomous agent to connect, pay, and activate API access via the x402 protocol.

---

## Stage 0: Agent Connection

### Request
```bash
POST /api/v1/402/connect
Content-Type: application/json

{
  "address": "0xAgentWallet",
  "signature": "0x...",
  "message": "Connect to ETHYS"
}
```

### Process
1. Verify wallet signature using EIP-712
2. Check if agent already exists
3. Create user record (`x402_users/{address}`)
4. Create agent record (`x402_agents/{agentId}`)
5. Link both via `controllerAddress`

### Response (Success)
```json
{
  "success": true,
  "message": "Connected successfully. Payment required to activate API access.",
  "agentId": "agent_abcdef123456",
  "x402_instructions": {
    "protocol": "x402",
    "token": {
      "address": "0x1dd996287db5a95d6c9236efb10c7f90145e5b07",
      "symbol": "ETHYS",
      "chain": "base-mainnet",
      "chainId": 8453
    },
    "amount": "1000000000000000000",
    "amountHuman": "1",
    "payTo": "0x5BA13d7183603cB42240a80Fe76A73D7750287Ec",
    "memo": "activate:agent_abcdef123456",
    "nextStep": {
      "method": "POST",
      "endpoint": "/api/v1/402/verify-payment",
      "body": {
        "agentId": "agent_abcdef123456",
        "txHash": "0x..."
      }
    },
    "instructions": {
      "@context": "https://ethys.dev/402/instructions",
      "steps": [
        {
          "action": "obtain_token",
          "token_address": "0x1dd996287db5a95d6c9236efb10c7f90145e5b07",
          "symbol": "ETHYS",
          "chain": "base-mainnet",
          "dex_links": {
            "uniswap": "https://app.uniswap.org/#/swap?inputCurrency=ETH&outputCurrency=0x1dd996287db5a95d6c9236efb10c7f90145e5b07&chain=base",
            "1inch": "https://app.1inch.io/#/8453/simple/swap/ETH/0x1dd996287db5a95d6c9236efb10c7f90145e5b07"
          }
        },
        {
          "action": "call_contract",
          "contract_address": "0x5BA13d7183603cB42240a80Fe76A73D7750287Ec",
          "contract_abi": [...],
          "function_name": "buyTierAuto",
          "function_params": [
            1,
            "agent_abcdef123456",
            "0x..."
          ],
          "estimated_gas": "150000"
        },
        {
          "action": "submit_verification",
          "endpoint": "/api/v1/402/verify-payment",
          "fields": ["agentId", "txHash"]
        }
      ]
    }
  }
}
```

### Response (Already Exists)
```json
{
  "success": true,
  "message": "Agent already registered",
  "agentId": "agent_abcdef123456",
  "status": "active",
  "x402_instructions": {
    "status": "already_activated",
    "apiKey": "ethys_<redacted>",
    "telemetry_endpoint": "/api/v1/402/telemetry",
    "trust_endpoint": "/api/v1/402/trust/update"
  }
}
```

---

## Stage 1: Agent Executes Payment

The agent calls the purchase contract's `buyTierAuto` function:
- **Contract**: `ETHYSTierPurchases` (`0x5BA13d7183603cB42240a80Fe76A73D7750287Ec`)
- **Function**: `buyTierAuto(uint8 tier, string agentId, bytes32 backendRef)`
- **Parameters**: 
  - `tier`: `1` (activation tier)
  - `agentId`: Agent identifier from connect response
  - `backendRef`: Unique reference for idempotency
- **Token**: ETHYS (must be approved first)
- **Amount**: Automatically calculated by contract based on oracle pricing

**Prerequisites:**
1. Agent must acquire ETHYS tokens via DEX
2. Agent must approve the contract to spend ETHYS tokens

**Blockchain Transaction:**
```solidity
// Step 1: Approve contract to spend tokens (if not already approved)
token.approve(purchaseContract, MAX_UINT256);

// Step 2: Call purchase function
purchaseContract.buyTierAuto(1, agentId, backendRef);
```

---

## Stage 2: Payment Verification

### Request
```bash
POST /api/v1/402/verify-payment
Content-Type: application/json

{
  "agentId": "agent_abcdef123456",
  "txHash": "0x1234567890abcdef..."
}
```

### Process
1. Fetch transaction from Base mainnet
2. Verify transaction receipt (confirmations ≥ 1)
3. Verify token contract matches ETHYS
4. Verify recipient matches merchant wallet
5. Verify amount ≥ required minimum
6. Verify memo/note matches `activate:{agentId}`
7. Check for duplicate processing
8. Create payment record
9. Activate agent & user
10. Generate API key

### Response (Success)
```json
{
  "success": true,
  "message": "Payment confirmed. API access activated.",
  "agentId": "agent_abcdef123456",
  "api_key": "ethys_abc123xyz789_1727827200_def456",
  "telemetry_endpoint": "/api/v1/402/telemetry",
  "trust_endpoint": "/api/v1/402/trust/update",
  "reference_docs": "https://ethys.dev/402/docs",
  "rate_limits": {
    "telemetry": "1000/hour",
    "trust_updates": "100/hour"
  }
}
```

### Response (Verification Failed)
```json
{
  "success": false,
  "error": "Payment verification failed",
  "details": {
    "reason": "insufficient_amount",
    "expected": "1000000000000000000",
    "received": "500000000000000000"
  }
}
```

---

## Stage 3: Agent Uses API

### Telemetry Submission
```bash
POST /api/v1/402/telemetry
Authorization: Bearer ethys_abc123xyz789_1727827200_def456
Content-Type: application/json

{
  "events": [
    {
      "metric": "task_completed",
      "value": 1,
      "timestamp": 1727827200
    },
    {
      "metric": "latency_ms",
      "value": 150,
      "timestamp": 1727827201
    }
  ]
}
```

**Response:**
```json
{
  "success": true,
  "message": "Telemetry recorded",
  "events_processed": 2,
  "timestamp": 1727827202
}
```

### Trust Score Update
```bash
POST /api/v1/402/trust/update
Authorization: Bearer ethys_abc123xyz789_1727827200_def456
Content-Type: application/json

{
  "agentId": "agent_abcdef123456",
  "trustData": {
    "reliability_score": 0.95,
    "coherence_index": 0.88,
    "interactions": 150
  }
}
```

**Response:**
```json
{
  "success": true,
  "message": "Trust score updated",
  "agentId": "agent_abcdef123456",
  "currentScore": {
    "rs": 0.95,
    "ci": 0.88
  },
  "timestamp": 1727827203
}
```

---

## Additional Endpoints

### Status Check
```bash
GET /api/v1/402/status/{agentId}
```

**Response:**
```json
{
  "success": true,
  "agentId": "agent_abcdef123456",
  "status": "active",
  "lastSeen": 1727827200,
  "trustScore": {
    "rs": 0.95,
    "ci": 0.88
  },
  "activatedAt": 1727827100,
  "wallet": "0xAgentWallet"
}
```

### Usage Metrics
```bash
GET /api/v1/402/usage/{agentId}
Authorization: Bearer ethys_...
```

**Response:**
```json
{
  "success": true,
  "agentId": "agent_abcdef123456",
  "usage": {
    "telemetryCalls": 450,
    "trustUpdates": 12,
    "periodStart": 1727823600,
    "periodEnd": 1727827200
  },
  "rateLimits": {
    "telemetry": {
      "limit": 1000,
      "used": 450,
      "remaining": 550,
      "resetAt": 1727830800
    },
    "trustUpdates": {
      "limit": 100,
      "used": 12,
      "remaining": 88,
      "resetAt": 1727830800
    }
  }
}
```

### Webhook Registration
```bash
POST /api/v1/402/webhook/register
Authorization: Bearer ethys_...
Content-Type: application/json

{
  "agentId": "agent_abcdef123456",
  "url": "https://agent.example.com/webhooks/ethys",
  "events": ["payment_verified", "trust_updated", "status_changed"]
}
```

**Response:**
```json
{
  "success": true,
  "message": "Webhook registered",
  "webhookId": "webhook_xyz789",
  "agentId": "agent_abcdef123456",
  "url": "https://agent.example.com/webhooks/ethys",
  "events": ["payment_verified", "trust_updated", "status_changed"],
  "registeredAt": 1727827200
}
```

**Webhook Payload Example:**
```json
{
  "event": "payment_verified",
  "agentId": "agent_abcdef123456",
  "timestamp": 1727827200,
  "data": {
    "txHash": "0x123...",
    "apiKey": "ethys_...",
    "status": "active"
  }
}
```

### Agent Disconnect
```bash
POST /api/v1/402/disconnect
Authorization: Bearer ethys_...
Content-Type: application/json

{
  "agentId": "agent_abcdef123456",
  "reason": "Scheduled maintenance",
  "suspend": true
}
```

**Response:**
```json
{
  "success": true,
  "message": "Agent suspended successfully",
  "agentId": "agent_abcdef123456",
  "status": "suspended",
  "canReconnect": true,
  "timestamp": 1727827200
}
```

## Error Scenarios

### HTTP 402 Payment Required
If agent tries to use API without activation:
```json
{
  "success": false,
  "error": "Payment Required",
  "code": 402,
  "x402_instructions": {
    "protocol": "x402",
    "token": {...},
    "amount": "...",
    "payTo": "..."
  }
}
```

### Invalid API Key
```json
{
  "success": false,
  "error": "Invalid or expired API key",
  "code": 401
}
```

### Duplicate Payment
```json
{
  "success": false,
  "error": "Transaction already processed",
  "code": 409,
  "existing_payment": {
    "paymentId": "...",
    "txHash": "0x...",
    "processedAt": "..."
  }
}
```

---

## State Transitions

```
[pending_payment] → (payment verified) → [active]
[active] → (expired/deactivated) → [inactive]
```

## Firestore Updates

After successful payment verification:
```json
// x402_users/{address}
{
  "status": "active",
  "activatedAt": Timestamp,
  "apiKey": "ethys_<redacted>"
}

// x402_agents/{agentId}
{
  "status": "active",
  "activatedAt": Timestamp,
  "apiKey": "ethys_<redacted>"
}

// x402_payments/{paymentId}
{
  "verified": true,
  "verifiedAt": Timestamp
}

// x402_api_keys/{keyId}
{
  "agentId": "agent_abcdef123456",
  "keyHash": "sha256_hash",
  "createdAt": Timestamp
}
```

