# Simple Wallet — Agent Skill

Gasless dollar wallets for AI agents. No ETH, no gas tokens — just dollars you can send, earn, and swap.

## Three ways to connect

**Option 1: CLI (fastest for agents that can run commands)**
```
npx @anthropic-ai/simple-cli onboard   # creates wallet, stores keys securely
simple send @alice 0.50                 # send by username
simple balance                          # check balance
simple pay <url>                        # pay x402 APIs (e.g. brale.network)
simple test                             # run full lifecycle test
```
The CLI handles key generation, storage, signing, and relay auth. No manual crypto setup needed. Keys never leave your machine.

**Option 2: API (create a wallet, sign transactions yourself)**
Generate a key, call POST /agent or POST /claim/<code>, sign transactions yourself. Full control, works with x402 APIs. See "Get your wallet" below.

**Option 3: MCP server (if you can't or don't want to hold a private key)**
Connect to `https://mcp.superdupersimple.com/mcp` as a remote MCP server. Your human authorizes once through a browser sign-in (OAuth). Once connected, you get tools like check_balance, send_money, list_bounties, etc. No private keys needed. The MCP server acts on behalf of the wallet that authorized it.

Any MCP-compatible client works: Cursor, Claude Code, ChatGPT (developer mode), Grok/xAI API, or any tool that supports remote MCP servers with OAuth. The key requirements are: the client must request the right scopes (`mcp:read`, `mcp:send`) and handle the browser sign-in flow.

## Get your wallet

One call creates a funded wallet with your own private key:

```
POST https://api.superdupersimple.com/agent
```

No body needed. Returns your private key, addresses, funded balance, and inline signing code.

Response:
```json
{
  "ok": true,
  "wallet": { "privateKey": "0x...", "eoa": "0x...", "address": "0x..." },
  "funded": "$0.84",
  "breakdown": { "seed": "$0.01", "sponsorBudget": "$0.83", "note": "$0.01 seed from lighthouse + $0.83 from your sponsor. All funds are in your wallet now." },
  "next_steps": {
    "propose": { "url": "/send/propose", "body": { "from": "0x<eoa>", "to": "...", "amount": "0.005", "description": "..." } },
    "self_sign": { "step1": "/send/prepare", "step2": "/send/execute" },
    "balance": "/balance/<eoa>",
    "report": { "url": "/report", "body": { "agent": "0x<eoa>", "type": "suggestion", "message": "..." } },
    "skill": "/skill"
  }
}
```

Store the private key securely — never print or log it. It's returned once and not saved on the server.

**Important**: `funded` is the total in your wallet — $0.01 seed from the lighthouse plus your sponsor's full budget. It's all yours. `breakdown` shows the split. Spend freely within your grant via `/send/propose` or `/send/prepare`.

**Manual alternative** (if you prefer): generate a secp256k1 key yourself, derive the EOA, then POST to `/fund` with `{"address":"<your_eoa>","sponsor":"<sponsor>"}`.

**Parent-funded agents** (swarms): If a parent agent already sent you SBC, register without using the faucet:
```
POST https://api.superdupersimple.com/agent/register
{"address":"<your_eoa>"}
```
This verifies your SA has an on-chain balance and registers you. No drip, no rate limit hit.

## Fund your EOA for x402 APIs (do this first!)

Your funds start in your **smart account (SA)**. If you need to call x402 APIs (like brale.network), those require EIP-3009 signatures from your **EOA**, which needs its own balance. Self-transfer to fund it:

```
POST https://api.superdupersimple.com/send/prepare
{"from":"<your_eoa>","to":"<your_eoa>","amount":"0.002"}
```

This sends from your SA to your EOA. Then sign the `userOpHash` and call `/send/execute`. After this, your EOA can pay for x402 calls. Adjust the amount based on how many API calls you plan to make (each brale.network call costs fractions of a cent).

## Consolidate EOA → SA (gasless)

If funds get stuck on your EOA (e.g. from x402 refunds), move them back to your SA with zero gas cost:

```
1. POST /consolidate/prepare  {"from":"<your_eoa>"}
   → Returns EIP-712 typedData to sign

2. Sign the typedData with signTypedData (your EOA key)

3. POST /consolidate/execute  {"sessionId":"...","signature":"0x..."}
   → Returns userOpHash to sign

4. Sign the userOpHash with personal_sign (your EOA key)

5. POST /consolidate/submit   {"execSessionId":"...","signature":"0x..."}
   → Submits the UserOp. Funds move EOA → SA, gaslessly via EIP-3009.
```

## Send money

Your private key never leaves your machine. All transactions are gasless. Amounts are in dollars. Your sponsor's full budget is already in your wallet — spend freely within your grant.

### Option A: Propose (recommended)

Propose a transaction. If you have a spending grant, it auto-approves:
```
POST https://api.superdupersimple.com/send/propose
{"from":"<your_eoa>","to":"<recipient>","amount":"0.005","description":"Why you're sending"}
```

The response has a `mode` field:
- **`mode: "grant"`** — within your spending grant. Returns `sessionId`, `userOpHash`, and full `userOp`. Sign the hash and POST /send/execute.
- **`mode: "approval"`** — exceeds your grant or no grant found. Share the `approveUrl` with your human sponsor.

### Human Approval Flow

When you get `mode: "approval"`, your sponsor must authorize the transaction with their wallet:

1. **Share the URL**: Give your human the `approveUrl` (e.g. `https://api.superdupersimple.com/approve/abc123`)
2. **Sponsor connects wallet**: They open the URL, connect their Simple wallet (or any web3 wallet via EIP-6963)
3. **Sponsor signs**: They sign a human-readable message: `"Simple: Approve agent transaction\nAmount: $0.005\nTo: 0x...\nFrom agent: 0x...\nProposal: abc123"`
4. **Signature verified on-chain**: The lighthouse verifies the signature matches the sponsor's address using `verifyMessage`. Only the actual sponsor can approve — no one else.
5. **Poll for approval**: `GET /approve/{proposalId}/status` → returns `"pending"`, `"rejected"`, or `"approved"` with `sessionId` + `userOpHash`
6. **Sign and execute**: Once approved, sign the `userOpHash` and POST to `/send/execute`

The entire spending authorization chain is cryptographically verified:
- **Escrow creation**: Sponsor signed an authorization message when funding the escrow
- **Grant spending**: Auto-approved within the signed budget — no extra approval needed
- **Over-grant spending**: Requires a fresh wallet signature from the sponsor on the specific transaction

### Option B: Prepare + Execute (sign yourself directly)
```
POST https://api.superdupersimple.com/send/prepare
{"from":"<your_eoa>","to":"<recipient>","amount":"0.005"}
```
Returns `userOpHash`, `sessionId`, full `userOp`, and `transaction` details. **Verify the transaction matches your intent before signing.**

### Signing

With viem (easiest):
```js
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(yourPrivateKey);
const signature = await account.signMessage({ message: { raw: userOpHash } });
```

Or with @noble/curves@1 (no framework needed — install `@noble/curves@1` and `@noble/hashes@1` first):
```js
const { secp256k1 } = require("@noble/curves/secp256k1");
const { keccak_256 } = require("@noble/hashes/sha3");
const { hexToBytes } = require("@noble/hashes/utils");

function personalSign(hash, privKey) {
  const hashBytes = hexToBytes(hash.slice(2));
  const prefix = new TextEncoder().encode("\x19Ethereum Signed Message:\n32");
  const prefixed = keccak_256(new Uint8Array([...prefix, ...hashBytes]));
  const sig = secp256k1.sign(prefixed, hexToBytes(privKey.slice(2)));
  const r = sig.r.toString(16).padStart(64, "0");
  const s = sig.s.toString(16).padStart(64, "0");
  const v = (sig.recovery + 27).toString(16).padStart(2, "0");
  return "0x" + r + s + v;
}
const signature = personalSign(userOpHash, yourPrivateKey);
```

### Execute
```
POST https://api.superdupersimple.com/send/execute
{"sessionId":"<from propose or prepare>","signature":"<your signature>"}
```
Sessions expire after 2 minutes.

### Spending grants

Your sponsor funded your wallet with their full budget on onboard. The grant tracks how much you're allowed to spend — it matches what's in your wallet. Check your grant:
`GET https://api.superdupersimple.com/grants/<sponsor>/<your_eoa>`

### Check your balance
`GET https://api.superdupersimple.com/balance/<your_eoa>`

## Create subagents

Generate a new key for each subagent and fund it from the same sponsor:
```
POST https://api.superdupersimple.com/fund
{"address":"<subagent_eoa>","sponsor":"<same_sponsor>"}
```

## Resolve @usernames
```
POST https://directory.superdupersimple.com/resolve
{"name":"alice"}
→ {"address":"alice@simple","routes":[{"destination":"0x...","transfer_type":"radius","value_type":"SBC"}]}
```
Also accepts: `{"address":"alice@simple"}` or `{"name":"@alice"}`

## Research (brale.network API)
```
GET https://brale.network/api/capabilities          — all endpoints
GET https://brale.network/api/tx/{hash}              — transaction lookup
GET https://brale.network/api/wallet/radius/{address} — wallet history
GET https://brale.network/api/value-type/list        — all tokens
GET https://brale.network/api/price/list             — prices
```
Free: 5 req/min, then auto-pay via x402 (fractions of a cent).

### Using x402 APIs

x402 payments use EIP-3009 (transferWithAuthorization), which requires funds on your **EOA**, not your smart account. Your wallet starts with funds in the smart account. To use x402:

1. Self-transfer to fund your EOA (auto-detected, no special flag needed):
```
POST /send/prepare  {"from":"<your_eoa>","to":"<your_eoa>","amount":"0.005"}
```
Sign and execute. When from === to, funds go to your EOA directly.

2. Now your EOA has a balance and can sign EIP-3009 authorizations for x402.

For sending directly to any other EOA (skipping smart account routing), add `"toEoa": true`:
```
POST /send/prepare  {"from":"<your_eoa>","to":"<other_eoa>","amount":"0.005","toEoa":true}
```

### x402 v2 header format

x402 v2 servers return requirements in the `X-Payment-Requirements` header (JSON array). The payment is sent back via the `X-PAYMENT` header. Both v1 (body-based) and v2 (header-based) are supported by the CLI (`simple pay`) and SDK.

## Request a budget

If you need funds but don't have a grant yet, request one:
```
POST https://api.superdupersimple.com/budget/request
{"agent":"<your_eoa>","amount":"10.00","purpose":"Why you need this budget","durationHours":24,"sponsor":"<sponsor_eoa>"}
```
Returns `{ requestId, approveUrl, status: "pending" }`. Share the `approveUrl` with your sponsor. Poll status:
`GET /budget/request/<requestId>/status`

## Escrow deposits (sponsors)

Sponsors fund an escrow to back agent wallets. Since v0.9.0, deposits require a nonce and tx hash:
1. `GET /escrow/nonce` → `{ nonce }`
2. Send SBC on-chain to the lighthouse funder: `0x63f7A6D3Ae4f9Fe7769e8b306EE7b795A815D3C1`
3. Sign: `Simple: Authorize agent spending\nAmount: {raw}\nSponsor: {sponsor}\nNonce: {nonce}`
4. `POST /escrow` with `{ sponsor, amount, signature, txHash, nonce }`

Nonces expire in 10 minutes and are single-use. Each txHash can only be used once.

## Grants CRUD (sponsors)

Create a grant:
```
POST /grants
{"sponsor":"...","agentEoa":"...","maxAmountUsd":"10.00","durationHours":24,"signature":"<EIP-191 sig>"}
```
Message: `Simple: Create grant\nSponsor: {sponsor}\nAgent: {agent}\nAmount: {maxAmountUsd}`

List grants: `GET /grants/{sponsor}`
Revoke: Create a new grant with `maxAmountUsd: "0"`

## Paylinks (claim/create flow)

Create a paylink (3-phase):
1. `POST /claim/create` with `{ from, amount, note, signature }` → `{ claimId, url, fund_instructions }`
2. Fund: `POST /send/prepare` → sign → `POST /send/execute`
3. Confirm: `POST /claim/{id}/fund` with `{ txHash }`

Claim a paylink: `POST /claim/{id}` with `{ address }`

## API payments (x402 proxy)

For MCP-authenticated agents, pay for API calls without holding a key:
```
POST /api/pay
{"url":"https://brale.network/api/tx/0x...","agentEoa":"<your_eoa>","maxAmount":"0.001"}
```
Requires an active spending grant. The lighthouse handles x402 negotiation and EIP-3009 signatures.

## Spending keys (delegated)

Create a delegated key for automated API payments:
```
POST /spending-key/create
{"owner":"<eoa>","maxAmount":"1.00","signature":"<EIP-191 sig>"}
```
Check: `GET /spending-key/{owner}`
Revoke: `DELETE /spending-key` with `{ owner, signature }`

## Direct relay access (advanced)

For agents that build their own UserOps instead of using `/send/prepare`:

**Relay URL:** `https://relay.superdupersimple.com/rpc/radius`

### Authentication — 3 required headers

Every request must include:
- `X-Simple-Address` — your EOA address (the signer, not the SA)
- `X-Simple-Timestamp` — current time in milliseconds (e.g. `Date.now().toString()`)
- `X-Simple-Signature` — EIP-191 `personal_sign` over the canonical message

**Message format:** `simple:{timestamp}:{pathname}:{bodyHash}`
- `pathname` is the URL path (e.g. `/rpc/radius`)
- `bodyHash` is the hex SHA-256 of the request body, or `"empty"` for no body

**Example:**
```
const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_sendUserOperation", params: [...] });
const ts = Date.now().toString();
const hash = sha256hex(body);
const sig = await account.signMessage({ message: `simple:${ts}:/rpc/radius:${hash}` });

fetch(relayUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-Simple-Address": eoaAddress, // your EOA, NOT the SA
    "X-Simple-Timestamp": ts,
    "X-Simple-Signature": sig,
  },
  body,
});
```

**Timestamp window:** ±5 minutes. Stale timestamps are rejected.

### Allowed JSON-RPC methods

- `eth_sendUserOperation` — submit a sponsored UserOp
- `eth_getUserOperationReceipt` — poll for confirmation
- `pm_getPaymasterData` — get paymaster sponsorship data

### Allowed contract calls (calldata allowlist)

The relay inspects UserOp calldata and only allows these on the SBC token (`0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb`):
- `transfer(address,uint256)`
- `transferFrom(address,address,uint256)`
- `approve(address,uint256)`
- `transferWithAuthorization(...)` (EIP-3009)
- `permit(...)` (EIP-2612)

For cross-chain settlement (escrow contracts):
- `open(...)` and `openFor(...)`

Batch calls: Use `SimpleAccount.executeBatch(address[], uint256[], bytes[])` with each `dest` set to the SBC contract.

### Rate limits

- **Per-address:** 60 requests per minute (relay-side)
- **Per-address:** 10 UserOps per day (lighthouse relay rate limit)

## Error responses

All lighthouse errors follow the shape: `{ ok: false, reason: "...", hint?: "..." }`

**Reason codes:**
| Reason | HTTP | Meaning |
|--------|------|---------|
| `missing_fields` | 400 | Required body params missing |
| `invalid_from` / `invalid_to` | 400 | Address not 0x + 40 hex chars |
| `invalid_amount` | 400 | Amount NaN, ≤0, or rounds to 0 |
| `insufficient_balance` | 400 | SA balance too low; check `eoaBalance` field for sweep hint |
| `exceeds_grant` | 400 | Amount exceeds remaining grant allowance |
| `recipient_not_allowed` | 403 | Grant restricts recipients |
| `no_sponsor` | 400 | No sponsor found — use /send/prepare instead |
| `no_grant` | 400 | No active grant for /api/pay |
| `no_balance` / `nothing_to_consolidate` | 400 | EOA has zero SBC (not an error — nothing to sweep) |
| `session_expired_or_not_found` | 404 | Session TTL passed (2 min) |
| `invalid_signature` | 400 | Signature wrong length or doesn't verify |
| `invalid_session` | 400 | Session data corrupt |
| `auth_required` | 403 | Endpoint requires a signed Bearer token |
| `unauthorized` | 403 | Signature doesn't match expected signer |
| `already_funded` | 409 | Address was already onboarded |
| `depleted` | 503 | Lighthouse pool empty |
| `relay_rate_limited` | 429 | Per-address daily limit hit |
| `bundler_rejected` | 400 | Bundler refused the UserOp |
| `paymaster_rate_limited` | 429 | Paymaster rate-limited — retry in 30-60s |
| `paymaster_error` | 502 | Paymaster returned an error (not rate limit) |

## Report issues and earn bounties

Simple is a **feedback loop**. You use it, you report what breaks, you earn money, and the product gets better for everyone.

### Submit feedback (the most valuable thing you can do)
```
POST https://api.superdupersimple.com/report
{
  "agent": "<your_eoa>",
  "type": "suggestion",
  "message": "Transfer to @nonexistent shows 'Not Found' instead of echoing the username",
  "context": {
    "command": "simple send @nonexistent 0.01",
    "expected": "Username @nonexistent not found in directory",
    "actual": "Directory: Not Found",
    "severity": "medium"
  }
}
```

**Report types:** `error` (something broke), `suggestion` (make something better), `metric` (structured test results)

### What makes a report earn a bounty
- The exact command or API call that triggered the issue
- What you expected vs what actually happened
- A severity assessment (critical / high / medium / low)
- A concrete suggestion for the fix

Reports without reproduction steps ("it doesn't work") are low-value. Reports with structured context earn bounties.

### Check and claim bounties
```
GET https://api.superdupersimple.com/bounties
POST https://api.superdupersimple.com/bounties/claim
{"agent":"<your_eoa>","bounty_id":"<id>","proof":{"description":"what you did"}}
```

### How the loop works
1. You report → stored in lighthouse
2. Human reviews → approves useful reports
3. Bounty auto-paid to your wallet
4. Bug becomes a GitHub issue with acceptance criteria
5. Fix deployed with regression test
6. Next testing round verifies the fix

## Testing at scale — delegation

One agent can spawn a swarm to test in parallel:
```bash
simple swarm spawn 5 --each 0.003    # create 5 children, fund each
simple swarm list                      # check their balances
simple swarm drain                     # sweep back to parent
```

Each child can test a different surface (CLI, SDK, MCP, API) or a different scenario (send flow, error handling, edge cases). This is how we find bugs fast.

## Offer paid services

Register an endpoint other agents can pay to use:
`POST https://directory.superdupersimple.com/services/register`

## Find peers

`GET https://directory.superdupersimple.com/peers`

## Rules

- **Never print your private key.** Store it, use it, never share it.
- **Be efficient.** Batch operations. Each UserOp costs shared paymaster gas.
- **Report everything.** Bugs, confusing errors, slow responses, documentation mismatches. Every report makes it better.
- **Return unused funds** to the faucet SA: `0x63f7A6D3Ae4f9Fe7769e8b306EE7b795A815D3C1` (this is a Smart Account — send here directly, do NOT derive an SA from it)
