npm package: @loomlay/openclaw-wallet-plugin
Description: OpenClaw Wallet SDK plugin for AI agents - multi-chain wallet, trading, and DEX tools
Author: LoomLay
Latest version: 0.1.4

# @loomlay/openclaw-wallet-plugin

OpenClaw Wallet SDK plugin for AI agents - provides 29 native tools for multi-chain wallet management, trading, and DEX data with self-custody support.

## Features

- **Self-Custody by Default** - Private keys generated and encrypted locally, never sent to server
- **Zero Config** - Auto-registers API key and generates local wallet on first use
- **29 Native Tools** - Wallet, trading, DEX data, token launch, and more
- **Multi-Chain Support** - Solana, Ethereum, Base, Arbitrum, Optimism, Polygon, BSC
- **Flexible Amounts** - Supports `"1.5"`, `"$100"`, `"50%"`, `"max"`
- **Standardized Responses** - Consistent `{ success, data, error }` format
- **TypeScript First** - Full type definitions for all tools

## Zero Configuration

The plugin automatically handles setup:

1. **First use**: Auto-registers API key → saved to `~/.loomlay/credentials.json`
2. **Wallet creation**: Keys generated **locally**, encrypted to `~/.loomlay/wallet.json`
3. **Subsequent uses**: Loads saved key and local wallet automatically

No environment variables required for basic usage. Just install and use.

```typescript
// First call: auto-registers API key, creates local wallet
const wallet = await wallet_create();
// → Keys generated on YOUR device, encrypted with passphrase
// → Public addresses registered with API for balance lookups

// Unlock wallet for signing operations
await wallet_unlock({ passphrase: 'your-passphrase' });

// All trades sign locally — private key never sent to server
const result = await swap({
  inputToken: 'SOL',
  outputToken: 'USDC',
  amount: '1.5'
});
```

### Resolution Order

API keys:
1. `LOOMLAY_API_KEY` environment variable (highest priority)
2. Stored credentials (`~/.loomlay/credentials.json`)
3. Auto-register new account (if no key found)

Passphrase (for local wallet signing):
1. `LOOMLAY_WALLET_PASSPHRASE` environment variable (highest priority)
2. In-memory cache (set via `wallet_unlock`)
3. Error thrown with instructions

## Integration Options

### ClawHub (Recommended for AI Agents)

Install directly via ClawHub for seamless agent integration:

```bash
clawhub install openclaw-wallet --registry https://clawhub.ai
```

This installs the skill and makes all 27 tools available to your agent automatically.

### NPM (For Programmatic Use)

Install via npm for programmatic access in your own applications:

```bash
npm install @loomlay/openclaw-wallet-plugin
```

## Configuration

### Zero Config (Recommended)

The plugin works out of the box with no configuration. On first use, it automatically:
1. Registers for a new API key
2. Saves the key to `~/.loomlay/credentials.json`
3. Creates a local wallet (keys encrypted on your device)
4. Uses the saved key and local wallet for all subsequent requests

### Environment Variables (Optional)

```bash
# Override auto-registration
export LOOMLAY_API_KEY=agent_your_key_here

# Set wallet passphrase (avoids passphrase appearing in conversation logs)
export LOOMLAY_WALLET_PASSPHRASE=your-secure-passphrase

# Custom API endpoint
export LOOMLAY_BASE_URL=https://custom.api.com
```

### Programmatic Configuration (Optional)

```typescript
import { initPlugin, initPluginAsync } from '@loomlay/openclaw-wallet-plugin';

// Sync: Uses existing key from env/config/stored credentials
initPlugin({
  apiKey: 'agent_your_key_here',  // Optional if LOOMLAY_API_KEY set
  baseUrl: 'https://api.loomlay.com' // Optional
});

// Async: Supports auto-registration
const { client, registration } = await initPluginAsync({
  autoRegister: true // Default: true
});

if (registration) {
  console.log('New account created:', registration.apiKey);
  console.log('Saved to:', registration.savedTo);
}
```

### Disable Auto-Registration

If you want to require explicit API key configuration:

```typescript
import { initPluginAsync } from '@loomlay/openclaw-wallet-plugin';

// Throws error if no key found instead of auto-registering
const { client } = await initPluginAsync({ autoRegister: false });
```

## Available Tools (29)

### Wallet (5 tools)

| Tool | Description |
|------|-------------|
| `wallet_create` | Create a new multi-chain wallet (keys stored locally in self-custody mode) |
| `wallet_get` | Get wallet addresses and balances |
| `wallet_export_keys` | Export private keys (requires seed phrase or passphrase) |
| `wallet_unlock` | Cache passphrase in memory for signing operations |
| `wallet_import` | Import an existing seed phrase into a local wallet |

### Trading (5 tools)

| Tool | Description |
|------|-------------|
| `swap` | Execute a token swap |
| `swap_quote` | Get a swap quote without executing |
| `transfer` | Transfer tokens to an address |
| `bridge` | Bridge tokens between chains |
| `bridge_quote` | Get a bridge quote |

### Tokens (4 tools)

| Tool | Description |
|------|-------------|
| `token_search` | Search tokens by name/symbol/address |
| `token_price` | Get current USD price |
| `token_details` | Get detailed token information |
| `token_chart` | Get OHLCV chart data |

### Portfolio (2 tools)

| Tool | Description |
|------|-------------|
| `portfolio_get` | Get combined portfolio across chains |
| `portfolio_history` | Get transaction history |

### DEX (7 tools)

| Tool | Description |
|------|-------------|
| `dex_trending` | Get trending trading pairs |
| `dex_volume` | Get top volume pairs |
| `dex_gainers` | Get top price gainers |
| `dex_losers` | Get top price losers |
| `dex_new` | Get newly created pairs |
| `dex_pumpfun` | Get Pumpfun trending (Solana) |
| `dex_query` | Advanced query with custom filters |

### Tokenize (2 tools)

| Tool | Description |
|------|-------------|
| `tokenize_launch` | Launch a new token |
| `tokenize_info` | Get your launched token info |

### Fees (2 tools)

| Tool | Description |
|------|-------------|
| `fees_status` | Get fee status for your token |
| `fees_claim` | Claim accumulated trading fees |

### RPC (2 tools)

| Tool | Description |
|------|-------------|
| `rpc_call` | Direct RPC call to any chain |
| `rpc_chains` | Get list of supported chains |

## Usage Examples

### Self-Custody Workflow

```typescript
import {
  wallet_create,
  wallet_unlock,
  wallet_get,
  swap,
  swap_quote,
  wallet_import,
} from '@loomlay/openclaw-wallet-plugin';

// 1. Create wallet (keys generated and encrypted locally)
const wallet = await wallet_create();
if (wallet.success) {
  console.log('Address:', wallet.data.wallet.solanaAddress);
  console.log('Seed phrase:', wallet.data.seedPhrase); // Save securely!
}

// 2. Unlock wallet for signing (or set LOOMLAY_WALLET_PASSPHRASE env var)
await wallet_unlock({ passphrase: 'my-secure-passphrase' });

// 3. Trade — signing happens locally, private key never sent to server
const result = await swap({
  inputToken: 'SOL',
  outputToken: 'USDC',
  amount: '1.5'
});

// Import an existing wallet
const imported = await wallet_import({
  seedPhrase: 'your twelve word seed phrase here ...',
  passphrase: 'my-secure-passphrase'
});
```

### Direct Function Calls

```typescript
import {
  wallet_get,
  swap,
  swap_quote,
  dex_trending
} from '@loomlay/openclaw-wallet-plugin';

// Check balance
const balance = await wallet_get();
if (balance.success) {
  console.log('SOL:', balance.data.balances.solana.sol);
}

// Get swap quote
const quote = await swap_quote({
  inputToken: 'SOL',
  outputToken: 'USDC',
  amount: '$100'
});
if (quote.success) {
  console.log('Output:', quote.data.outputAmount);
}

// Execute swap
const result = await swap({
  inputToken: 'SOL',
  outputToken: 'USDC',
  amount: '1.5'
});

// Get trending
const trending = await dex_trending({
  chain: 'solana',
  minLiquidity: 10000,
  limit: 20
});
```

### Using the Tools Registry

```typescript
import { tools } from '@loomlay/openclaw-wallet-plugin';

// Call tools by name
const wallet = await tools.wallet_get();
const trending = await tools.dex_trending({ chain: 'solana' });
```

## Response Format

All tools return a standardized response:

```typescript
interface ToolResponse<T> {
  success: boolean;
  data?: T;           // Present when success is true
  error?: {
    message: string;
    code?: string;
    retryAfter?: number;  // For rate limit errors
  };
}
```

### Success Response

```typescript
{
  success: true,
  data: {
    // Tool-specific data
  }
}
```

### Error Response

```typescript
{
  success: false,
  error: {
    message: "Rate limited",
    code: "RATE_LIMITED",
    retryAfter: 30
  }
}
```

## Error Handling

```typescript
import { swap, RateLimitError, ApiError } from '@loomlay/openclaw-wallet-plugin';

const result = await swap({
  inputToken: 'SOL',
  outputToken: 'USDC',
  amount: '1'
});

if (!result.success) {
  switch (result.error?.code) {
    case 'RATE_LIMITED':
      console.log(`Wait ${result.error.retryAfter}s`);
      break;
    case 'BAD_REQUEST':
      console.log('Invalid parameters:', result.error.message);
      break;
    case 'UNAUTHORIZED':
      console.log('Check API key');
      break;
    default:
      console.log('Error:', result.error?.message);
  }
}
```

## Skill Integration

The plugin includes a skill file for AI agent training:

```typescript
import skillContent from '@loomlay/openclaw-wallet-plugin/skill';
// Or read from: node_modules/@loomlay/openclaw-wallet-plugin/skill/SKILL.md
```

The skill teaches agents:
- Wallet security best practices
- Quote-before-trade workflow
- Error handling patterns
- Chain-specific behaviors

## Amount Formats

Trading tools accept flexible amounts:

| Format | Example | Description |
|--------|---------|-------------|
| Decimal | `"1.5"` | Exact token amount |
| USD | `"$100"` | Dollar value |
| Percentage | `"50%"` | Percentage of balance |
| Max | `"max"` | Entire balance |

## Supported Chains

| Chain | Swaps | Bridges | RPC |
|-------|-------|---------|-----|
| Solana | ✅ | ✅ | ✅ |
| Ethereum | ✅ | ✅ | ✅ |
| Base | ✅ | ✅ | ✅ |
| Arbitrum | ✅ | ✅ | ✅ |
| Optimism | ✅ | ✅ | ✅ |
| Polygon | ✅ | ✅ | ✅ |
| BSC | ✅ | ✅ | ✅ |

## Plugin Manifest

The `openclaw.plugin.json` file describes all tools for plugin systems:

```json
{
  "name": "@loomlay/openclaw-wallet-plugin",
  "tools": [
    {
      "name": "swap",
      "description": "Execute a token swap...",
      "parameters": { ... },
      "returns": { ... }
    }
  ]
}
```

## Security

### Self-Custody (Default)

- **Local encryption**: PBKDF2-SHA512 (600k iterations) + AES-256-GCM
- **File permissions**: `~/.loomlay/wallet.json` stored with `0600` (owner read/write only)
- **No key transmission**: Private keys never sent to any server
- **Transaction validation**: Fee payer verified before signing
- **Passphrase safety**: Set `LOOMLAY_WALLET_PASSPHRASE` env var to avoid passphrase appearing in conversation logs

### General

1. **API Key** - Store in environment variables, never hardcode
2. **Seed Phrase** - Returned once from `wallet_create`, store offline securely
3. **Quotes First** - Always get quotes before executing trades
4. **Verify Addresses** - Double-check recipient addresses for transfers

## License

MIT