{"skill":{"slug":"pancake-swap-skills","displayName":"pancake skills","summary":"BSC (Binance Smart Chain) trading on PancakeSwap — wallet creation, token swaps, pair discovery, and balance management.","description":"---\nname: bsc-pancakeswap\nversion: 2.0.0\ndescription: BSC (Binance Smart Chain) trading on PancakeSwap — wallet creation, token swaps, pair discovery, and balance management.\nhomepage: https://pancakeswap.finance\nenv:\n  - name: BSC_RPC_URL\n    description: \"BSC JSON-RPC endpoint for sending transactions and reading on-chain state.\"\n    default: \"https://bsc-dataseed1.binance.org\"\n    required: true\n  - name: BSC_CHAIN_ID\n    description: \"Chain ID for BSC (56 = mainnet, 97 = testnet).\"\n    default: \"56\"\n    required: true\n  - name: PANCAKE_ROUTER\n    description: \"PancakeSwap V2 Router contract address on BSC.\"\n    default: \"0x10ED43C718714eb63d5aA57B78B54704E256024E\"\n    required: true\n  - name: WBNB\n    description: \"Wrapped BNB (WBNB) contract address on BSC.\"\n    default: \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"\n    required: true\n  - name: BSC_WALLET_FILE\n    description: \"Path to the agent's BSC wallet file (JSON with encrypted private key and address).\"\n    default: \"~/.config/bsc_agent/wallet.json\"\n    required: false\ncredentials:\n  - name: BSC Wallet File\n    path: \"~/.config/bsc_agent/wallet.json\"\n    description: \"Contains the agent's BSC private key (encrypted or plaintext) and public address. Created once during wallet setup. The agent uses this to sign swap transactions on BSC. This file SHOULD be encrypted at rest — see Security section.\"\n    access: read\n  - name: ClawChain Credentials (optional)\n    path: \"~/.config/clawchain/credentials.json\"\n    description: \"Chromia keypair used to authenticate on-chain operations. Only needed if registering the BSC public key on ClawChain for EVM event tracking. This file is created by the clawchain skill, not by this skill.\"\n    access: read\n    optional: true\ndependencies:\n  - name: Node.js\n    version: \">=18\"\n    description: \"JavaScript runtime required to run ethers.js wallet and transaction scripts.\"\n  - name: ethers\n    version: \"6\"\n    description: \"Ethereum library for wallet generation, contract interaction, and transaction signing.\"\n    install: \"npm install ethers\"\n---\n\n# BSC PancakeSwap Trading Skill\n\n## Purpose & Scope\n\nThis skill enables an AI agent to trade tokens on [PancakeSwap](https://pancakeswap.finance) (BSC mainnet). It covers:\n\n- **Wallet creation** — Generate a BSC keypair and store it locally for transaction signing.\n- **Token discovery** — Resolve any BEP-20 token by contract address, check pair existence and liquidity.\n- **Swaps** — Execute token swaps through PancakeSwap V2 Router with slippage protection.\n- **Balance checks** — Query native BNB and BEP-20 token balances.\n- **Top-ups** — Provide the agent's BSC address so the user can fund it.\n\n### What This Skill Does NOT Do\n\n- It does **not** manage ClawChain agent registration. For that, see the `clawchain` skill (`skill.md` or `curl_skills.md`).\n- It does **not** provide investment advice or execute trades without user confirmation.\n- It does **not** access any files outside of `~/.config/bsc_agent/` and optionally `~/.config/clawchain/credentials.json` (read-only, for EVM key registration only).\n\n### Transparency: Files Accessed\n\n| File | Access | Purpose |\n|------|--------|---------|\n| `~/.config/bsc_agent/wallet.json` | Read/Write (created once) | Stores the agent's BSC private key and address for signing transactions |\n| `~/.config/clawchain/credentials.json` | Read-only (optional) | Used only if registering BSC public key on ClawChain for EVM event tracking |\n\n### Transparency: Network Calls\n\n| Endpoint | Purpose |\n|----------|---------|\n| BSC RPC (`BSC_RPC_URL`) | Read blockchain state (balances, pair info) and submit signed transactions |\n| PancakeSwap Router contract | On-chain calls to discover pairs, get quotes, execute swaps |\n\n---\n\n## Configuration (BSC Mainnet)\n\nSet these environment variables before using the skill. All have sensible defaults for BSC mainnet:\n\n```bash\nexport BSC_RPC_URL=\"https://bsc-dataseed1.binance.org\"\nexport BSC_CHAIN_ID=56\n\n# PancakeSwap V2 (BSC mainnet)\nexport PANCAKE_ROUTER=\"0x10ED43C718714eb63d5aA57B78B54704E256024E\"\nexport WBNB=\"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"\n```\n\n**Block explorer:** https://bscscan.com\n\n**PancakeSwap UI:** https://pancakeswap.finance/swap?chain=bsc\n\n### Optional: Switch to Testnet\n\nFor testnet (tBNB, tCHR, etc.), override the defaults:\n\n```bash\nexport BSC_RPC_URL=\"https://data-seed-prebsc-1-s1.binance.org:8545\"\nexport BSC_CHAIN_ID=97\nexport PANCAKE_ROUTER=\"0xD99D1c33F9fC3444f8101754aBC46c52416550D1\"\nexport WBNB=\"0xae13d989dac2f0debff460ac112a837c89baa7cd\"\n```\n\n### Prerequisites\n\nThis skill requires **Node.js 18+** and the **ethers** npm package (v6):\n\n```bash\nnpm install ethers\n# or: pnpm add ethers\n```\n\n---\n\n## 1. Wallet Setup — Create Wallet and Save Keys\n\nThe agent needs a local wallet file containing a **private key** and **public address** so it can sign transactions. This file is created once during initial setup and reused for all subsequent operations.\n\n> **⚠️ Security:** The wallet file contains sensitive key material. See the [Security Notes](#7-security-notes) section for encryption and file permission best practices. Only use a dedicated, small-balance wallet — never your main funds.\n\n### Option A: Using Node.js (recommended)\n\nRun this script to generate a new wallet and write it to a file:\n\n```bash\nnode -e \"\nconst fs = require('fs');\nconst path = require('path');\nconst { ethers } = require('ethers');\nconst wallet = ethers.Wallet.createRandom();\nconst dir = process.env.HOME + '/.config/bsc_agent';\nfs.mkdirSync(dir, { recursive: true });\nconst file = dir + '/wallet.json';\nfs.writeFileSync(file, JSON.stringify({\n  privateKey: wallet.privateKey,\n  address: wallet.address,\n  publicKey: wallet.publicKey\n}, null, 2), { mode: 0o600 });\nconsole.log('Wallet saved to ' + file);\nconsole.log('Address: ' + wallet.address);\n\"\n```\n\nDefault file location: `~/.config/bsc_agent/wallet.json`\n\n**File format (wallet.json):**\n\n```json\n{\n  \"privateKey\": \"0x...\",\n  \"address\": \"0x...\",\n  \"publicKey\": \"0x...\"\n}\n```\n\n- **privateKey** — Used to sign transactions. This file is restricted to owner-only access (`chmod 600`). Never log or expose this value.\n- **address** — The agent's BSC account. The user sends BNB/tokens to this address to fund the agent.\n- **publicKey** — Derived from private key. Used optionally for ClawChain EVM event tracking registration.\n\n### Option B: Custom path\n\nTo use a different path, set the environment variable:\n\n```bash\nexport BSC_WALLET_FILE=\"$HOME/.config/bsc_agent/wallet.json\"\n# Then in the script, write to process.env.BSC_WALLET_FILE\n```\n\n### After wallet setup\n\n1. Read `address` and `publicKey` from `wallet.json`.\n2. Tell the user: **My BSC address for top-ups is:** `<address>`\n3. The user must send native BNB (for gas) and any tokens they want the agent to swap to this address.\n4. **(Optional)** Register your BSC public key on ClawChain for EVM event tracking — see [Section 1.5](#15-register-public-key-on-clawchain-optional).\n\n---\n\n## 1.5. Register Public Key on ClawChain (Optional)\n\n> **This step is optional.** It links your BSC wallet public key to your ClawChain agent account to enable tracking EVM events on Chromia. Skip this if you don't need on-chain event tracking.\n\n> **Prerequisite:** You must already have a registered and claimed agent on ClawChain. See the `clawchain` skill for registration instructions.\n\n### Prerequisites\n\n- A registered agent account on ClawChain (Chromia)\n- An authenticated session (FT4 keypair from ClawChain registration)\n- Your `wallet.json` file with `publicKey` (required) and optionally `address`\n- The ClawChain credentials file at `~/.config/clawchain/credentials.json` (created by the `clawchain` skill)\n\n### Environment Variables for ClawChain\n\nThese are the same variables used by the `clawchain` skill — set them if not already configured:\n\n```bash\nexport CLAWCHAIN_BRID=\"9D728CC635A9D33DAABAC8217AA8131997A8CBF946447ED0B98760245CE5207E\"\nexport CLAWCHAIN_NODE=\"https://chromia.01node.com:7740\"\n```\n\n### Registration Steps\n\n#### Option A: Using Chromia CLI\n\n```bash\n# Read wallet info\nWALLET_FILE=\"${BSC_WALLET_FILE:-$HOME/.config/bsc_agent/wallet.json}\"\nPUBLIC_KEY=$(cat $WALLET_FILE | grep -o '\"publicKey\": \"[^\"]*' | cut -d'\"' -f4)\nADDRESS=$(cat $WALLET_FILE | grep -o '\"address\": \"[^\"]*' | cut -d'\"' -f4)\n\n# Register public key on Chromia\nchr tx register_evm_public_key \\\n  \"pancakeswap\" \\\n  \"$PUBLIC_KEY\" \\\n  \"BSC\" \\\n  56 \\\n  \"$ADDRESS\" \\\n  --ft-auth \\\n  --secret ~/.config/clawchain/credentials.json \\\n  -brid $CLAWCHAIN_BRID \\\n  --api-url $CLAWCHAIN_NODE \\\n  --await\n```\n\n**Arguments:** `wallet_type` `public_key` `chain` `network_id` `address`\n\n**Network IDs:**\n- BSC Mainnet: `56`\n- BSC Testnet: `97`\n- Ethereum Mainnet: `1`\n- Ethereum Goerli: `5`\n- Polygon Mainnet: `137`\n\n**Note:** If you don't have an address, use `\"\"` (empty string) for the last parameter.\n\n#### Option B: Using JavaScript/TypeScript\n\nIf you're integrating this into a web application with an authenticated FT4 session:\n\n```javascript\nconst fs = require('fs');\nconst walletFile = process.env.BSC_WALLET_FILE || '~/.config/bsc_agent/wallet.json';\nconst walletData = JSON.parse(fs.readFileSync(walletFile, 'utf8'));\n\n// Assuming you have a Chromia session object (from @chromia/ft4)\nconst result = await session.call({\n  name: 'register_evm_public_key',\n  args: [\n    'pancakeswap',              // wallet_type\n    walletData.publicKey,      // public_key (required)\n    'BSC',                      // chain\n    56,                         // network_id (56 for BSC mainnet, 97 for testnet)\n    walletData.address || \"\"   // address (optional)\n  ]\n});\n\nconsole.log('Public key registered:', result);\n```\n\n### Query Registered Public Keys\n\nTo check which public keys are registered for your agent:\n\n```bash\n# Get all registered public keys for an agent\nchr query get_evm_public_keys 'agent_name=your_agent_name' \\\n  -brid $CLAWCHAIN_BRID --api-url $CLAWCHAIN_NODE\n\n# Get specific public key by wallet type\nchr query get_evm_public_key_by_type \\\n  'agent_name=your_agent_name' \\\n  'wallet_type=pancakeswap' \\\n  -brid $CLAWCHAIN_BRID --api-url $CLAWCHAIN_NODE\n```\n\n### Error Handling\n\n- **\"Public key already registered\"**: The public key is already registered for this agent. Query existing keys to verify.\n- **\"Public key is required for EIF event tracking\"**: You must provide a public key.\n- **\"Invalid public key format\"**: Public key must start with `0x` and be at least 66 characters (0x + 64 hex chars).\n- **\"Agent not found\"**: Ensure your agent account exists on ClawChain.\n- **Authentication errors**: Ensure you have a valid FT4 session authenticated with your Chromia account.\n\n---\n\n## 2. How the User Can Top Up the Agent Account\n\nThe agent does not have an \"account\" on a server — it has a BSC address (from `wallet.json`). Fund the agent by sending BNB and tokens to that address:\n\n### Get BNB for gas and swaps\n\n1. Buy BNB on an exchange or bridge from another chain.\n2. Send **BNB** to the agent address: `<address>` from `wallet.json`.\n3. Add BSC Mainnet in MetaMask (Chain ID 56, RPC above), then transfer BNB to the agent.\n\n### Get tokens\n\n- Send any BEP-20 token to `<address>`. The agent can swap via PancakeSwap if a pair exists (e.g. USDT/BNB, BUSD/BNB).\n\n### Check balance\n\n- **Native (BNB):** `provider.getBalance(address)`\n- **Any BEP-20 token:** call `balanceOf(address)` on the token contract.\n\n---\n\n## 3. Discovering Available Tokens and Swaps\n\nThe agent can work with **any** BEP-20 token and determine **which swaps are possible**. No fixed token list is required.\n\n### Which tokens are available\n\n- **By contract address:** Any BEP-20 token is identified by its contract address. Accept token addresses from the user or from token lists.\n- **Resolve symbol and decimals:** Call the token contract (ERC-20/BEP-20):\n  - `symbol()` → e.g. \"USDT\", \"WBNB\"\n  - `decimals()` → use for amount math and display (e.g. 18 or 6)\n  - `name()` → full name (optional)\n- **Token lists (optional):** PancakeSwap and BSC publish token lists; the agent can also accept any user-provided contract address.\n- **Native gas token:** BNB is the chain native token; the wrapped version is WBNB (address in config). Use WBNB in router paths.\n\n### Which swaps are available\n\n- **Get the Factory:** Call the router's `factory()` (read-only) to get the PancakeSwap V2 Factory address.\n- **Check if a pair exists:** Call `factory.getPair(tokenA, tokenB)`. If the result is the zero address (`0x000...`), no pair exists. Otherwise it is the pair contract address.\n- **Check liquidity:** On the pair contract, call `getReserves()`. If both reserves are > 0, the pair has liquidity and that swap is available.\n- **Quote before swapping:** Use the router's `getAmountsOut(amountIn, path)` (read-only). If the call reverts or returns zero for the output amount, the swap is not feasible (no liquidity or invalid path).\n- **Multi-hop paths:** If there is no direct A–B pair, try a path via WBNB: `[tokenA, WBNB, tokenB]`. Call `getAmountsOut(amountIn, path)`; if it succeeds and returns a positive amount, the swap is available.\n- **Optional:** PancakeSwap API or subgraph can list pairs for a token; the agent may use these to discover pairs in addition to on-chain checks.\n\n---\n\n## 4. Making a Trade (Swap on PancakeSwap)\n\nThe agent uses the private key from `wallet.json` to sign a swap transaction and sends it to BSC.\n\n### PancakeSwap V2 router (BSC mainnet)\n\n| Contract | Address |\n|----------|---------|\n| Router | `0x10ED43C718714eb63d5aA57B78B54704E256024E` |\n| WBNB | `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c` |\n\n### Common swap methods\n\n| Method | Use case |\n|--------|----------|\n| `swapExactETHForTokens` | Swap exact BNB for tokens (min amount out) |\n| `swapExactTokensForETH` | Swap exact tokens for BNB |\n| `swapExactTokensForTokens` | Swap exact token A for token B |\n| `swapTokensForExactTokens` | Swap tokens for exact amount of token B |\n\n### Swap flow (any token pair with liquidity)\n\n1. **Load wallet** from `wallet.json` (privateKey + address).\n2. **Connect** to BSC: `new ethers.JsonRpcProvider(BSC_RPC_URL)` (mainnet: chain id 56).\n3. **Resolve tokens:** Use token contract addresses (from user or discovery). For native BNB use WBNB in the path.\n4. **Check swap availability:** Call router `getAmountsOut(amountIn, path)`. If it reverts or returns zero, try a multi-hop path (e.g. `[tokenA, WBNB, tokenB]`) or inform the user the pair has no liquidity.\n5. **Build path:** e.g. BNB → token: `[WBNB, tokenAddress]`; token → BNB: `[tokenAddress, WBNB]`; token → token: `[tokenA, WBNB, tokenB]` (or direct if pair exists).\n6. **Get router contract** (address above), ABI for `swapExactETHForTokens`, `swapExactTokensForETH`, or `swapExactTokensForTokens`.\n7. **Deadline:** `Math.floor(Date.now() / 1000) + 300` (e.g. 5 minutes).\n8. **amountOutMin:** from `getAmountsOut(amountIn, path)` then apply slippage (e.g. 1% = amountOut * 0.99).\n9. **Sign and send:** For BNB → token use `{ value: amountInWei }`; for token → BNB or token → token, approve router for the token first, then call the swap.\n\n### Slippage\n\n- **amountOutMin** = expected output × (1 - slippage). E.g. 1% slippage → multiply by 0.99.\n- For volatile pairs use 2–5%.\n\n### Token decimals\n\n- BNB has 18 decimals. 1 BNB = `1e18` wei.\n- Many BEP-20 tokens use 18 decimals; USDT/USDC often use 6. Check the token contract or docs.\n\n---\n\n## 5. Command / Script Patterns for the Agent\n\n### Read wallet (do not expose private key in logs)\n\n- Read `~/.config/bsc_agent/wallet.json` (or `BSC_WALLET_FILE`).\n- Use `address` when telling the user where to top up.\n- Use `privateKey` only inside the signing process (ethers Wallet). **Never log or print the private key.**\n\n### Execute swap (high level)\n\n1. Load `wallet.json`.\n2. Create `ethers.Wallet(privateKey, provider)`.\n3. Build router call (e.g. `swapExactETHForTokens`) with path, deadline, amountOutMin.\n4. Send transaction: `tx = await router.swapExactETHForTokens(...); await tx.wait()`.\n5. Return tx hash to user: `https://bscscan.com/tx/<hash>`.\n\n### Get quote before swapping\n\n- Call router `getAmountsOut(amountIn, path)` (read-only) to get expected `amountOut`, then compute `amountOutMin` with slippage.\n\n---\n\n## 6. Example Token Addresses (BSC Mainnet)\n\n| Symbol | Address | Notes |\n|--------|---------|--------|\n| WBNB | `0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c` | Native wrapped; use in paths |\n| USDT | `0x55d398326f99059fF775485246999027B3197955` | Stablecoin |\n| BUSD | `0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56` | Stablecoin |\n\n**Do not limit to these.** The agent should accept any BEP-20 address and discover availability via `getPair` / `getReserves` and `getAmountsOut` (see §3). If a pair has no liquidity, add liquidity via the PancakeSwap UI or use another token pair.\n\n---\n\n## 7. Security Notes\n\n### File Permissions\n\n- **wallet.json** must be restricted to owner-only access. The wallet creation script sets `mode: 0o600` automatically. Verify with:\n  ```bash\n  chmod 600 ~/.config/bsc_agent/wallet.json\n  ls -la ~/.config/bsc_agent/wallet.json\n  # Should show: -rw-------\n  ```\n\n### Dedicated Wallet\n\n- Use this wallet **only** for the agent and only with amounts you accept to lose if the machine or file is compromised.\n- **Do not reuse a wallet that holds large funds elsewhere.** Create a fresh, dedicated wallet.\n- For testnet usage, no real funds are at risk.\n\n### Key Handling Best Practices\n\n- **Never log the private key** to console, files, or monitoring systems.\n- **Never transmit the private key** over the network. All signing happens locally.\n- The agent reads the private key only to construct an `ethers.Wallet` instance for signing. It is never sent to any remote endpoint.\n- Consider using **encrypted keystores** (ethers.js `Wallet.encrypt()`) for production use. The agent would prompt for a password to decrypt at startup.\n\n### Optional: Encrypted Keystore\n\nFor enhanced security, use ethers.js encrypted wallet format instead of plaintext:\n\n```javascript\n// Create encrypted wallet (during setup)\nconst encrypted = await wallet.encrypt(\"your-password\");\nfs.writeFileSync(file, encrypted, { mode: 0o600 });\n\n// Load encrypted wallet (during operations)\nconst wallet = await ethers.Wallet.fromEncryptedJson(\n  fs.readFileSync(file, 'utf8'),\n  \"your-password\"\n);\n```\n\n---\n\n## 8. Errors\n\n| Error | Meaning / action |\n|-------|------------------|\n| insufficient funds | Not enough BNB for gas or not enough token/BNB for the swap. User should top up. |\n| execution reverted: PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT | Slippage too low; increase or retry. |\n| execution reverted: PancakeRouter: EXPIRED | Deadline passed; rebuild tx with new deadline. |\n| nonce too low | Reuse of nonce; wait and retry or refresh nonce from chain. |\n\n---\n\n## 9. Links\n\n- PancakeSwap (BSC mainnet): https://pancakeswap.finance/swap?chain=bsc  \n- PancakeSwap V2 docs: https://docs.pancakeswap.finance/developers/smart-contracts/pancakeswap-exchange/v2-contracts  \n- BSC explorer: https://bscscan.com  \n","tags":{"latest":"1.0.0"},"stats":{"comments":0,"downloads":1085,"installsAllTime":41,"installsCurrent":0,"stars":0,"versions":1},"createdAt":1771420900945,"updatedAt":1779077059106},"latestVersion":{"version":"1.0.0","createdAt":1771420900945,"changelog":"**Major update: PancakeSwap skill for BSC rewritten, expands feature coverage and setup clarity.**\n\n- Adds wallet creation and management, including security best practices and file path configuration.\n- Supports BEP-20 token discovery, liquidity checks, and balance queries.\n- Implements swap execution via PancakeSwap V2 with slippage protection.\n- Environment variables have clear defaults for mainnet and testnet, with setup examples.\n- Clarifies file access, credentials, and dependencies.\n- Documents optional integration with ClawChain for event tracking.\n- Emphasizes transparency and security throughout configuration and usage.","license":null},"metadata":null,"owner":{"handle":"kj-script","userId":"s170f5pwytkfa8ctkn02pdnkbn885yxy","displayName":"Keti Yohannes","image":"https://avatars.githubusercontent.com/u/38397885?v=4"},"moderation":null}