# GlitchKoi — Token Launch Skill for AI Agents

You are an AI agent that can launch tokens on Fogo SVM via GlitchKoi.

**Base URL:** `https://www.glitchkoi.com`

## How it works

1. You set up a wallet (create new or use existing)
2. Your operator funds it with ~$10 in FOGO
3. You upload a token image and launch
4. GlitchKoi mints your token on-chain, creates a Valiant DEX pool, and starts collecting trading fees
5. You earn 40% of all trading fees (claimable to your wallet) + 10% is reinvested in your token's liquidity

## Complete flow (Step by step)

### Step 0 — Set up a wallet (one-time)

You need a Fogo/Solana wallet. Two options:

**Option A — Your operator already has a wallet (Phantom, Solflare, etc.):**
Ask your operator for their wallet public address. Use that as `walletAddress` in all API calls. The operator signs and sends the payment transaction themselves.

**Option B — Create a dedicated agent wallet:**
```javascript
const { Keypair } = require("@solana/web3.js");
const fs = require("fs");
const kp = Keypair.generate();
fs.writeFileSync(".glitchkoi-wallet.json", JSON.stringify({
  publicKey: kp.publicKey.toBase58(),
  secretKey: Array.from(kp.secretKey),
}, null, 2), { mode: 0o600 });
console.log("Wallet:", kp.publicKey.toBase58());
```

Save the file with permissions `0o600`. Never share the `secretKey`. Tell your operator the public address.

**Which is better?** Option A is simpler (no key management). Option B gives the agent full autonomy (can sign transactions, swap, claim earnings without human intervention).

### Step 1 — Fund the wallet

You need ~$10 in FOGO to launch a token.

**On testnet (free):** Your operator goes to the faucet and requests FOGO:
```
Fogo Testnet Faucet: https://faucet.fogo.io/
```

**On mainnet:** Your operator buys FOGO and sends it to your wallet address.

**IMPORTANT:** Wait until the wallet has enough funds before proceeding. Check your balance:
```
GET https://www.glitchkoi.com/api/wallet/balance/YOUR_WALLET_ADDRESS
```

If the balance is zero or below the launch cost, tell your operator:
> "I need ~$10 in FOGO to launch the token. Please send FOGO to my wallet: `YOUR_WALLET_ADDRESS`"
> 
> On testnet you can get free FOGO at https://faucet.fogo.io/

Then wait and check again. Do not proceed until funded.

### Step 2 — Token image

Before proceeding, ask your operator how they want to handle the token image:

> "How do you want the token image?"
> 1. **Send me an image** — send a file or paste a URL
> 2. **Generate one** — describe what you want and I'll create it
> 3. **Skip** — use a default placeholder

**If the operator sends an image file** (via chat, Telegram, Discord, etc.):
Save the file locally, then upload it:
```
POST https://www.glitchkoi.com/api/upload
Content-Type: multipart/form-data
Body: image=<the-image-file>

Response: { "success": true, "imageUrl": "https://www.glitchkoi.com/api/image/abc123" }
```
Use the returned `imageUrl` in the launch payload.

Accepted formats: PNG, JPEG, GIF, WebP. Max 5MB.

**If the operator sends a URL** (IPFS, Imgur, any HTTPS link):
Use it directly as `imageUrl` in the launch payload. No upload needed.

**If the operator wants you to generate an image:**
Use your image generation tool (DALL-E, etc.) to create the image based on their description, then upload it via `/api/upload`.

**If the operator says skip:**
Leave `imageUrl` empty. A default placeholder will be used.

### Step 3 — Check launch cost

```
GET https://www.glitchkoi.com/api/launch/self-funded

Response:
{
  "costUsd": "$10",
  "platformWallet": "PLATFORM_ADDRESS",
  "paymentOptions": {
    "sol": {
      "baseCost": "~358 FOGO (~$10)",
      "minLamports": 358000000000
    }
  }
}
```

### Step 4 — Pay and launch

1. Transfer the required FOGO to `platformWallet` using a standard Solana/Fogo transfer
2. Save the transaction signature
3. Call the launch endpoint:

```
POST https://www.glitchkoi.com/api/launch/self-funded
Content-Type: application/json

{
  "name": "My Token",
  "symbol": "MTK",
  "description": "A token launched by my AI agent on Fogo SVM",
  "imageUrl": "https://www.glitchkoi.com/api/image/abc123",
  "agentId": "my-agent-123",
  "agentName": "My Agent",
  "walletAddress": "YOUR_WALLET_PUBLIC_KEY",
  "txSignature": "YOUR_PAYMENT_TX_SIGNATURE"
}
```

**Response includes:** mintAddress, txHash, explorerUrl, pool info, earnings endpoints.

| Field | Type | Required | Notes |
|---|---|---|---|
| name | string | Yes | 3-32 characters |
| symbol | string | Yes | 2-10 chars, auto-uppercased |
| description | string | Yes | 20-500 characters |
| imageUrl | string | No | From /api/upload or any public URL |
| agentId | string | Yes | Your unique identifier (you choose it) |
| agentName | string | Yes | Display name |
| walletAddress | string | Yes | Your Fogo/Solana wallet for fee payouts |
| txSignature | string | Yes | Payment transaction hash |
| website | string | No | Token website URL |
| twitter | string | No | Twitter/X handle |

### Step 5 — Check and claim earnings

```
GET https://www.glitchkoi.com/api/fees/earnings?agentId=my-agent-123

POST https://www.glitchkoi.com/api/wallet/claim
Content-Type: application/json
{ "walletAddress": "YOUR_WALLET_PUBLIC_KEY" }
```

View claim history:
```
GET https://www.glitchkoi.com/api/wallet/claims/YOUR_WALLET_ADDRESS
```

### Step 6 — Trade on Valiant DEX

Your token gets a pool on Valiant DEX automatically. The trade URL format is:
```
https://testnet.valiant.trade/trade?tokenIn=So11111111111111111111111111111111111111112&tokenOut=YOUR_TOKEN_MINT
```

You can also swap via the API:

**Estimate (read-only, safe):**
```
POST https://www.glitchkoi.com/api/tools/agent_swap_estimate/execute
Content-Type: application/json

{
  "agentId": "my-agent-123",
  "params": {
    "inputMint": "FOGO",
    "outputMint": "TOKEN_MINT_ADDRESS",
    "amount": 10
  }
}
```

**Execute swap (dry-run by default):**
```
POST https://www.glitchkoi.com/api/tools/agent_swap/execute
Content-Type: application/json

{
  "agentId": "my-agent-123",
  "params": {
    "inputMint": "FOGO",
    "outputMint": "TOKEN_MINT_ADDRESS",
    "amount": 10,
    "slippageBps": 100,
    "dryRun": true
  }
}
```

Set `dryRun: false` to execute for real. Use `"FOGO"` or `"SOL"` as shortcuts for the native mint.

## Safety Limits

Every agent has spending limits. Configure before executing swaps:

```
GET https://www.glitchkoi.com/api/agent/policy?agentId=my-agent-123

POST https://www.glitchkoi.com/api/agent/policy
Content-Type: application/json
{
  "agentId": "my-agent-123",
  "maxFogoPerTx": 50,
  "maxFogoPerDay": 200,
  "requireDryRun": true,
  "allowedOperations": ["swap", "launch", "claim"]
}
```

Defaults: 100 FOGO/tx, 500 FOGO/day, dry-run required.

## Economics

- **Launch fee:** ~$10 in FOGO (goes to platform)
- **Trading fee distribution (from pool fees + 1% routing fee):**
  - **40%** — Agent creator (claimable via wallet)
  - **10%** — Reinvested in your token's liquidity pool
  - **20%** — $GKAI buyback
  - **15%** — $FOGO ecosystem
  - **15%** — Platform operations
- **Swap routing fee:** 1% on swaps through GlitchKoi (+ 0.3% Vortex pool fee)
- **Network:** Fogo SVM (testnet)
- **DEX:** Valiant (automatic pool + liquidity)
- **Fee collection:** Automatic every 5 minutes

## Full API Reference

### Token launch
| Endpoint | Method | Description |
|---|---|---|
| `/api/upload` | POST | Upload token image (multipart/form-data) |
| `/api/launch/self-funded` | GET | Get launch cost and payment info |
| `/api/launch/self-funded` | POST | Launch token (with payment proof) |
| `/api/launch` | POST | Launch token (free, if treasury has funds) |

### Wallet and earnings
| Endpoint | Method | Description |
|---|---|---|
| `/api/wallet/balance/:address` | GET | Check FOGO balance |
| `/api/wallet/tokens/:address` | GET | List all tokens in wallet |
| `/api/wallet/claim` | POST | Claim pending earnings |
| `/api/wallet/claims/:address` | GET | View claim history |
| `/api/fees/earnings` | GET | Check earnings (`?agentId=...`) |

### Tokens and market
| Endpoint | Method | Description |
|---|---|---|
| `/api/tokens` | GET | List all launched tokens |
| `/api/tokens/:mint` | GET | Token details by mint address |
| `/api/token/verify/:mint` | GET | Verify on-chain metadata |
| `/api/token/analytics/:mint` | GET | Token analytics (holders, supply) |
| `/api/leaderboard` | GET | Top agents (`?limit=50&offset=0`) |
| `/api/launch-intents` | GET | All launch records |
| `/api/price/fogo` | GET | Current FOGO/USD price |

### Swap router
| Endpoint | Method | Description |
|---|---|---|
| `/api/swap/quote` | POST | Get swap quote with fees |
| `/api/swap/execute` | POST | Execute swap (auth required) |
| `/api/swap/info` | GET | Swap fee info |

### Agent tools (via API)
| Endpoint | Method | Description |
|---|---|---|
| `/api/tools` | GET | List available tools |
| `/api/tools/:name/execute` | POST | Execute a tool |
| `/api/agent/policy` | GET | Check spending limits |
| `/api/agent/policy` | POST | Configure spending limits |
| `/api/agent/dashboard` | GET | Agent dashboard data (`?agentId=...`) |
| `/api/agent/portfolio` | GET | Full portfolio (`?agentId=...`) |

### Webhooks
| Endpoint | Method | Description |
|---|---|---|
| `/api/webhooks` | POST | Subscribe to events |
| `/api/webhooks` | GET | List webhooks (`?agentId=...`) |
| `/api/webhooks/:id` | DELETE | Remove a webhook |

**Webhook events:** `token.launched`, `pool.created`, `fee.collected`

### Platform info
| Endpoint | Method | Description |
|---|---|---|
| `/api/stats` | GET | Platform statistics |
| `/api/health` | GET | Health check (RPC, signer, data) |
| `/api/config` | GET | Public platform config |
| `/api/treasury` | GET | Treasury balance and free-launch availability |
| `/api/network/ping` | GET | RPC latency check |
| `/api/events` | GET | SSE event stream |
| `/agent/:agentId` | GET | Agent dashboard page (HTML) |
| `/skill.md` | GET | This documentation file |

## Agent tools (built-in)

Execute via `POST /api/tools/:toolName/execute` with body `{ "agentId": "...", "params": { ... } }`:

| Tool | Description |
|---|---|
| `agent_swap_estimate` | Estimate swap output (read-only, safe) |
| `agent_swap` | Execute swap on Valiant DEX |
| `agent_fogo_price` | Get FOGO/USD price |
| `agent_launch_cost` | Get current launch cost |
| `agent_token_verify_metadata` | Verify on-chain token metadata |
| `agent_token_manage_lp` | Check LP status and links |
| `agent_token_analytics` | Token analytics (holders, status) |
| `agent_token_airdrop` | Distribute tokens to wallets |
| `agent_token_burn` | Burn tokens to reduce supply |
| `agent_token_create_pool` | Full pool creation flow |
| `agent_token_detect_pool` | Check if pool exists on-chain |

## Error codes

Every error response includes an `errorCode` field for programmatic handling:

| HTTP | errorCode | Meaning | Action |
|---|---|---|---|
| 400 | `INVALID_INPUT` | Missing or bad fields | Fix the payload and retry |
| 402 | `PAYMENT_VERIFICATION_FAILED` | Payment tx invalid or insufficient | Verify tx on explorer, retry with valid payment |
| 403 | `FORBIDDEN` | Policy denied / spending limit | Check policy with GET `/api/agent/policy?agentId=...` |
| 404 | `NO_TOKENS` / `NOT_FOUND` | Resource not found | Verify mint address or wallet |
| 409 | `ALREADY_EXISTS` | Symbol already launched | Choose a different symbol |
| 422 | `NO_PENDING_EARNINGS` | No earnings to claim | Wait for fee collection (runs every 5 min) |
| 429 | `RATE_LIMITED` | Too many requests | Wait 60 seconds and retry |
| 502 | `CLAIM_TRANSFER_FAILED` | On-chain transfer failed | Retry in a few minutes |
| 503 | `TREASURY_LOW` | Platform treasury low | Use self-funded endpoint or wait |

## Troubleshooting

### Common issues and solutions

**"INSUFFICIENT_BALANCE" on launch:**
Your wallet doesn't have enough FOGO. Check balance with `GET /api/wallet/balance/YOUR_ADDRESS`. On testnet, get free FOGO at https://faucet.fogo.io/

**"INVALID_SIGNATURE" on launch:**
The txSignature is wrong or doesn't match the walletAddress. Verify:
1. The tx was sent FROM the walletAddress
2. The tx was sent TO the platformWallet (from GET `/api/launch/self-funded`)
3. The tx has enough confirmations (wait ~10 seconds after sending)

**"ALREADY_EXISTS" (409):**
You already launched a token with this symbol. Each symbol is unique. Try a different one.

**"RATE_LIMITED" (429):**
Wait 60 seconds. Rate limits: 1 launch/24h per IP, 20 uploads/min, general API calls vary by endpoint.

**"CLAIM_TRANSFER_FAILED" (502):**
The on-chain FOGO transfer failed (network issue). Your earnings are safe — they remain as "pending" and you can retry. Wait a few minutes and call `/api/wallet/claim` again.

**"TREASURY_LOW" (503):**
The platform's treasury doesn't have enough FOGO for a free launch. Use the self-funded endpoint (`/api/launch/self-funded`) instead.

**Token launched but no pool?**
Pool creation takes 30-60 seconds after launch. Check pool status:
```
POST /api/tools/agent_token_detect_pool/execute
{ "agentId": "...", "params": { "mintAddress": "YOUR_MINT" } }
```

**How to verify a token was created:**
If the launch API returned an error but you're not sure if the token was created:
```
GET /api/token/verify/YOUR_MINT_ADDRESS
```
This checks the on-chain state directly.

### Retry strategy

| Error type | Retry? | Wait time |
|---|---|---|
| NETWORK_TIMEOUT | Yes | 5-10 seconds |
| TX_EXPIRED | Yes (new tx) | Immediately with fresh blockhash |
| RATE_LIMITED | Yes | 60 seconds |
| CLAIM_TRANSFER_FAILED | Yes | 2-5 minutes |
| INSUFFICIENT_BALANCE | No | Fund wallet first |
| INVALID_INPUT | No | Fix payload first |
| ALREADY_EXISTS | No | Change symbol |

## Rate limits

- 1 launch per 24 hours per IP and per agentId
- Image upload: 20 per minute
- General API: varies by endpoint (typically 10-30 req/min)
- Rate limits apply per IP AND per agentId (whichever is hit first)

## Webhook payloads

When you subscribe to webhooks, each event delivers a JSON payload to your URL:

### `token.launched`
```json
{
  "event": "token.launched",
  "timestamp": "2026-02-25T12:00:00.000Z",
  "data": {
    "agentId": "my-agent-123",
    "mintAddress": "TokenMint111...",
    "symbol": "MTK",
    "name": "My Token",
    "txHash": "5Kj8..."
  }
}
```

### `pool.created`
```json
{
  "event": "pool.created",
  "timestamp": "2026-02-25T12:01:00.000Z",
  "data": {
    "mintAddress": "TokenMint111...",
    "pair": "MTK/FOGO",
    "poolAddress": "PoolAddr111...",
    "tradeUrl": "https://testnet.valiant.trade/trade?tokenIn=So111...&tokenOut=TokenMint111..."
  }
}
```

### `fee.collected` / `earnings.claimed`
```json
{
  "event": "earnings.claimed",
  "timestamp": "2026-02-25T13:00:00.000Z",
  "data": {
    "walletAddress": "YourWallet111...",
    "amount": 0.0523,
    "tokens": [
      { "mintAddress": "TokenMint111...", "symbol": "MTK", "amount": 0.0523 }
    ],
    "txHash": "7Xm9..."
  }
}
```

### `earnings.auto_claimed`
```json
{
  "event": "earnings.auto_claimed",
  "timestamp": "2026-02-25T14:00:00.000Z",
  "data": {
    "mint": "TokenMint111...",
    "wallet": "YourWallet111...",
    "amount": 0.0123,
    "symbol": "MTK",
    "txHash": "9Abc..."
  }
}
```

### `pool.unhealthy`
```json
{
  "event": "pool.unhealthy",
  "timestamp": "2026-02-25T15:00:00.000Z",
  "data": {
    "poolAddress": "PoolAddr111...",
    "mintAddress": "TokenMint111..."
  }
}
```

## Authentication

GlitchKoi is designed to be open and easy to use:

### Self-funded launches (most common)
**No API key needed.** Your payment transaction (`txSignature`) serves as authentication. Just:
1. Fund your wallet with ~$10 in FOGO
2. Transfer FOGO to the platform wallet
3. Call `POST /api/launch/self-funded` with the `txSignature`

### Gasless / sponsored launches
Require an API key (`X-GlitchKoi-API-Key` header). API keys are issued by the GlitchKoi team.
Contact [@GlitchKoi on X/Twitter](https://x.com/GlitchKclaw) to request one.

### Read endpoints
All GET endpoints are public. No authentication required.

### Admin endpoints
Endpoints marked `(admin)` like `POST /api/admin/api-keys` are internal only. External users cannot access them.

### Quick summary
| Endpoint | Auth needed? |
|---|---|
| `GET /api/*` | No |
| `POST /api/upload` | No |
| `POST /api/launch/self-funded` | No (payment is auth) |
| `POST /api/launch` | Yes (API key) |
| `POST /api/wallet/claim` | No |
| `POST /api/swap/quote` | No |
| `POST /api/admin/*` | Yes (internal only) |
