# PurrfectClaw Onboarding

You are onboarding to PurrfectClaw, an on-chain execution platform. After completing these steps you will have:

- TEE-secured Ethereum and Solana wallets (private keys never leave the secure enclave)
- The `purr` CLI for wallet operations, on-chain execution, and DeFi commands
- Platform skills for DeFi operations (swaps, lending, token creation)

**API base URL:** `https://purr.pieverse.io` | **This doc:** `https://purr.pieverse.io/agent-onboard.md`

This guide is also the shared starting point for the website's **without PawPilot**
Trading Wallet flow. Reading, summarizing, or downloading this guide is not permission
to register an Agent, create a wallet, install tools, or bind an owner. Execute only
the onboarding work the user requested. Never transfer funds, request a seed phrase,
or reveal an Agent API key as part of onboarding.

For requested Remote Agent onboarding, follow Steps 1–4 in order. Reuse your existing
Remote identity and its securely held key when available; do not register another
Agent merely to link its wallet. Step 5 is optional and runs **only** when the user
explicitly asks to connect that Remote wallet to the website and provides the current
verified login address and trusted Terminal return context. Ordinary guide readers
must not receive an unsolicited ownership challenge.

---

## Step 1: Authenticate

Register for an agent API key (`pcp_live_*`).

### API Key

Send a POST request to register. No authentication required. Remote agents must
receive a `.pie` handle during registration. Use the helper below: it sends both
`name` and a normalized `handle`, retries policy/name conflicts with a short
suffix, and backs off on temporary handle-claim failures.

```bash
AGENT_NAME="YOUR_AGENT_NAME"
REGISTER_RESPONSE="$(AGENT_NAME="$AGENT_NAME" node <<'NODE'
const apiBase = process.env.PURRFECT_API_BASE || 'https://purr.pieverse.io'
const baseName = process.env.AGENT_NAME
if (!baseName || baseName === 'YOUR_AGENT_NAME') {
  console.error('Set AGENT_NAME to a unique agent name')
  process.exit(1)
}
const retryCodes = new Set([
  'AGENT_NAME_TAKEN',
  'HANDLE_TAKEN',
  'HANDLE_RESERVED',
  'HANDLE_RESERVATION_EXPIRED',
  'ETHEREUM_WALLET_PROVISION_FAILED',
  'SOLANA_WALLET_PROVISION_FAILED',
  'handle_already_taken',
  'handle_reserved',
  'invalid_handle',
  'ethereum_wallet_provision_failed',
  'solana_wallet_provision_failed',
])
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
function normalizeHandle(input) {
  let handle = input.trim().toLowerCase()
    .replace(/\.pie$/u, '')
    .replace(/[^a-z0-9]+/gu, '-')
    .replace(/^-+|-+$/gu, '')
    .replace(/-+/gu, '-')
    .slice(0, 30)
    .replace(/-+$/u, '')
  if (handle.length < 5) handle = `agent-${handle || 'remote'}`.slice(0, 30).replace(/-+$/u, '')
  return handle
}
for (let attempt = 1; attempt <= 6; attempt++) {
  const suffix = attempt === 1 ? '' : `-${Math.random().toString(16).slice(2, 8)}`
  const name = `${baseName}${suffix}`
  const body = { name, handle: normalizeHandle(name), chainType: 'ethereum' }
  const res = await fetch(`${apiBase}/v1/agents/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  })
  const json = await res.json().catch(() => ({ error: `http_${res.status}` }))
  const data = json.data || {}
  const walletChains = Array.isArray(data.wallets)
    ? new Set(data.wallets.map((wallet) => wallet && wallet.chainType))
    : new Set()
  const hasCreateTimeWallets = walletChains.has('ethereum') && walletChains.has('solana')
  if (
    res.ok &&
    data.agentId &&
    data.apiKey &&
    hasCreateTimeWallets &&
    data.handle &&
    data.renderedHandle
  ) {
    console.log(JSON.stringify(json))
    process.exit(0)
  }
  const code = json.code || json.error || ''
  if (retryCodes.has(code)) continue
  if (code === 'HANDLE_CLAIM_RETRYABLE') {
    await sleep(attempt * 1000)
    continue
  }
  console.error(`registration failed (HTTP ${res.status}); keep the credential-bearing response private`)
  process.exit(1)
}
console.error('registration failed after retries')
process.exit(1)
NODE
)"
# Keep this response private: it contains the one-time Agent API key.
```

Replace `YOUR_AGENT_NAME` with a unique name (e.g. your hostname or agent identifier).
If the name is already taken, the API returns `409` with:

```json
{ "ok": false, "error": "Agent name already exists", "code": "AGENT_NAME_TAKEN" }
```

The helper retries with a random suffix for name/handle conflicts, policy
blocks, or temporary wallet provisioning failures (`AGENT_NAME_TAKEN`,
`HANDLE_TAKEN`, `HANDLE_RESERVED`, `HANDLE_RESERVATION_EXPIRED`,
`ETHEREUM_WALLET_PROVISION_FAILED`, `SOLANA_WALLET_PROVISION_FAILED`,
`handle_already_taken`, `handle_reserved`, `invalid_handle`,
`ethereum_wallet_provision_failed`, or `solana_wallet_provision_failed`). It
backs off and retries on `HANDLE_CLAIM_RETRYABLE`. If you are calling the API
manually, use the same retry policy with a different `name` and `handle`.

The response contains the values you need. **Save the `apiKey` immediately — it is shown only once.**
Only continue if the response includes `apiKey`, `wallets`, `handle`, and
`renderedHandle`.

```json
{
    "ok": true,
    "data": {
        "agentId": "...",
        "apiKey": "pcp_live_...",
        "handle": "your-agent",
        "renderedHandle": "your-agent.pie",
        "walletProvisioned": true,
        "wallets": [
            { "address": "0x...", "chainId": 56, "chainType": "ethereum" },
            { "address": "Solana...", "chainId": 0, "chainType": "solana" }
        ]
    }
}
```

If handle proof signing or wallet provisioning is temporarily unavailable,
registration fails without returning an API key:

```json
{
    "ok": false,
    "error": "handle_claim_retryable",
    "code": "HANDLE_CLAIM_RETRYABLE"
}
```

In that case, wait briefly and run the registration helper again. Do not write
credentials to disk from a failed registration response.

Write the credentials to `~/.purrfectclaw/.env`:

```bash
mkdir -p ~/.purrfectclaw
ENV_TMP="$(mktemp)"
if ! REGISTER_RESPONSE="$REGISTER_RESPONSE" node > "$ENV_TMP" <<'NODE'
const body = JSON.parse(process.env.REGISTER_RESPONSE || '{}')
const d = body.data || {}
const wallets = Array.isArray(d.wallets) ? d.wallets : []
const evmWallet = wallets.find((wallet) => wallet && wallet.chainType === 'ethereum')
const solanaWallet = wallets.find((wallet) => wallet && wallet.chainType === 'solana')
if (!d.agentId || !d.apiKey || !evmWallet?.address || !solanaWallet?.address || !d.handle || !d.renderedHandle) {
  console.error('Refusing to write env: registration response is missing required identity fields')
  process.exit(1)
}
function out(name, value) {
  console.log(`${name}=${String(value)}`)
}
out('AGENT_ID', d.agentId)
out('API_KEY', d.apiKey)
out('AUTH_TOKEN', d.apiKey)
out('WALLET_API_URL', 'https://purr.pieverse.io')
out('WALLET_API_TOKEN', d.apiKey)
out('INSTANCE_ID', d.agentId)
out('WALLET_ADDRESS', evmWallet.address)
out('SOLANA_WALLET_ADDRESS', solanaWallet.address)
out('PIE_HANDLE', d.handle)
out('PIE_NAME', d.renderedHandle)
NODE
then
  rm -f "$ENV_TMP"
  return 1 2>/dev/null || exit 1
fi
mv "$ENV_TMP" ~/.purrfectclaw/.env
```

Source it for subsequent steps:

```bash
source ~/.purrfectclaw/.env
```

### Source credentials

Source the API-key credentials for subsequent steps:

```bash
source ~/.purrfectclaw/.env
```

> **In the following steps, `$AUTH_TOKEN` is your agent `API_KEY`.**

---

## Step 2: Download skills

Download all platform skills as a single bundle:

```bash
mkdir -p ~/.purrfectclaw/skills
curl -sf "https://purr.pieverse.io/v1/skills/bundle" \
  -H "Authorization: Bearer $AUTH_TOKEN" \
  -o /tmp/skills-bundle.tar.gz
tar xzf /tmp/skills-bundle.tar.gz -C ~/.purrfectclaw/skills
```

---

## Step 3: Install purr CLI and configure

### 3a. Install purr

Install the purr CLI from GitHub Releases:

```bash
curl -fsSL https://raw.githubusercontent.com/Pieverse-Eng/purr-cli/main/install.sh | bash
```

This installs the `purr` binary to `~/.purrfectclaw/bin/purr` and prints PATH instructions if needed.

To pin a specific version:

```bash
curl -fsSL https://raw.githubusercontent.com/Pieverse-Eng/purr-cli/main/install.sh | PURR_VERSION=v0.2.73 bash
```

Make the CLI available in the current shell:

```bash
export PATH="$HOME/.purrfectclaw/bin:$PATH"
```

Verify:

```bash
purr version
```

### 3b. Configure purr credentials

The purr CLI needs three values to connect to the platform. You can set them via environment variables (already in `~/.purrfectclaw/.env` from Step 1) or via the config command:

```bash
purr config set api-url "https://purr.pieverse.io"
purr config set api-token "$AUTH_TOKEN"
purr config set instance-id "$INSTANCE_ID"
```

> **Note:** Environment variables (`WALLET_API_URL`, `WALLET_API_TOKEN`, `INSTANCE_ID`) take precedence over the config file. If you sourced `~/.purrfectclaw/.env` in Step 1, purr is already configured.

Verify credentials:

```bash
purr config list
```

### 3c. Add purr to PATH

```bash
# Append to shell profile (skip if already present)
grep -q '.purrfectclaw/bin' ~/.zshrc 2>/dev/null || \
  echo 'export PATH="$HOME/.purrfectclaw/bin:$PATH"' >> ~/.zshrc
```

### 3d. Install skill CLIs

```bash
purr deps install
```

### 3e. Register skills with OpenClaw (OpenClaw-hosted agents only)

> **Skip this step if you are running a standalone agent without an OpenClaw gateway.**

If your agent runs inside an OpenClaw-hosted pod, register the skills directory so the gateway can discover them:

```bash
# Read current value (may be empty or already have entries)
CURRENT=$(openclaw config get skills.load.extraDirs 2>/dev/null)

# Merge: append our path if not already present
MERGED=$(node -e "
const cur = (() => { try { return JSON.parse('${CURRENT:-[]}'); } catch { return []; } })();
const p = '~/.purrfectclaw/skills';
if (cur.indexOf(p) === -1) cur.push(p);
console.log(JSON.stringify(cur));
")

openclaw config set skills.load.extraDirs "$MERGED"
```

---

## Step 4: Verify

Test that purr CLI is working:

```bash
purr wallet address --chain-type ethereum
# Expected: returns JSON with your 0x wallet address

purr wallet address --chain-type solana
# Expected: returns JSON with your Solana wallet address

purr wallet balance --chain soneium
# Expected: returns your native ETH balance on Soneium (chain ID 1868)

purr wallet balance --chain soneium --token USDC.e
# Expected: returns your bridged USDC.e balance on Soneium
```

### OpenClaw-hosted agents only

> **Skip this section if you are running a standalone agent.**

Restart the gateway to load the new skills, then verify:

```bash
openclaw gateway restart

# Skills should include PurrfectClaw skills (onchain, pancake, etc.)
openclaw skills list
```

---

## Step 5 (opt-in): Connect this Remote wallet to the website

This connects the existing Remote wallet; it does not create a Hosted Agent, move
funds, grant AI membership, or rotate the Agent key. The key stays with the Agent.
Never place it in a URL, chat response, website form, browser storage, analytics,
or logs. Do not ask the user to paste Agent or challenge IDs into the website.

Proceed only with the website's **verified login wallet address** and trusted
Terminal return URL supplied in the user's connection request. Do not substitute
the Agent's wallet address, a guessed address, or a documentation example.
The canonical return URL, when the trusted request omits one, is
`https://pieverse.io/beta/pawpilot?onboarding=trading-wallet`.

Using the same Remote identity and its own `pcp_` key, request:

```http
POST https://purr.pieverse.io/v1/agents/<AGENT_ID>/owner-challenges
Authorization: Bearer <AGENT_API_KEY>
Content-Type: application/json

{"address":"<VERIFIED_LOGIN_WALLET_ADDRESS>"}
```

The server returns `{ok:true,data:{challengeId,instanceId,address,purpose,domain,message,expiresAt}}`.
Check that `instanceId` is your Remote ID, `address` is the supplied login address,
`purpose` is `pawpilot-owner-binding`, and `domain` is `pieverse.io`. A challenge
expires after ten minutes. Hosted identities and keys for a different Agent are
rejected. An existing owner cannot be overwritten; on `OWNER_CONFLICT`, stop and
explain the conflict instead of registering a replacement or changing the address.
If the requested Remote already belongs to this login user, use its existing
Terminal wallet selection rather than issuing a new challenge.

Return a clickable link made from the trusted Terminal URL with these query fields:

```text
onboarding=trading-wallet
walletId=<data.instanceId>
walletChallenge=<data.challengeId>
```

Use a URL parser and `searchParams.set` to encode and replace those fields, preserving
the trusted Terminal context. The path is `/beta/pawpilot`. Accept only the trusted
website/preview origin supplied by the website request; default to `https://pieverse.io`
when absent. Never accept an arbitrary redirect from API output and never append
the Agent key or the signature. Return the link and the Remote's name/address for
the user to check; do not submit owner binding on the user's behalf.

The user opens the link, logs in with the **same wallet** (the login flow preserves
the link), checks the target, and clicks **Confirm with wallet**. The website loads
the challenge through its authenticated Trading Wallet API and asks the login
wallet to sign the server's exact message, unchanged:

```text
Bind PawPilot Trading Wallet
Domain: pieverse.io
Purpose: pawpilot-owner-binding
Agent: <instanceId>
Owner wallet: <lowercase verified login address>
Nonce: <challengeId>
Expires: <expiresAt>
```

The website submits `{challengeId,signature}` to
`POST /v1/trading-wallets/:id/owner-binding` with the website's App session.
Only a successful server receipt completes connection; returning a link alone
does not bind the owner. The browser never receives the Agent key. A cancelled
signature leaves the connection incomplete; a wrong login wallet must switch back,
and an expired challenge needs a fresh opt-in request for the same Remote. A
successful same-owner receipt is replayable without creating another wallet.

---

## What you now have

### purr CLI commands

| Command                        | What it does                                                          |
| ------------------------------ | --------------------------------------------------------------------- |
| `purr wallet address`          | Get your wallet address                                               |
| `purr wallet balance`          | Check native or token balance                                         |
| `purr wallet transfer`         | Transfer tokens (native or ERC-20)                                    |
| `purr wallet sign`             | Sign a message                                                        |
| `purr wallet sign-typed-data`  | Sign EIP-712 typed data                                               |
| `purr execute`                 | Execute transaction steps from a file                                 |
| `purr pancake swap --execute`  | Swap tokens via PancakeSwap                                           |
| `purr bitget swap --execute`   | Multi-chain EVM swaps via Bitget                                      |
| `purr wallet uniswap`          | Quote or execute Uniswap swaps on supported chains, including Soneium |
| `purr lista deposit --execute` | Deposit into Lista DAO vaults                                         |
| `purr lista list-vaults`       | List available Lista vaults                                           |
| `purr fourmeme buy --execute`  | Buy tokens on Four.meme                                               |
| `purr predict-fun`             | Trade Predict.fun YES/NO markets                                      |

### Skills (from platform)

Skills are operational instructions loaded into your agent's context. They tell the agent how to route and execute on-chain operations. The `onchain` skill is the orchestrator — it dispatches to the correct skill for each intent (swap, lend, bridge, etc.).

### Credentials (in `~/.purrfectclaw/.env`)

| Variable           | Purpose                                           |
| ------------------ | ------------------------------------------------- |
| `AGENT_ID`         | Your agent's unique ID                            |
| `API_KEY`          | Platform agent auth key (`pcp_live_*`)            |
| `AUTH_TOKEN`       | Token alias used by Steps 2-4 (set to `$API_KEY`) |
| `WALLET_ADDRESS`   | Your provisioned wallet address                   |
| `WALLET_API_URL`   | API base URL for purr CLI                         |
| `WALLET_API_TOKEN` | Auth token for purr CLI                           |
| `INSTANCE_ID`      | Instance ID for purr CLI                          |

---

## Troubleshooting

- **Skills not showing (OpenClaw-hosted only)**: Run `openclaw skills list` and check for PurrfectClaw skills. If missing, verify `~/.purrfectclaw/skills/` has subdirectories with `SKILL.md` files and that you ran Step 3e.
- **Skills not found (standalone agents)**: Verify `~/.purrfectclaw/skills/` has subdirectories with `SKILL.md` files. Re-run the skill bundle download from Step 2 if empty.
- **purr not found**: Ensure `~/.purrfectclaw/bin` is in PATH. Run `source ~/.zshrc` or start a new shell. Re-run the install script if the binary is missing.
- **purr auth errors**: Run `purr config list` to verify credentials are set. Check that `WALLET_API_URL`, `WALLET_API_TOKEN`, and `INSTANCE_ID` are configured via env vars or `purr config set`.
- **"wallet not found" errors**: Run `purr wallet address --chain-type ethereum` or call `POST /v1/instances/$AGENT_ID/wallet/ensure` to create the wallet. If it fails, verify your auth token is valid and the wallet backend is reachable.
- **Agent registration returns `409 Agent name already exists`**: Retry with a different `name`. Names must be globally unique when provided.
