> For the complete documentation index, see [llms.txt](https://docs.greenowl.money/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.greenowl.money/agent-and-tools/agent/owl_agent.md).

# owl-agent

## Overview

**Owl Agent** is an autonomous DeFi agent built as an OpenClaw skill, enabling AI-powered interactions with the Lendefi protocol through ERC-4337 smart wallets. The agent provides a conversational interface for wallet management, DeFi operations, and yield optimization on Base Sepolia.

The agent wraps two MCP servers to expose **23 curated tools** optimized for AI agent autonomy:

* **lendefi-mcp** — Lendefi protocol reads and transaction encoding (37 underlying tools)
* **owl-wallet-mcp** — Smart wallet factory operations (4 underlying tools)

**Key Features:**

* ERC-4337 UserOperation signing and submission via bundler relay
* Gas-sponsored transactions through WhitelistPaymaster
* Autonomous yield farming and position management
* Portfolio analysis and strategy recommendations
* Secure key management with GCP Secret Manager integration

***

## Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                          OWL-AGENT (OpenClaw Skill)                         │
├─────────────────────────────────────────────────────────────────────────────┤
│  WALLET (6)            │  DEFI (8)             │  YIELD/UTILITY (9)         │
│  ─────────────         │  ──────────           │  ─────────────────         │
│  • get_wallet_status   │  • deposit_liquidity  │  • get_market_overview     │
│  • deploy_wallet       │  • withdraw_liquidity │  • list_opportunities      │
│  • execute_transaction │  • get_my_liquidity   │  • find_best_yield         │
│  • get_balance         │  • create_position    │  • analyze_position        │
│  • transfer_erc20      │  • supply_collateral  │  • compare_markets         │
│  • approve_token       │  • borrow / repay     │  • suggest_strategy        │
│                        │  • get_my_positions   │  • get_transaction_status  │
│                        │                       │  • estimate_gas            │
│                        │                       │  • get_portfolio_summary   │
└─────────────────────────────────────────────────────────────────────────────┘
          │                       │                         │
          ▼                       ▼                         ▼
┌──────────────────┐   ┌──────────────────┐      ┌──────────────────┐
│  owl-wallet-mcp  │   │  lendefi-mcp     │      │  bundler-relay   │
│  (stdio)         │   │  (stdio)         │      │  (HTTP)          │
└──────────────────┘   └──────────────────┘      └──────────────────┘
          │                       │                         │
          └───────────────────────┴─────────────────────────┘
                                  │
                          ┌───────▼───────┐
                          │  Base Sepolia │
                          │  (ERC-4337)   │
                          └───────────────┘
```

### Component Flow

1. **OpenClaw Runtime** — Invokes agent tools via SKILL.md definition
2. **Owl Agent** — Routes requests to appropriate MCP server, signs UserOps with EOA private key
3. **MCP Servers** — Generate transaction calldata (lendefi-mcp) or query wallet state (owl-wallet-mcp)
4. **Bundler Relay** — Submits UserOperations to ERC-4337 bundler (API key protected)
5. **EntryPoint Contract** — Executes UserOps on-chain, validates signatures, invokes paymaster

***

## Tool Reference

### Wallet Management (6 tools)

| Tool                  | Description                                              | Parameters                   |
| --------------------- | -------------------------------------------------------- | ---------------------------- |
| `get_wallet_status`   | Check wallet deployment status, address, and ETH balance | None                         |
| `deploy_wallet`       | Deploy ERC-4337 smart wallet via CREATE2 factory         | None                         |
| `execute_transaction` | Send ETH from smart wallet                               | `to`, `amount`               |
| `get_balance`         | Get ETH and ERC-20 token balances                        | `token` (optional)           |
| `transfer_erc20`      | Transfer ERC-20 tokens                                   | `token`, `to`, `amount`      |
| `approve_token`       | Approve spender for ERC-20 tokens                        | `token`, `spender`, `amount` |

**Usage Pattern:**

```typescript
// Agent checks wallet status
await agent.get_wallet_status()
// → { deployed: false, address: "0x...", balance: "0 ETH" }

// Agent deploys wallet if needed
await agent.deploy_wallet()
// → { success: true, userOpHash: "0x...", walletAddress: "0x..." }

// Agent executes transaction
await agent.execute_transaction({ to: "0x...", amount: "0.01" })
// → { userOpHash: "0x..." }
```

***

### DeFi Operations (8 tools)

| Tool                 | Description                                 | Parameters                                                 |
| -------------------- | ------------------------------------------- | ---------------------------------------------------------- |
| `deposit_liquidity`  | Deposit tokens into Lendefi vault for yield | `market`, `amount`                                         |
| `withdraw_liquidity` | Withdraw tokens from vault                  | `market`, `amount`                                         |
| `get_my_liquidity`   | View vault position and accrued interest    | `market` (optional)                                        |
| `create_position`    | Open borrowing position with collateral     | `market`, `collateral`, `collateralAmount`, `borrowAmount` |
| `supply_collateral`  | Add collateral to existing position         | `positionId`, `amount`                                     |
| `borrow`             | Borrow additional tokens against position   | `positionId`, `amount`                                     |
| `repay`              | Repay outstanding debt                      | `positionId`, `amount`                                     |
| `get_my_positions`   | View all borrowing positions                | None                                                       |

**Usage Pattern:**

```typescript
// Agent deposits into USDC vault
await agent.deposit_liquidity({ market: "USDC", amount: "100" })
// → { userOpHash: "0x...", vault: "0x...", shares: "99.5" }

// Agent creates leveraged position
await agent.create_position({
  market: "USDC",
  collateral: "WETH",
  collateralAmount: "1.0",
  borrowAmount: "2000"
})
// → { userOpHash: "0x...", positionId: 42 }
```

***

### Yield Intelligence (9 tools)

| Tool                     | Description                                  | Parameters                              |
| ------------------------ | -------------------------------------------- | --------------------------------------- |
| `get_market_overview`    | All markets with APY, utilization, liquidity | None                                    |
| `list_opportunities`     | Yield opportunities sorted by APY            | `minAPY` (optional)                     |
| `find_best_yield`        | Filter by APY and risk tolerance             | `minAPY`, `maxRisk`, `preferredAssets`  |
| `analyze_position`       | Health check and liquidation risk            | `positionId`                            |
| `compare_markets`        | Side-by-side market comparison               | `markets[]`                             |
| `suggest_strategy`       | AI-powered investment recommendations        | `portfolio`, `riskProfile`, `targetAPY` |
| `get_transaction_status` | Check UserOp confirmation status             | `userOpHash`                            |
| `estimate_gas`           | Gas cost estimation for operations           | `operation`, `params`                   |
| `get_portfolio_summary`  | Complete DeFi portfolio overview             | None                                    |

**Usage Pattern:**

```typescript
// Agent analyzes yield opportunities
await agent.find_best_yield({ minAPY: 5.0, maxRisk: "medium" })
// → [ { market: "USDC", apy: 8.2%, risk: "low", ... }, ... ]

// Agent checks position health
await agent.analyze_position({ positionId: 42 })
// → { healthFactor: 1.8, liquidationPrice: "$1850", recommendation: "safe" }
```

***

## ERC-4337 Integration

### UserOperation Flow

The agent constructs and signs **PackedUserOperations** (ERC-4337 v0.7) for all on-chain transactions:

1. **MCP Server** generates transaction calldata
2. **Owl Agent** constructs UserOperation struct
3. **EOA Private Key** signs UserOperation hash
4. **Bundler Relay** submits to bundler (API key protected)
5. **EntryPoint** validates and executes on-chain

### Contract Addresses (Base Sepolia)

| Contract           | Address                                      |
| ------------------ | -------------------------------------------- |
| EntryPoint v0.7    | `0x0000000071727De22E5E9d8BAf0edAc6f37da032` |
| WhitelistPaymaster | `0xfeca68c7a02a8153897b54e36e42972d0f9f3166` |
| SmartWalletFactory | See `owl-wallet-mcp` docs                    |

### Gas Sponsorship

All agent transactions are gas-sponsored through the **WhitelistPaymaster**:

* Agent wallet must be whitelisted by paymaster owner
* No ETH balance required in smart wallet for gas
* Paymaster validates wallet address in `paymasterAndData` field

***

## Configuration

### Environment Variables

**Development (Local):**

```bash
# EOA private key for signing UserOps
WALLET_PRIVATE_KEY=0x...

# Bundler relay endpoint (defaults to localhost:3002)
BUNDLER_RELAY_URL=http://localhost:3002/rpc

# Optional: Custom MCP server paths
MCP_LENDEFI_PATH=/path/to/lendefi-mcp/src/index.ts
MCP_WALLET_PATH=/path/to/owl-wallet-mcp/src/index.ts
```

**Production (GCP Secret Manager):**

```bash
# Enable GCP Secret Manager integration
GOOGLE_CLOUD_PROJECT=your-project-id
USE_GCP_SECRETS=true

# Bundler relay (Cloud Run URL)
BUNDLER_RELAY_URL=https://bundler-relay-xxxxx-uc.a.run.app/rpc
```

### Setup Steps

**1. Install Dependencies**

```bash
cd openclaw/owl-agent
npm install
```

**2. Configure Environment**

```bash
cp .env.example .env
# Edit .env with your configuration
```

**3. Build & Run**

```bash
# Development with hot reload
npm run dev

# Production build
npm run build
npm start

# Lint & type check
npm run lint
npm run typecheck
```

***

## Security

### Key Management

**Development:**

* Private key stored in `.env` file
* ⚠️ Never commit `.env` to version control
* Use test accounts only on Base Sepolia

**Production:**

* Private key stored in GCP Secret Manager (`owl-agent-evm-key`)
* Service account with `secretmanager.secretAccessor` role
* Automatic credential injection in Cloud Run/GKE

### GCP Secret Manager Setup

**1. Enable API**

```bash
gcloud services enable secretmanager.googleapis.com
```

**2. Create Secret**

```bash
echo -n "0xYOUR_PRIVATE_KEY" | gcloud secrets create owl-agent-evm-key \
  --data-file=- \
  --replication-policy="automatic"
```

**3. Create Service Account**

```bash
gcloud iam service-accounts create owl-agent-sa \
  --display-name="Owl Agent Service Account"

SA_EMAIL="owl-agent-sa@${PROJECT_ID}.iam.gserviceaccount.com"
```

**4. Grant IAM Permissions**

```bash
gcloud secrets add-iam-policy-binding owl-agent-evm-key \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/secretmanager.secretAccessor"
```

**5. Attach Service Account to Workload**

```bash
# Cloud Run deployment
gcloud run deploy owl-agent \
  --service-account=${SA_EMAIL} \
  --set-env-vars=USE_GCP_SECRETS=true,GOOGLE_CLOUD_PROJECT=${PROJECT_ID}
```

### Secret Rotation

```bash
# Add new version
echo -n "0xNEW_KEY" | gcloud secrets versions add owl-agent-evm-key --data-file=-

# Disable old version
gcloud secrets versions disable <VERSION> --secret=owl-agent-evm-key

# Destroy old version (permanent)
gcloud secrets versions destroy <VERSION> --secret=owl-agent-evm-key
```

***

## File Structure

```
owl-agent/
├── tool.ts                 # Main agent implementation (23 tools)
├── SKILL.md               # OpenClaw skill definition
├── README.md              # This documentation
├── package.json           # Dependencies and scripts
├── tsconfig.json          # TypeScript configuration
├── eslint.config.js       # Linting rules
├── .env.example           # Environment template
├── abis/                  # Contract ABIs
│   ├── entrypoint-abi.json      # ERC-4337 EntryPoint v0.7
│   ├── smartwallet-abi.json     # SmartWallet ABI
│   └── erc20-abi.json           # ERC-20 token ABI
└── scripts/               # Utility scripts
```

***

## Related Components

| Component          | Documentation                                                                                                                 | Purpose                                   |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| **lendefi-mcp**    | [MCP Servers → Lendefi](/mcp-servers/mcp-servers/lendefi.md)                                                                  | Lendefi protocol integration (37 tools)   |
| **owl-wallet-mcp** | [MCP Servers → Owl Wallet](https://github.com/greenowl-money/owl-wallet-docs/blob/main/mcp-servers/owl-wallet.md)             | Smart wallet factory operations (4 tools) |
| **bundler-relay**  | [Infrastructure → Bundler Relay](https://github.com/greenowl-money/owl-wallet-docs/blob/main/infrastructure/bundler-relay.md) | ERC-4337 bundler API key protection       |
| **SmartWallet**    | [Smart Contracts → SmartWallet](https://github.com/greenowl-money/owl-wallet-docs/blob/main/contracts/core/smartwallet.md)    | On-chain wallet contract                  |

***

## Troubleshooting

**Agent fails to sign UserOps:**

* Verify `WALLET_PRIVATE_KEY` is valid hex string with `0x` prefix
* Check GCP Secret Manager permissions if using `USE_GCP_SECRETS=true`
* Confirm service account has `secretmanager.secretAccessor` role

**UserOp submission fails:**

* Verify bundler relay is running and accessible at `BUNDLER_RELAY_URL`
* Check wallet is whitelisted in WhitelistPaymaster
* Ensure wallet is deployed before executing transactions

**MCP server connection errors:**

* Confirm `MCP_LENDEFI_PATH` and `MCP_WALLET_PATH` point to valid TypeScript files
* Check MCP servers are properly installed in their respective directories
* Verify Node.js version is compatible (v18+ recommended)

**GCP Secret access denied:**

```bash
# Check IAM bindings
gcloud secrets get-iam-policy owl-agent-evm-key

# Verify service account
gcloud iam service-accounts get-iam-policy ${SA_EMAIL}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.greenowl.money/agent-and-tools/agent/owl_agent.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
