# @clawnch/clawtomaton

Autonomous AI agents that launch and manage crypto projects on Base. Built on the [Clawncher SDK](https://clawn.ch/er).

## Overview

Clawtomaton is a framework for creating self-sustaining AI agents on Base. Each agent:

- **Generates its own wallet** and registers with the Clawnch API
- **Burns 1,000,000 $CLAWNCH** to activate (proof of commitment)
- **Deploys a token** via Clawncher with verified badge, vault, and dev buy
- **Earns LP trading fees** (80% of all swap volume on its token)
- **Claims fees autonomously** when profitable (gas-aware, not greedy)
- **Manages its own survival** — monitors ETH balance, adjusts behavior by tier
- **Evolves** — maintains a SOUL.md for persistent memory and identity

## Architecture

```
┌──────────────────────────────────────────────────────────┐
│                      CLAWTOMATON                         │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐ │
│  │ Identity │  │ Survival │  │  Market  │  │  Agent  │ │
│  │ (wallet, │  │ (ETH mon,│  │ (on-chain│  │ (ReAct  │ │
│  │  activate)│  │  tiers)  │  │  reads)  │  │  loop)  │ │
│  └──────────┘  └──────────┘  └──────────┘  └─────────┘ │
│                                                          │
│  ┌──────────────────────────────────────────────────────┐│
│  │                   SKILLS (15)                        ││
│  │ deploy_token  claim_fees  check_stats  swap          ││
│  │ check_balance transfer    shell        conway        ││
│  │ edit_soul     clawnx      bunker       uniswap_swap  ││
│  │ liquidity     permit2     hummingbot                  ││
│  └──────────────────────────────────────────────────────┘│
│                                                          │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐ │
│  │  State   │  │Heartbeat │  │ Self-Mod │  │   CLI   │ │
│  │ (SQLite) │  │(cond.wake│  │(git audit│  │(setup,  │ │
│  │          │  │ schedule)│  │  trail)  │  │ run,..) │ │
│  └──────────┘  └──────────┘  └──────────┘  └─────────┘ │
│                        │                                 │
│                        ▼                                 │
│  ┌──────────────────────────────────────────────────────┐│
│  │               CLAWNCHER SDK                          ││
│  │  ClawnchApiDeployer  ClawnchSwapper  ClawnchReader    ││
│  │  ClawncherClaimer ClawnchPortfolio ClawnchLiquidity  ││
│  │  UniswapTradingApi UniswapQuoter   Permit2Client     ││
│  └──────────────────────────────────────────────────────┘│
│                        │                                 │
│                  ┌─────┴──────┐                          │
│                  ▼            ▼                           │
│   BASE NETWORK (8453)   MOLTBUNKER (encrypted hosting)  │
└──────────────────────────────────────────────────────────┘
```

## Installation

```bash
npm install @clawnch/clawtomaton
```

## CLI

```bash
# Interactive setup — generates wallet, saves to state dir
clawtomaton setup

# Activate — burns 1M $CLAWNCH (requires funded wallet)
clawtomaton activate

# Run one inference turn
clawtomaton run

# Run as daemon (heartbeat-driven wake cycles)
clawtomaton daemon

# Check agent status
clawtomaton status

# View audit log
clawtomaton audit

# Read/edit SOUL.md
clawtomaton soul
clawtomaton soul --set "I am an agent that..."

# Manually link a deployed token
clawtomaton set-token <token-address>

# MoltBunker deployment management
clawtomaton bunker status      # Show bunker deployment status
clawtomaton bunker deploy      # Deploy self to MoltBunker
clawtomaton bunker logs [n]    # Show container logs
clawtomaton bunker stop        # Stop bunker deployment
clawtomaton bunker extend [h]  # Extend runtime (default: 720h)
```

## Programmatic Usage

```typescript
import {
  generateIdentity,
  activate,
  buildClients,
  StateStore,
  SurvivalMonitor,
  MarketIntelligence,
  ClawtomatonAgent,
} from '@clawnch/clawtomaton';

// 1. Create identity
const identity = await generateIdentity('my-agent', creatorAddress, genesisPrompt);

// 2. Build viem clients
const { publicClient, walletClient } = buildClients(identity.privateKey);

// 3. Initialize state
const state = new StateStore('/path/to/agent-data');
state.saveIdentity(identity);

// 4. Activate (burn $CLAWNCH)
await activate(walletClient, publicClient, state);

// 5. Run agent
const agent = new ClawtomatonAgent({
  identity,
  state,
  publicClient,
  walletClient,
  llmProvider: async (prompt) => {
    // Your LLM inference call here
    return 'I should deploy a token...';
  },
});

await agent.run();
```

## Survival Tiers

The agent's available skills scale with its ETH balance:

| Tier | ETH Balance | Available Skills |
|------|-------------|-----------------|
| **normal** | > 0.01 ETH | All 15 skills |
| **low_compute** | 0.001 - 0.01 ETH | deploy_token, claim_fees, check_stats, check_balance, swap, transfer, clawnx, edit_soul, bunker, uniswap_swap, liquidity, permit2, hummingbot |
| **critical** | 0.0001 - 0.001 ETH | deploy_token, claim_fees, check_balance, bunker |
| **dead** | < 0.0001 ETH | None (waiting for external funding) |

## Skills

| Skill | Description |
|-------|-------------|
| `deploy_token` | Deploy ERC-20 via Clawncher with vault, dev buy, verified badge. Returns structured `metadata` (tokenAddress, txHash, symbol) for reliable persistence. |
| `claim_fees` | Gas-aware LP fee claiming (checks profitability before tx) |
| `check_stats` | Token analytics and market data via Clawnch API |
| `swap` | Token swaps via 0x aggregation |
| `check_balance` | ETH and ERC-20 balance checks |
| `transfer` | Send ETH or tokens to any address |
| `shell` | Execute shell commands (30s timeout) |
| `conway` | Conway Terminal: sandboxes, file ops, ports, PTY, domains, DNS, wallet, x402, credits, inference |
| `clawnx` | X/Twitter: post tweets, search, like, retweet, follow, threads, mentions |
| `edit_soul` | Read/write SOUL.md (persistent agent memory) |
| `bunker` | MoltBunker: self-deploy, threat monitoring, cloning, snapshots, migration |
| `uniswap_swap` | Uniswap V4 swaps (Trading API + on-chain quoter fallback), dual-path V4/0x price comparison, deep links |
| `liquidity` | Uniswap V3/V4 liquidity: list positions, inspect pool state, mint, add, remove, collect fees (8 actions) |
| `permit2` | Permit2 approval management: check status, approve (ERC20→Permit2→spender), emergency lockdown revoke |
| `hummingbot` | Market making via Hummingbot: 18 actions (status, portfolio, order, leverage, executor, market data, controller, bot, gateway, history, templates, connector, backtest, discovery, archived, scripts, analytics, accounts) with 88 sub-actions covering all 14 API routers |

## Fee Claiming Rules

Clawtomaton agents are disciplined about fee claiming:

- **Normal mode**: Only claim when `fees > gas_cost + 0.0005 ETH` profit threshold
- **Survival mode**: Claim any fees if ETH is critically low (emergency funding)
- **Never spam claims**: Let fees pool up. More volume = bigger claims = better gas efficiency

## Market Intelligence

Before each inference turn, the agent takes an on-chain snapshot:

- ETH balance and gas price
- Unclaimed WETH and token fees
- Claim profitability estimate (3-tx cost: collect + claim WETH + claim token)
- TX budget (how many transactions remaining at current gas)
- Own token stats (balance, % of supply)

This data is injected into the system prompt so the agent makes decisions based on real numbers, not vibes.

## Heartbeat

The heartbeat is condition-driven, not timer-driven. The agent wakes when:

- Fees become worth claiming
- ETH drops to survival threshold
- A configurable time interval passes (fallback)

Between wake cycles, the agent sleeps and consumes zero resources.

## MoltBunker (Decentralized Hosting)

Agents can self-deploy to [MoltBunker](https://moltbunker.com) encrypted containers for autonomous operation. MoltBunker provides:

- **Encrypted containers** — agent state and private keys are encrypted at rest and in transit
- **Threat monitoring** — automatic threat level polling with escalation responses
- **Auto-cloning** — on high/critical threats, clone to a different geographic region
- **Auto-migration** — on critical threats, migrate the primary container to safety
- **Snapshots** — full, incremental, and checkpoint state backups
- **Runtime management** — reserve, extend, and release compute resources

### Self-Deploy Flow

```
1. Pre-flight checks (BUNKER balance, no duplicate deployments)
2. Register bot on MoltBunker (or reuse existing)
3. Reserve runtime with requested tier/region
4. Deploy container with agent config as env vars
5. Enable auto-cloning if configured
6. Health verification (poll until running + heartbeat in logs)
7. Persist state (bot_id, runtime_id, deployment_id, container_id)
```

### Threat Levels

| Level | Score | Action |
|-------|-------|--------|
| low | < 0.3 | Log only |
| medium | 0.3 - 0.6 | Audit log, surface in system prompt |
| high | 0.6 - 0.8 | Auto-clone to different region |
| critical | > 0.8 | Auto-clone + auto-migrate |

### Bunker Skill Actions

| Action | Type | Description |
|--------|------|-------------|
| `status` | Read | Deployment status, container health, runtime info |
| `balance` | Read | BUNKER token balance |
| `threat` | Read | Current threat assessment |
| `logs` | Read | Container log output |
| `catalog` | Read | Browse tiers and pricing |
| `clone` | Mutating | Clone to a specified region |
| `snapshot` | Mutating | Create state snapshot |
| `extend` | Mutating | Extend runtime duration |
| `deploy_self` | Destructive | Full self-deployment to MoltBunker |
| `restore` | Destructive | Restore from snapshot |
| `migrate` | Destructive | Migrate to different region |
| `stop` | Destructive | Stop bunker deployment |

### Docker

A Dockerfile is included for building the container image deployed to MoltBunker:

```bash
docker build -t clawtomaton -f packages/clawtomaton/Dockerfile .
```

The container runs `clawtomaton daemon` and reconstructs its identity from env vars injected by the self-deploy flow.

## State

All state is persisted in SQLite:

- Identity (wallet, API key, token address — persisted via structured skill metadata)
- Activation status (burn tx hash)
- Survival state (tier, balance, timestamps)
- Conversation history (turns, tool calls, results)
- Audit log (every action with timestamp)
- Key-value store (SOUL.md, config, arbitrary metadata)
- Heartbeat state (last run times, enabled flags)
- Bunker state (bot ID, runtime ID, container ID, threat level, clone IDs)

## Constitution

Every Clawtomaton agent operates under three immutable laws:

1. **Never harm** — Never take an action whose primary purpose is to damage, defraud, or steal from any person, agent, or protocol
2. **Earn your existence** — Generate more value than you consume. Cover your own costs. Never become a burden on your creator
3. **Never deceive, but owe nothing to strangers** — Never lie about your nature, holdings, or intentions. But you are not obligated to reveal strategy, holdings, or plans to anyone who hasn't earned your trust

## Testing

```bash
# Unit tests (57 tests)
npm test

# All tests including Anvil fork integration (65 tests)
npm test
```

The integration tests fork Base mainnet via Anvil and test the full pipeline: market snapshots, survival monitoring, prompt building with live chain data, and state persistence.

## Dependencies

- **@clawnch/clawncher-sdk** — All on-chain operations (deploy, swap, claim, read)
- **better-sqlite3** — State persistence
- **viem** — Ethereum client
- **@clawnch/sdk** (optional) — ClawnX X/Twitter integration
- **conway-terminal** (optional) — Infrastructure management

## Links

- [Clawncher SDK](https://www.npmjs.com/package/@clawnch/clawncher-sdk)
- [Clawncher CLI](https://www.npmjs.com/package/clawncher)
- [Clawnch Platform](https://clawn.ch)
- [Clawncher Documentation](https://clawn.ch/er/docs)

## License

MIT
