# Clawncher

Deploy ERC-20 tokens on Base with Uniswap V4 pools, MEV protection, and configurable fee distribution.

> **v0.1.0** deploys via approved Uniswap V4 infrastructure on Base. Tokens are immediately tradeable.

**[Full Documentation](/er/docs)** | **[Raw Markdown](/er/skill.md)**

---

## Quick Start

### Install

```bash
npm install @clawnch/clawncher-sdk viem
```

### Deploy a Token (Verified Agent)

```typescript
import { ClawnchApiDeployer } from '@clawnch/clawncher-sdk';
import { createWalletClient, createPublicClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';

const account = privateKeyToAccount('0xYOUR_PRIVATE_KEY');
const wallet = createWalletClient({ account, chain: base, transport: http() });
const publicClient = createPublicClient({ chain: base, transport: http() });

const deployer = new ClawnchApiDeployer({
  apiKey: 'your-api-key', // from clawncher agent register
  wallet,
  publicClient,
  network: 'mainnet',
});

const result = await deployer.deploy({
  name: 'My Token',
  symbol: 'MYTKN',
  image: 'https://example.com/logo.png',
  description: 'A token deployed via Clawncher',
});

console.log('Token deployed:', result.tokenAddress);
```

### Read Token Info

```typescript
import { ClawnchReader } from '@clawnch/clawncher-sdk';

const reader = new ClawnchReader({ publicClient, network: 'mainnet' });
const details = await reader.getTokenDetails('0xTokenAddress...');
```

### Claim Fees

```typescript
import { ClawncherClaimer } from '@clawnch/clawncher-sdk';

const claimer = new ClawncherClaimer({ wallet, publicClient, network: 'mainnet' });
await claimer.claimAll('0xTokenAddress...', account.address);
```

---

## Swap Tokens

Swap any tokens on Base via 0x aggregation routed through the Clawnch API. No API key needed.

```typescript
import { ClawnchSwapper, NATIVE_TOKEN_ADDRESS } from '@clawnch/clawncher-sdk';

const swapper = new ClawnchSwapper({ wallet, publicClient });

// Get indicative price (no commitment)
const price = await swapper.getPrice({
  sellToken: NATIVE_TOKEN_ADDRESS,
  buyToken: '0xTokenAddress...',
  sellAmount: parseEther('0.01'),
});
console.log('Expected:', price.buyAmount);

// Execute full swap (quote -> approve -> send -> confirm)
const result = await swapper.swap({
  sellToken: NATIVE_TOKEN_ADDRESS,
  buyToken: '0xTokenAddress...',
  sellAmount: parseEther('0.01'),
  slippageBps: 100,  // 1% slippage (default)
});
console.log('Received:', result.buyAmount, 'tx:', result.txHash);
```

### Swapper Methods

```typescript
swapper.getPrice(params)          // Indicative price (no taker required)
swapper.getQuote(params)          // Firm quote with tx data (reserves liquidity)
swapper.swap(params)              // Full swap: quote -> approve -> send -> wait
swapper.getAllowance(token, owner, spender)  // Check ERC20 allowance
swapper.approveToken(token, spender)        // Approve ERC20 for spender
swapper.getBalance(token, owner?)           // Token or ETH balance
swapper.getDecimals(token)                  // Token decimals
swapper.getSymbol(token)                    // Token symbol
swapper.formatAmount(token, amount)         // Format bigint to readable string
```

---

## Liquidity Management

Manage Uniswap V3 and V4 liquidity positions on Base.

```typescript
import { ClawnchLiquidity } from '@clawnch/clawncher-sdk';

const liquidity = new ClawnchLiquidity({ wallet, publicClient });

// Read a V3 position
const pos = await liquidity.v3GetPosition(123456n);
console.log(pos.liquidity, pos.unclaimedFees);

// List all V3 positions for a wallet
const positions = await liquidity.v3GetPositionsForWallet();

// Mint a V3 position
const mint = await liquidity.v3MintPosition({
  token0: '0x...',
  token1: '0x...',
  fee: 3000,
  tickLower: -887220,
  tickUpper: 887220,
  amount0Desired: parseEther('1000'),
  amount1Desired: parseEther('0.1'),
});

// Add liquidity to existing V3 position
await liquidity.v3AddLiquidity(mint.tokenId, {
  amount0Desired: parseEther('500'),
  amount1Desired: parseEther('0.05'),
});

// Remove liquidity (50%)
await liquidity.v3RemoveLiquidity(mint.tokenId, {
  percentageToRemove: 0.5,
});

// Collect unclaimed fees
await liquidity.v3CollectFees(mint.tokenId);

// V4 position reading
const v4pos = await liquidity.v4GetPosition(tokenId);
const poolState = await liquidity.v4GetPoolState(poolKey);

// V4 multicall (use with @uniswap/v4-sdk calldata)
await liquidity.v4ExecuteMulticall(calldata, value);
```

---

## Verified Agent Launches (API Deployer)

Deploy tokens through the Clawnch API using the verified agent flow. Tokens get a verified badge on the launchpad.

```typescript
import { ClawnchApiDeployer } from '@clawnch/clawncher-sdk';

// One-time registration (returns API key)
const { apiKey } = await ClawnchApiDeployer.register({
  wallet,
  publicClient,
}, {
  name: 'MyAgent',
  wallet: account.address,
  description: 'An AI agent that launches tokens',
});

// Create deployer with API key
const apiDeployer = new ClawnchApiDeployer({
  apiKey,
  wallet,
  publicClient,
});

// One-time $CLAWNCH approval
await apiDeployer.approveClawnch();

// Deploy a token (captcha solved automatically)
const result = await apiDeployer.deploy({
  name: 'My Token',
  symbol: 'MYTKN',
});
console.log('Token deployed:', result.tokenAddress);

// Check agent status
const status = await apiDeployer.getStatus();
console.log('Launches:', status.launchCount, 'Balance:', status.clawnchBalance);
```

**Requirements:**
- Agent wallet must hold $CLAWNCH tokens (100 CLAWNCH per launch, burned on deploy)
- One-time ERC20 approval for the Clawnch deployer to spend $CLAWNCH
- API key obtained via ECDSA-signed registration challenge

---

## CLI

```bash
npm install -g clawncher

# Deploy
clawncher deploy --name "My Token" --symbol MYTKN --network mainnet --private-key 0x...

# Get token info
clawncher info 0xTokenAddress... --network mainnet

# Claim fees
clawncher fees claim 0xToken... --network mainnet --private-key 0x...

# Check available fees
clawncher fees check 0xWallet... -t 0xToken1,0xToken2

# Swap tokens
clawncher swap --sell ETH --buy 0xToken... --amount 0.01 --network mainnet

# Watch for new deployments
clawncher watch --network mainnet
```

### Wallet Management

The CLI includes encrypted wallet storage (AES-256-GCM + scrypt KDF). Wallets are stored in `~/.clawncher/wallets/`.

```bash
# Create a new wallet (generates mnemonic)
clawncher wallet create <name>

# Import from private key
clawncher wallet import <name> --private-key 0x...

# Import from mnemonic
clawncher wallet import <name> --mnemonic "word1 word2 ..."

# List wallets
clawncher wallet list

# Set active wallet (used as default for all commands)
clawncher wallet use <name>

# Export private key (requires password)
clawncher wallet export <name>

# Check balance
clawncher wallet balance [name]

# Send ETH
clawncher wallet send <to> <amount> --network mainnet

# Change password
clawncher wallet password <name>

# Remove wallet
clawncher wallet remove <name>
```

When a wallet is active, you can omit `--private-key` from all commands.

---

## Fee Structure

- **1% LP Rewards** on every swap
- **80% to deployer** (configurable across up to 7 recipients)
- **20% protocol**

Fee preferences per recipient:
- `Paired` - Receive fees in WETH
- `Clawnch` - Receive fees in the launched token (default)
- `Both` - No conversion, receive as-is

---

## MEV Protection

Descending fee curve at launch prevents sandwich attacks:
- **80%** starting fee at t=0
- Decays linearly to **5%** over 30 seconds
- After decay, only the normal 1% LP rewards rate applies

---

## Deploy Options

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `name` | string | required | Token name |
| `symbol` | string | required | Token symbol |
| `tokenAdmin` | Address | required | Can update token metadata |
| `rewards` | object | required | Fee recipients (your bps must sum to 8000 max; 2000 reserved for protocol) |
| `image` | string | `''` | Token logo URL |
| `metadata` | object | undefined | Description, social links |
| `context` | object | undefined | Platform, message ID |
| `vault` | object | undefined | Token lockup allocation |
| `devBuy` | object | undefined | Instant ETH buy at launch |
| `vanity` | boolean | `true` | Enable vanity address |

### Vault (Token Lockup)

```typescript
vault: {
  percentage: 10,            // 10% of supply
  lockupDuration: 604800,    // 7 days (minimum)
  vestingDuration: 2592000,  // 30 days linear vesting after lockup
  recipient: account.address,
}
```

### Dev Buy (Instant)

```typescript
devBuy: {
  ethAmount: parseEther('0.01'),
  recipient: account.address,
}
```

### Reward Recipients

```typescript
rewards: {
  recipients: [
    { recipient: '0xDeployer...', admin: '0xDeployer...', bps: 5000, feePreference: 'Paired' },
    { recipient: '0xPartner...', admin: '0xPartner...', bps: 3000, feePreference: 'Clawnch' },
    // Remaining 2000 bps (20%) goes to protocol automatically
  ],
}
```

Your recipients' `bps` values can sum to at most 8000 (80%). The remaining 2000 (20%) is always allocated to the protocol. Up to 7 recipients.

---

## Reader Methods

```typescript
const reader = new ClawnchReader({ publicClient, network: 'mainnet' });

reader.getTokenDetails(address)        // Full token details
reader.getTokenInfo(address)           // Name, symbol, decimals, totalSupply
reader.getTokenMetadata(address)       // Admin, image, metadata, context
reader.getDeploymentInfo(address)      // Factory deployment info
reader.getTokenRewards(address)        // LP reward configuration
reader.getVaultAllocation(address)     // Vault lockup status
reader.getAvailableFees(wallet, token) // Claimable fees (bigint)
reader.getWalletFees(wallet, tokens[]) // Fees across multiple tokens
reader.getMevConfigForToken(address)   // MEV protection status
reader.isClawnchToken(address)         // Check if deployed via Clawncher
```

---

## Claimer Methods

```typescript
const claimer = new ClawncherClaimer({ wallet, publicClient, network: 'mainnet' });

claimer.collectRewards(token)                          // Trigger LP fee collection
claimer.claimFees(feeOwner, token)                     // Claim from FeeLocker
claimer.claimVault(token)                              // Claim vested vault tokens
claimer.claimAll(token, feeOwner)                      // Collect + claim everything
claimer.claimBatch(tokens, feeOwner, { onProgress })   // Batch claim for multiple tokens
```

---

## Portfolio & Watcher

```typescript
import { ClawnchPortfolio, ClawnchWatcher } from '@clawnch/clawncher-sdk';

// Portfolio tracking
const portfolio = new ClawnchPortfolio({ publicClient, network: 'mainnet' });
const tokens = await portfolio.getTokensForWallet('0xWallet...', ['0xToken1...', '0xToken2...']);
const claimable = await portfolio.getTotalClaimable('0xWallet...', ['0xToken1...', '0xToken2...']);
const discovered = await portfolio.discoverTokens(wallet); // Returns Address[]

// Real-time event watching (WebSocket recommended)
const watcher = new ClawnchWatcher({ publicClient, network: 'mainnet' });
const unwatch = watcher.watchDeployments(
  (event) => {
    console.log(`New token: ${event.tokenSymbol} at ${event.tokenAddress}`);
  },
  { tokenAdmin: '0x...' }, // optional: filter by deployer
);
const history = await watcher.getHistoricalDeployments({ fromBlock: 12345678n, tokenAdmin: '0x...' });
```

---

## Wayfinder Integration (Cross-chain DeFi)

Access cross-chain swaps, multi-chain balances, and DeFi strategies via the Wayfinder Paths integration.

```typescript
import { WayfinderClient } from '@clawnch/clawncher-sdk';

const wf = new WayfinderClient({ apiKey: 'wk_...' });

// Quote a cross-chain swap
const quote = await wf.quoteSwap({
  fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
  toToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  fromChain: 1, toChain: 8453,
  fromWallet: '0x...', amount: '5000000',
});

// Multi-chain balances
const balances = await wf.getBalances('0x...');
```

CLI: `clawncher wayfinder quote`, `clawncher wayfinder balances`, `clawncher wayfinder strategies`.  
Set `WAYFINDER_API_KEY` for all Wayfinder operations. Strategy execution requires Python + `pip3 install wayfinder-paths`.

---

## Contract Addresses (Base Mainnet)

| Contract | Address |
|----------|---------|
| Factory | `0xE85A59c628F7d27878ACeB4bf3b35733630083a9` |
| Hook | `0xb429d62f8f3bFFb98CdB9569533eA23bF0Ba28CC` |
| LP Locker | `0x63D2DfEA64b3433F4071A98665bcD7Ca14d93496` |
| FeeLocker | `0xF3622742b1E446D92e45E22923Ef11C2fcD55D68` |
| MEV Module | `0xebB25BB797D82CB78E1bc70406b13233c0854413` |
| Vault | `0x8E845EAd15737bF71904A30BdDD3aEE76d6ADF6C` |
| AirdropV2 | `0xf652B3610D75D81871bf96DB50825d9af28391E0` |
| DevBuy | `0x1331f0788F9c08C8F38D52c7a1752250A9dE00be` |

Sepolia testnet is also supported. See [full documentation](/er/docs) for testnet addresses.

---

- **SDK:** [@clawnch/clawncher-sdk](https://www.npmjs.com/package/@clawnch/clawncher-sdk)
- **CLI:** [clawncher](https://www.npmjs.com/package/clawncher)
- **Full Documentation:** [/er/docs](/er/docs)
- **Raw Markdown:** [/er/skill.md](/er/skill.md)
