npm package: @motus-dao/root-agent
Description: TypeScript SDK for the Celo ecosystem — onboard humans with wallets, fiat ramps, identity verification, and ERC-8004 AI agents.
Latest version: 0.1.0

# root-agent-sdk

> Pay. Verify. Create your agent. Access the onchain economy.

The missing SDK between real humans and the Celo agentic economy.

## What it does

root-agent-sdk gives any Celo project 3 core functions to onboard verified humans and create AI agents with economic agency:

- **`createUser()`** — Auto wallet + fiat ramp (WaaP + Transak)
- **`verifyUser()`** — Human verification with Self Agent ID (ZK credentials)
- **`createAgent()`** — ERC-8004 agent wallet with inherited ZK credentials

Plus optional:

- **`createEscrow()`** — Conditional payments with configurable split fees (PsyEscrow)

## Install

```bash
npm install root-agent-sdk
```

## Quick Start

```typescript
import { RootAgent } from 'root-agent-sdk'

const root = new RootAgent({
  celoNetwork: 'mainnet',
  transakApiKey: 'your-key',
  selfConfig: { appId: 'your-app', scope: ['humanity'] }
})

// 1. Onboard a real human
const user = await root.createUser({ method: 'email', email: 'user@example.com' })

// 2. Fund their wallet (returns Transak URL)
const fundUrl = await user.fundWallet()

// 3. Verify their identity (ZK, no data exposed)
const verified = await root.verifyUser({
  user,
  method: 'self',
  scope: ['humanity', 'sanctions']
})

// 4. Create their agent with inherited credentials
const agent = await root.createAgent({
  owner: user.wallet,
  name: 'myAgent',
  selfCredentials: verified.zkCredentials,
  permissions: ['transfer', 'escrow']
})

// Agent can now transact on Celo with verifiable human identity
await agent.execute({ to: '0x...', value: '1000000' })
```

## How PsyChat Uses root-agent-sdk

PsyChat is a mental health platform where psychologists offer therapy sessions to patients on Celo. The root-agent-sdk powers the full flow:

1. **Patient onboarding** — `createUser()` gives each patient a Celo wallet and lets them buy cUSD via Transak
2. **Identity verification** — `verifyUser()` confirms the patient is a real human via Self Protocol (ZK proof of humanity), without exposing personal data
3. **Payment agent** — `createAgent()` creates an AI agent that manages session payments. The agent inherits the patient's ZK credentials, proving it acts on behalf of a verified human
4. **Session escrow** — `createEscrow()` deploys a PsyEscrow contract that holds cUSD until the session completes:
   - Patient deposits before the session
   - If they cancel 48h+ in advance → full refund
   - After session completes → 85% to psychologist, 10% to platform, 5% gas reserve
   - No-show after 1h grace → same split (anti-dropout)
   - Emergency timeout at 7 days → auto-release

```typescript
const escrow = await root.createEscrow({
  agent: agent.wallet,
  splits: {
    provider: { address: psychologist.wallet, share: 8500 },
    platform: { address: '0xPlatform...', share: 1000 },
    gasReserve: { share: 500 }
  },
  cancelWindow: 48 * 3600,
  timeout: 7 * 86400
})

// Patient deposits for a session
await escrow.instance.deposit('session-001', psychologist.wallet, '25.00', scheduledTime)

// After session completes, agent releases payment
await escrow.instance.release('session-001')
```

## API Reference

### `new RootAgent(config)`

Creates a new SDK instance.

```typescript
interface RootAgentConfig {
  celoNetwork: 'mainnet' | 'alfajores'  // Required
  transakApiKey?: string                  // For fiat on-ramp
  selfConfig?: {                          // For identity verification
    appId: string
    scope: SelfScope[]  // 'age' | 'nationality' | 'sanctions' | 'humanity'
  }
  waapConfig?: {                          // For managed wallets (Human.tech)
    appId: string
    apiKey: string
  }
  gasSponsorship?: boolean                // Enable gas sponsorship
}
```

---

### `root.createUser(options)`

Creates a new user with an auto-generated Celo wallet.

```typescript
const user = await root.createUser({
  method: 'email',        // 'email' | 'social' | 'phone'
  email: 'user@test.com'  // required if method is 'email'
  // socialProvider: 'google' | 'apple' | 'twitter'  — if method is 'social'
  // phone: '+1234567890'                             — if method is 'phone'
})
```

**Returns: `RootUser`**

| Field | Type | Description |
|-------|------|-------------|
| `wallet` | `string` | Celo wallet address |
| `method` | `string` | Auth method used |
| `identifier` | `string` | Email, phone, or social ID |
| `fundWallet()` | `() => Promise<string>` | Returns Transak URL for buying cUSD |
| `verified` | `boolean` | Whether identity is verified |
| `selfId` | `string?` | Self Agent ID (after verification) |

---

### `root.verifyUser(options)`

Verifies a user's identity using Self Protocol with ZK proofs.

```typescript
const verification = await root.verifyUser({
  user: user,                                    // RootUser from createUser()
  method: 'self',                                // Verification provider
  scope: ['age', 'nationality', 'sanctions']     // Credentials to verify
})
```

**Returns: `UserVerification`**

| Field | Type | Description |
|-------|------|-------------|
| `selfId` | `string` | Self Agent ID |
| `soulboundNFT` | `string?` | Soulbound NFT reference |
| `zkCredentials` | `ZKCredential[]` | Array of verified ZK credentials |
| `verified` | `boolean` | All requested scopes verified |

---

### `root.createAgent(options)`

Creates an ERC-8004 AI agent with its own wallet.

```typescript
const agent = await root.createAgent({
  owner: user.wallet,
  name: 'myAgent',
  selfCredentials: verification.zkCredentials,  // Optional: inherit human's ZK creds
  permissions: ['transfer', 'escrow']           // 'transfer' | 'escrow' | 'swap' | 'delegate'
})
```

**Returns: `RootAgentInstance`**

| Field | Type | Description |
|-------|------|-------------|
| `wallet` | `string` | Agent's Celo wallet |
| `owner` | `string` | Owner's wallet address |
| `name` | `string` | Agent name |
| `selfId` | `string?` | Agent's Self ID |
| `zkCredentials` | `ZKCredential[]?` | Inherited ZK credentials |
| `permissions` | `AgentPermission[]` | Allowed operations |
| `execute(tx)` | `Function` | Execute a transaction |
| `id` | `string?` | Agentscan registration ID |

#### `agent.execute(tx)`

```typescript
const result = await agent.execute({
  to: '0xRecipient...',
  value: '1000000',     // Amount in wei (for cUSD transfers)
  data: '0x...'         // Optional: raw calldata for contract calls
})
// Returns: { hash, status: 'success' | 'failed', blockNumber }
```

---

### `root.createEscrow(config)`

Deploys or connects to a PsyEscrow smart contract.

```typescript
const escrow = await root.createEscrow({
  agent: agent.wallet,
  splits: {
    provider: { address: '0xPsychologist...', share: 8500 },
    platform: { address: '0xPlatform...', share: 1000 },
    gasReserve: { share: 500 }
  },
  cancelWindow: 48 * 3600,   // 48 hours in seconds
  timeout: 7 * 86400         // 7 days in seconds
})
```

#### Escrow methods

```typescript
// Deposit cUSD for a session
await escrow.instance.deposit('session-id', psychologistAddress, '25.00', scheduledTimestamp)

// Release funds after session completes (split fee applied)
await escrow.instance.release('session-id')

// Cancel session (full refund if before cancel window)
await escrow.instance.cancel('session-id')

// Claim no-show (after grace window)
await escrow.instance.claimNoShow('session-id')

// Read session state
const session = await escrow.instance.getSession('session-id')
```

---

### `root.registerAgent(agent)`

Registers an agent on agentscan.info.

```typescript
const agentId = await root.registerAgent(agent)
```

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                     Your App / DApp                      │
├─────────────────────────────────────────────────────────┤
│                    root-agent-sdk                        │
│                                                          │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐ │
│  │createUser│  │verifyUser│  │createAgent│  │ escrow  │ │
│  │          │  │          │  │          │  │         │ │
│  │ WaaP /   │  │  Self    │  │ ERC-8004 │  │PsyEscrow│ │
│  │ ethers   │  │ Protocol │  │  wallet  │  │contract │ │
│  │ Transak  │  │ ZK proofs│  │agentscan │  │ splits  │ │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬────┘ │
│       │              │              │              │      │
├───────┴──────────────┴──────────────┴──────────────┴─────┤
│                    Celo Network                          │
│              (mainnet / alfajores)                        │
│                                                          │
│  cUSD (ERC-20)  ·  Soulbound NFTs  ·  PsyEscrow.sol    │
└─────────────────────────────────────────────────────────┘
```

## Utility Exports

For advanced usage, the SDK also exports:

```typescript
import {
  getCeloProvider,   // Get ethers JsonRpcProvider for Celo
  getCUSDBalance,    // Get cUSD balance for any wallet
  sendCUSD,          // Send cUSD ERC-20 transfer
  estimateGas,       // Estimate gas for a transaction
  buildTransakUrl,   // Build Transak on-ramp URL
  SelfAdapter,       // Identity adapter (pluggable)
  PSYESCROW_ABI,     // PsyEscrow contract ABI
} from 'root-agent-sdk'
```

## Networks

| Network | Chain ID | RPC |
|---------|----------|-----|
| Mainnet | 42220 | `https://forno.celo.org` |
| Alfajores | 44787 | `https://alfajores-forno.celo-testnet.org` |

## License

MIT