diff --git a/README.md b/README.md index 4d2d448..af6336a 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ _Maintained by the Bankr team._ ## Installation +### Claude Code + First, add the marketplace: ```bash @@ -63,10 +65,18 @@ claude plugin install bankr-agent-dev@bankr-claude-plugins claude plugin install bankr-x402-sdk-dev@bankr-claude-plugins ``` +### Other Coding Tools (Cursor, OpenCode, Gemini CLI, Antigravity, etc.) + +Only skills are compatible with other platforms. Agents, commands, hooks, and MCP servers require Claude Code. + +```bash +bunx skills add BankrBot/claude-plugins +``` + ## Requirements - Claude Code CLI -- Node.js 18+ +- Node.js 20+ - USDC on Base (for x402 payments) ## Links diff --git a/bankr-agent-dev/.claude-plugin/plugin.json b/bankr-agent-dev/.claude-plugin/plugin.json index 64133f9..aca15bd 100644 --- a/bankr-agent-dev/.claude-plugin/plugin.json +++ b/bankr-agent-dev/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "bankr-agent-dev", - "version": "0.1.1", + "version": "1.0.0", "description": "Developer toolkit for building applications on top of the Bankr Agent API - scaffold projects, understand API patterns, and build integrations", "author": { "name": "Bankr Team" diff --git a/bankr-agent-dev/README.md b/bankr-agent-dev/README.md index 31784a9..4304449 100644 --- a/bankr-agent-dev/README.md +++ b/bankr-agent-dev/README.md @@ -14,15 +14,25 @@ This plugin helps developers scaffold and build applications that interact with ## Prerequisites - Bankr API key (get one at https://bankr.bot/api) -- Node.js 18+ and npm/bun +- Node.js 20+ and npm/bun ## Installation +### Claude Code + ```bash claude plugin marketplace add BankrBot/claude-plugins claude plugin install bankr-agent-dev@bankr-claude-plugins ``` +### Other Coding Tools (Cursor, OpenCode, Gemini CLI, Antigravity, etc.) + +Only skills are compatible with other platforms. Agents, commands, hooks, and MCP servers require Claude Code. + +```bash +bunx skills add BankrBot/claude-plugins +``` + ## Usage ### Scaffold a New Project diff --git a/bankr-agent-dev/commands/scaffold.md b/bankr-agent-dev/commands/scaffold.md index 2ddaeab..06058a5 100644 --- a/bankr-agent-dev/commands/scaffold.md +++ b/bankr-agent-dev/commands/scaffold.md @@ -10,359 +10,53 @@ Create a complete TypeScript/Node.js project scaffold for building on the Bankr ## Process -1. **Determine project type** - If `$ARGUMENTS` specifies a type, use it. Otherwise, ask the user: +1. **Determine project type** - If `$ARGUMENTS` specifies a type, use it. Otherwise, ask the user. -Available project types: -- **bot** - Automated trading bot, price monitor, alert system, or scheduled task -- **web-service** - HTTP API that wraps or extends Bankr functionality -- **dashboard** - Web UI for portfolio tracking, market analysis, or monitoring -- **cli** - Command-line tool for Bankr operations + Load the `bankr-project-templates` skill for available types: + - **bot** - Automated trading bot, price monitor, alert system, scheduled task + - **web-service** - HTTP API that wraps or extends Bankr functionality + - **dashboard** - Web UI for portfolio tracking, market analysis, monitoring + - **cli** - Command-line tool for Bankr operations 2. **Ask for project details**: - Project name (kebab-case, e.g., `my-trading-bot`) - Brief description of what it will do - Any specific Bankr operations it will use (trading, prices, polymarket, defi) - -3. **Create project structure** using the appropriate template below. - -4. **Explain next steps** - How to set up API key, install dependencies, and run. - ---- - -## Project Templates - -### Bot Template - -For automated bots, monitors, and scheduled tasks: - -``` -{project-name}/ -├── package.json -├── tsconfig.json -├── .env.example -├── .gitignore -├── README.md -├── src/ -│ ├── index.ts # Main entry point with scheduler -│ ├── bankr-client.ts # Bankr API client -│ ├── types.ts # TypeScript interfaces -│ └── config.ts # Configuration loading -└── scripts/ - └── run.sh # Convenience script -``` - -**Key features:** -- Polling loop with configurable interval -- Status update streaming -- Error handling and retries -- Environment-based configuration - -### Web Service Template - -For HTTP APIs that extend Bankr: - -``` -{project-name}/ -├── package.json -├── tsconfig.json -├── .env.example -├── .gitignore -├── README.md -├── src/ -│ ├── index.ts # Server entry point -│ ├── server.ts # Express/Fastify server setup -│ ├── routes/ -│ │ ├── health.ts # Health check endpoint -│ │ └── bankr.ts # Bankr proxy/extension routes -│ ├── bankr-client.ts # Bankr API client -│ ├── types.ts # TypeScript interfaces -│ └── config.ts # Configuration loading -└── scripts/ - └── run.sh -``` - -**Key features:** -- REST API endpoints -- Request validation -- Async job handling -- Webhook support for job completion - -### Dashboard Template - -For web UIs with frontend and backend: - -``` -{project-name}/ -├── package.json -├── tsconfig.json -├── .env.example -├── .gitignore -├── README.md -├── server/ -│ ├── index.ts # Backend server -│ ├── bankr-client.ts # Bankr API client -│ ├── routes/ -│ │ └── api.ts # API routes for frontend -│ └── types.ts -├── public/ -│ ├── index.html # Main HTML page -│ ├── styles.css # Basic styles -│ └── app.js # Frontend JavaScript -└── scripts/ - └── run.sh -``` - -**Key features:** -- Simple HTML/CSS/JS frontend (no build step required) -- Backend API for Bankr operations -- Real-time status updates via polling -- Portfolio/market data display - -### CLI Template - -For command-line tools: - -``` -{project-name}/ -├── package.json -├── tsconfig.json -├── .env.example -├── .gitignore -├── README.md -├── src/ -│ ├── index.ts # CLI entry with commander.js -│ ├── commands/ -│ │ ├── trade.ts # Trading commands -│ │ ├── price.ts # Price query commands -│ │ └── status.ts # Job status commands -│ ├── bankr-client.ts # Bankr API client -│ └── types.ts -└── scripts/ - └── run.sh -``` - -**Key features:** -- Commander.js CLI framework -- Subcommands for different operations -- Interactive prompts where needed -- Progress indicators during polling - ---- - -## Common Files - -### package.json - -```json -{ - "name": "{project-name}", - "version": "0.1.1", - "description": "{description}", - "type": "module", - "main": "dist/index.js", - "scripts": { - "build": "tsc", - "start": "node dist/index.js", - "dev": "tsx src/index.ts" - }, - "dependencies": { - "dotenv": "^16.3.1" - }, - "devDependencies": { - "@types/node": "^20.10.0", - "tsx": "^4.7.0", - "typescript": "^5.3.0" - } -} -``` - -Add framework-specific dependencies based on project type: -- **web-service**: Add `express` or `fastify` -- **cli**: Add `commander` -- **dashboard**: Add `express` for backend - -### tsconfig.json - -```json -{ - "compilerOptions": { - "target": "ES2022", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "outDir": "./dist", - "rootDir": "./src", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "declaration": true - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] -} -``` - -### .env.example - -``` -BANKR_API_KEY=bk_your_api_key_here -BANKR_API_URL=https://api.bankr.bot -``` - -### .gitignore - -``` -node_modules/ -dist/ -.env -*.log -``` - -### bankr-client.ts (Core Module) - -This is the essential Bankr API client that all project types share: - -```typescript -import "dotenv/config"; - -const API_URL = process.env.BANKR_API_URL || "https://api.bankr.bot"; -const API_KEY = process.env.BANKR_API_KEY; - -// Types -export interface JobStatusResponse { - success: boolean; - jobId: string; - status: "pending" | "processing" | "completed" | "failed" | "cancelled"; - prompt: string; - response?: string; - transactions?: Transaction[]; - richData?: RichData[]; - statusUpdates?: StatusUpdate[]; - error?: string; - createdAt: string; - completedAt?: string; - processingTime?: number; -} - -export interface Transaction { - type: string; - metadata?: { - humanReadableMessage?: string; - inputTokenTicker?: string; - outputTokenTicker?: string; - inputTokenAmount?: string; - outputTokenAmount?: string; - transaction?: { - chainId: number; - to: string; - data: string; - gas?: string; - value?: string; - }; - }; -} - -export interface StatusUpdate { - message: string; - timestamp: string; -} - -export interface RichData { - type: string; - base64?: string; - url?: string; -} - -// API Functions -export async function submitPrompt(prompt: string): Promise<{ jobId: string }> { - if (!API_KEY) throw new Error("BANKR_API_KEY not set"); - - const response = await fetch(`${API_URL}/agent/prompt`, { - method: "POST", - headers: { - "x-api-key": API_KEY, - "Content-Type": "application/json", - }, - body: JSON.stringify({ prompt }), - }); - - if (!response.ok) { - throw new Error(`API error: ${response.status} - ${await response.text()}`); - } - - const data = await response.json(); - if (!data.success) throw new Error(data.error || "Failed to submit prompt"); - return { jobId: data.jobId }; -} - -export async function getJobStatus(jobId: string): Promise { - if (!API_KEY) throw new Error("BANKR_API_KEY not set"); - - const response = await fetch(`${API_URL}/agent/job/${jobId}`, { - headers: { "x-api-key": API_KEY }, - }); - - if (!response.ok) { - throw new Error(`API error: ${response.status} - ${await response.text()}`); - } - - return response.json(); -} - -export async function waitForCompletion( - jobId: string, - onProgress?: (msg: string) => void -): Promise { - let lastUpdateCount = 0; - - for (let i = 0; i < 120; i++) { - const status = await getJobStatus(jobId); - - // Report new status updates - if (onProgress && status.statusUpdates) { - for (let j = lastUpdateCount; j < status.statusUpdates.length; j++) { - onProgress(status.statusUpdates[j].message); - } - lastUpdateCount = status.statusUpdates.length; - } - - if (["completed", "failed", "cancelled"].includes(status.status)) { - return status; - } - - await new Promise((r) => setTimeout(r, 2000)); - } - - throw new Error("Job timed out"); -} - -export async function execute( - prompt: string, - onProgress?: (msg: string) => void -): Promise { - const { jobId } = await submitPrompt(prompt); - onProgress?.(`Job submitted: ${jobId}`); - return waitForCompletion(jobId, onProgress); -} -``` - ---- + - Package manager preference: **bun** (recommended - faster) or **npm** + +3. **Create project structure**: + - Load `bankr-project-templates` skill for the directory structure + - Load `bankr-client-patterns` skill for common files and client code + - Create all directories using `mkdir -p` + - Write each file using the Write tool + - Customize based on user's description + +4. **Explain next steps**: + - How to get a Bankr API key (https://bankr.bot/api) + - How to run the project (use selected package manager: `bun install && bun dev` or `npm install && npm run dev`) + - What to customize first based on their use case + +## Skills to Load + +**Core Skills (always load):** +- `bankr-project-templates` - Directory structures for each project type +- `bankr-client-patterns` - bankr-client.ts and common files (package.json, tsconfig.json, .env.example, .gitignore) +- `bankr-api-basics` - API documentation for reference + +**Capability Skills (load based on project purpose):** +- `bankr-token-trading` - For trading bots: prompt templates, swap response handling +- `bankr-transfers` - For payment bots: recipient resolution, transfer patterns +- `bankr-polymarket` - For prediction market bots: betting API, position tracking +- `bankr-leverage-trading` - For leverage bots: Avantis patterns, position management +- `bankr-nft-operations` - For NFT bots: OpenSea browsing, purchase automation +- `bankr-portfolio` - For dashboards: balance aggregation, portfolio tracking +- `bankr-market-research` - For price bots: monitoring patterns, alert systems +- `bankr-automation` - For order bots: limit orders, DCA, TWAP implementation +- `bankr-token-deployment` - For token launchers: Clanker integration, fee claiming ## Implementation Notes -When scaffolding: - -1. **Create all directories first** using mkdir -p -2. **Write each file** using the Write tool -3. **Customize based on user's description** - adjust the example code to match their use case -4. **Include helpful comments** in the generated code -5. **Generate a README.md** with: - - Project description - - Setup instructions (npm install, configure .env) - - Usage examples - - Bankr API reference link - -After scaffolding, explain: -- How to get a Bankr API key (https://bankr.bot/api) -- How to run the project (`npm install && npm run dev`) -- What to customize first based on their use case +- Create all directories first using `mkdir -p` +- Write each file using the Write tool +- Include helpful comments in generated code +- Generate a README.md with setup instructions and usage examples diff --git a/bankr-agent-dev/skills/bankr-api-basics/SKILL.md b/bankr-agent-dev/skills/bankr-api-basics/SKILL.md index 0ecd01a..4e01ca0 100644 --- a/bankr-agent-dev/skills/bankr-api-basics/SKILL.md +++ b/bankr-agent-dev/skills/bankr-api-basics/SKILL.md @@ -1,7 +1,7 @@ --- -name: Bankr API Basics -description: Provides Bankr Agent API documentation including endpoints, job patterns, and TypeScript interfaces. Triggered by questions about "Bankr API", "Bankr Agent API", "how does Bankr work", "Bankr job status", "Bankr response format", or "building on Bankr". -version: 0.1.0 +name: Bankr Dev - API Basics +description: This skill should be used when the user asks about "Bankr API", "Bankr Agent API", "how does Bankr work", "Bankr job status", "Bankr response format", or "building on Bankr". Provides endpoint documentation, job patterns, and TypeScript interfaces. +version: 1.0.0 --- # Bankr Agent API Essentials diff --git a/bankr-agent-dev/skills/bankr-automation/SKILL.md b/bankr-agent-dev/skills/bankr-automation/SKILL.md new file mode 100644 index 0000000..4897802 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-automation/SKILL.md @@ -0,0 +1,67 @@ +--- +name: Bankr Dev - Automation +description: This skill should be used when building automated trading systems, implementing limit orders, or adding DCA/TWAP functionality. Covers limit orders, stop losses, DCA schedules, and TWAP execution. +version: 1.0.0 +--- + +# Automation Capability + +Create and manage automated orders via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Limit buy | `Set a limit order to buy ETH at $3,000` | +| Limit buy with amount | `Set a limit order to buy $500 of ETH at $3,000` | +| Limit sell | `Limit sell my ETH when it hits $4,000` | +| Stop loss (price) | `Set stop loss for my ETH at $2,800` | +| Stop loss (percent) | `Stop loss: sell ETH if it drops 10%` | +| DCA | `DCA $100 into ETH every week` | +| DCA with duration | `DCA $50 into BTC every day for 1 month` | +| TWAP buy | `TWAP buy $5000 of ETH over 24 hours` | +| TWAP sell | `TWAP sell 1 ETH over 4 hours` | +| Scheduled command | `Every Monday, buy $100 of ETH` | +| View automations | `Show my automations` | +| View limit orders | `What limit orders do I have?` | +| Cancel automation | `Cancel automation abc123` | +| Cancel all | `Cancel all my automations` | + +## Prompt Patterns + +``` +Set a limit order to buy {token} at {price} +Set stop loss for my {token} at {price|percent} +DCA {amount} into {token} {frequency} [for {duration}] +TWAP buy {amount} of {token} over {duration} +Show my automations +Cancel automation {id} +``` + +**Frequencies:** every hour, every day, every week, every month + +**Supported chains:** Base, Polygon, Ethereum (EVM), Solana (Jupiter triggers) + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Create limit order +await execute("Set a limit order to buy $500 of ETH at $3,000"); + +// Create DCA +await execute("DCA $100 into ETH every week for 3 months"); + +// Create TWAP +await execute("TWAP buy $5000 of ETH over 24 hours"); + +// View automations +await execute("Show my automations"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-token-trading` - Immediate trades diff --git a/bankr-agent-dev/skills/bankr-client-patterns/SKILL.md b/bankr-agent-dev/skills/bankr-client-patterns/SKILL.md new file mode 100644 index 0000000..4e466c9 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-client-patterns/SKILL.md @@ -0,0 +1,508 @@ +--- +name: Bankr Dev - Client Patterns +description: This skill should be used when the user asks to "implement Bankr client", "write bankr-client.ts", "create API client for Bankr", "common files for Bankr project", "package.json for Bankr", "tsconfig for Bankr", "Bankr TypeScript patterns", "Bankr response types", or needs the reusable client code and common project files for Bankr API integrations. +version: 1.0.0 +--- + +# Bankr Client Patterns + +Reusable client code and common files for Bankr API projects. + +## bankr-client.ts + +The core API client module for all Bankr projects: + +```typescript +import "dotenv/config"; + +const API_URL = process.env.BANKR_API_URL || "https://api.bankr.bot"; +const API_KEY = process.env.BANKR_API_KEY; + +// ============================================ +// Types +// ============================================ + +export type JobStatus = "pending" | "processing" | "completed" | "failed" | "cancelled"; + +export interface JobStatusResponse { + success: boolean; + jobId: string; + status: JobStatus; + prompt: string; + response?: string; + transactions?: Transaction[]; + richData?: RichData[]; + statusUpdates?: StatusUpdate[]; + error?: string; + createdAt: string; + startedAt?: string; + completedAt?: string; + cancelledAt?: string; + processingTime?: number; + cancellable?: boolean; +} + +export interface StatusUpdate { + message: string; + timestamp: string; +} + +// Transaction types +export type Transaction = + | SwapTransaction + | ApprovalTransaction + | TransferErc20Transaction + | TransferEthTransaction + | ConvertEthToWethTransaction + | ConvertWethToEthTransaction + | TransferNftTransaction + | MintManifoldNftTransaction + | MintSeaDropNftTransaction + | BuyNftTransaction + | AvantisTradeTransaction + | SwapCrossChainTransaction + | ManageBankrStakingTransaction; + +interface BaseTransactionMetadata { + __ORIGINAL_TX_DATA__: { + chain: string; + humanReadableMessage: string; + inputTokenAddress: string; + inputTokenAmount: string; + inputTokenTicker: string; + outputTokenAddress: string; + outputTokenTicker: string; + receiver: string; + }; + transaction: { + chainId: number; + to: string; + data: string; + gas: string; + gasPrice: string; + value: string; + }; +} + +export interface SwapTransaction { + type: "swap"; + metadata: BaseTransactionMetadata & { + approvalRequired?: boolean; + approvalTx?: { to: string; data: string }; + permit2?: object; + }; +} + +export interface ApprovalTransaction { + type: "approval"; + metadata: BaseTransactionMetadata; +} + +export interface TransferErc20Transaction { + type: "transfer_erc20"; + metadata: BaseTransactionMetadata; +} + +export interface TransferEthTransaction { + type: "transfer_eth"; + metadata: BaseTransactionMetadata; +} + +export interface ConvertEthToWethTransaction { + type: "convert_eth_to_weth"; + metadata: BaseTransactionMetadata; +} + +export interface ConvertWethToEthTransaction { + type: "convert_weth_to_eth"; + metadata: BaseTransactionMetadata; +} + +export interface TransferNftTransaction { + type: "transfer_nft"; + metadata: BaseTransactionMetadata; +} + +export interface MintManifoldNftTransaction { + type: "mint_manifold_nft"; + metadata: BaseTransactionMetadata; +} + +export interface MintSeaDropNftTransaction { + type: "mint_seadrop_nft"; + metadata: BaseTransactionMetadata; +} + +export interface BuyNftTransaction { + type: "buy_nft"; + metadata: BaseTransactionMetadata; +} + +export interface AvantisTradeTransaction { + type: "avantisTrade"; + metadata: { + chainId: number; + description: string; + to: string; + data: string; + value?: string; + }; +} + +export interface SwapCrossChainTransaction { + type: "swapCrossChain"; + metadata: { + chainId: number; + description: string; + to: string; + data: string; + value: string; + }; +} + +export interface ManageBankrStakingTransaction { + type: "manage_bankr_staking"; + metadata: { + chainId: number; + description: string; + to: string; + data: string; + value?: string; + }; +} + +// Rich data types +export type RichData = SocialCard | Chart; + +export interface SocialCard { + type: "social-card"; + variant: "analysis"; + text: string; +} + +export interface Chart { + type: "chart"; + url: string; +} + +// ============================================ +// API Functions +// ============================================ + +export async function submitPrompt(prompt: string): Promise<{ jobId: string }> { + if (!API_KEY) { + throw new Error("BANKR_API_KEY not set. Get one at https://bankr.bot/api"); + } + + const response = await fetch(`${API_URL}/agent/prompt`, { + method: "POST", + headers: { + "x-api-key": API_KEY, + "Content-Type": "application/json", + }, + body: JSON.stringify({ prompt }), + }); + + if (!response.ok) { + const text = await response.text(); + throw new Error(`API error ${response.status}: ${text}`); + } + + const data = await response.json(); + if (!data.success) { + throw new Error(data.error || "Failed to submit prompt"); + } + + return { jobId: data.jobId }; +} + +export async function getJobStatus(jobId: string): Promise { + if (!API_KEY) { + throw new Error("BANKR_API_KEY not set"); + } + + const response = await fetch(`${API_URL}/agent/job/${jobId}`, { + headers: { "x-api-key": API_KEY }, + }); + + if (!response.ok) { + const text = await response.text(); + throw new Error(`API error ${response.status}: ${text}`); + } + + return response.json(); +} + +export async function cancelJob(jobId: string): Promise { + if (!API_KEY) { + throw new Error("BANKR_API_KEY not set"); + } + + const response = await fetch(`${API_URL}/agent/job/${jobId}/cancel`, { + method: "POST", + headers: { + "x-api-key": API_KEY, + "Content-Type": "application/json", + }, + }); + + if (!response.ok) { + const text = await response.text(); + throw new Error(`API error ${response.status}: ${text}`); + } + + return response.json(); +} + +export async function waitForCompletion( + jobId: string, + onProgress?: (message: string) => void, + options?: { pollInterval?: number; maxAttempts?: number } +): Promise { + const pollInterval = options?.pollInterval || 2000; + const maxAttempts = options?.maxAttempts || 150; // 5 minutes max + let lastUpdateCount = 0; + + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const status = await getJobStatus(jobId); + + // Report new status updates + if (onProgress && status.statusUpdates) { + for (let i = lastUpdateCount; i < status.statusUpdates.length; i++) { + onProgress(status.statusUpdates[i].message); + } + lastUpdateCount = status.statusUpdates.length; + } + + // Check for terminal states + if (["completed", "failed", "cancelled"].includes(status.status)) { + return status; + } + + await new Promise((resolve) => setTimeout(resolve, pollInterval)); + } + + throw new Error("Job timed out after maximum attempts"); +} + +/** + * Execute a Bankr prompt and wait for completion + * Convenience function that combines submit + poll + */ +export async function execute( + prompt: string, + onProgress?: (message: string) => void +): Promise { + const { jobId } = await submitPrompt(prompt); + onProgress?.(`Job submitted: ${jobId}`); + return waitForCompletion(jobId, onProgress); +} +``` + +--- + +## Common Files + +### package.json + +Base package.json for all Bankr projects: + +```json +{ + "name": "{project-name}", + "version": "0.1.0", + "description": "{description}", + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "dev": "tsx src/index.ts" + }, + "dependencies": { + "dotenv": "^16.3.1" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "tsx": "^4.7.0", + "typescript": "^5.3.0" + } +} +``` + +#### Framework-Specific Dependencies + +Add based on project template: + +**Web Service (Express):** +```json +"dependencies": { + "express": "^4.18.0" +}, +"devDependencies": { + "@types/express": "^4.17.21" +} +``` + +**Web Service (Fastify):** +```json +"dependencies": { + "fastify": "^4.25.0" +} +``` + +**CLI:** +```json +"dependencies": { + "commander": "^12.0.0" +} +``` + +--- + +### tsconfig.json + +TypeScript configuration: + +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +--- + +### .env.example + +Environment variables template: + +```bash +# Bankr API Configuration +BANKR_API_KEY=bk_your_api_key_here +BANKR_API_URL=https://api.bankr.bot + +# Optional: Wallet address for context +BANKR_WALLET_ADDRESS=0x... +``` + +--- + +### .gitignore + +Standard ignore patterns: + +``` +# Dependencies +node_modules/ + +# Build output +dist/ + +# Environment +.env +.env.local +.env.*.local + +# Logs +*.log +npm-debug.log* + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Testing +coverage/ +``` + +--- + +## Usage Patterns + +### Basic Usage + +```typescript +import { execute } from "./bankr-client"; + +const result = await execute("What is the price of ETH?", (msg) => { + console.log("Progress:", msg); +}); + +console.log(result.response); +``` + +### With Error Handling + +```typescript +import { execute } from "./bankr-client"; + +try { + const result = await execute("Buy $50 of ETH on Base"); + + if (result.status === "completed") { + console.log("Success:", result.response); + + // Handle transactions + if (result.transactions) { + for (const tx of result.transactions) { + console.log(`${tx.type}:`, tx.metadata.__ORIGINAL_TX_DATA__?.humanReadableMessage); + } + } + } else if (result.status === "failed") { + console.error("Failed:", result.error); + } +} catch (error) { + console.error("Error:", error.message); +} +``` + +### Manual Control + +```typescript +import { submitPrompt, waitForCompletion, cancelJob } from "./bankr-client"; + +// Submit +const { jobId } = await submitPrompt("Analyze ETH market"); + +// Set up timeout +const timeout = setTimeout(() => { + cancelJob(jobId); +}, 120000); + +// Wait with custom options +const result = await waitForCompletion(jobId, console.log, { + pollInterval: 2000, + maxAttempts: 60, +}); + +clearTimeout(timeout); +``` + +--- + +## API Reference + +Consult the `bankr-api-basics` skill for: +- Complete endpoint documentation +- Authentication details +- Response field descriptions +- Error codes and handling diff --git a/bankr-agent-dev/skills/bankr-leverage-trading/SKILL.md b/bankr-agent-dev/skills/bankr-leverage-trading/SKILL.md new file mode 100644 index 0000000..3892720 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-leverage-trading/SKILL.md @@ -0,0 +1,60 @@ +--- +name: Bankr Dev - Leverage Trading +description: This skill should be used when building perpetual trading bots, implementing leverage functionality, or adding position management. Covers Avantis integration, long/short positions, and risk controls. +version: 1.0.0 +--- + +# Leverage Trading Capability + +Trade perpetuals with leverage via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Open long | `Open a 5x long on ETH with $100` | +| Open short | `Open a 3x short on BTC with $50` | +| Long with stop loss | `Open a 5x long on ETH with $100, stop loss at -10%` | +| Long with take profit | `Open a 5x long on ETH with $100, take profit at +20%` | +| Full risk management | `Open a 5x long on ETH with $100, stop loss at -10%, take profit at +20%` | +| View positions | `Show my Avantis positions` | +| Close position | `Close my ETH long position` | +| Close all | `Close all my Avantis positions` | +| Check PnL | `Check my PnL on Avantis` | + +## Prompt Patterns + +``` +Open a {leverage}x {long|short} on {asset} with {collateral} +Open a {leverage}x long on {asset} with {collateral}, stop loss at {price|percent} +Close my {asset} {long|short} position +Show my Avantis positions +``` + +**Supported assets:** +- Crypto: BTC, ETH, SOL, ARB, AVAX, BNB, DOGE, LINK, OP, MATIC +- Forex: EUR/USD, GBP/USD, USD/JPY, AUD/USD, USD/CAD +- Commodities: Gold, Silver, Oil, Natural Gas + +**Chain:** Base + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Open leveraged position +await execute("Open a 5x long on ETH with $100, stop loss at -10%"); + +// Check positions +await execute("Show my Avantis positions"); + +// Close position +await execute("Close my ETH long position"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-market-research` - Price data for trading decisions diff --git a/bankr-agent-dev/skills/bankr-market-research/SKILL.md b/bankr-agent-dev/skills/bankr-market-research/SKILL.md new file mode 100644 index 0000000..54acf95 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-market-research/SKILL.md @@ -0,0 +1,71 @@ +--- +name: Bankr Dev - Market Research +description: This skill should be used when building market data displays, implementing price feeds, or adding technical analysis. Covers prices, market caps, technical analysis, sentiment, and trending tokens. +version: 1.0.0 +--- + +# Market Research Capability + +Query market data and analysis via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Token price | `What's the price of ETH?` | +| Market data | `Show me BTC market data` | +| Market cap | `What's the market cap of SOL?` | +| 24h volume | `What's the 24h volume for ETH?` | +| Holder count | `How many holders does BNKR have?` | +| Technical analysis | `Do technical analysis on BTC` | +| RSI | `What's the RSI for ETH?` | +| Price action | `Analyze SOL price action` | +| Sentiment | `What's the sentiment on ETH?` | +| Social mentions | `Check social mentions for DOGE` | +| Price chart | `Show ETH price chart` | +| Chart with period | `Show BTC price chart for 30d` | +| Trending tokens | `What tokens are trending today?` | +| Top gainers | `Show top gainers today` | +| Top losers | `Show top losers today` | +| Trending by chain | `What's trending on Base?` | +| Compare tokens | `Compare ETH vs SOL` | + +## Prompt Patterns + +``` +What's the price of {token}? +Show me {token} market data +Do technical analysis on {token} +What's the sentiment on {token}? +Show {token} price chart [for {period}] +What tokens are trending today? +Compare {token1} vs {token2} +``` + +**Chart periods:** 1d, 7d, 30d, 90d, 1y + +**Supported chains:** All chains (data aggregated from multiple sources) + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Price check +await execute("What's the price of ETH?"); + +// Technical analysis +await execute("Do technical analysis on BTC"); + +// Sentiment +await execute("What's the sentiment on SOL?"); + +// Trending +await execute("What tokens are trending today?"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-token-trading` - Execute trades based on research diff --git a/bankr-agent-dev/skills/bankr-nft-operations/SKILL.md b/bankr-agent-dev/skills/bankr-nft-operations/SKILL.md new file mode 100644 index 0000000..0624152 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-nft-operations/SKILL.md @@ -0,0 +1,57 @@ +--- +name: Bankr Dev - NFT Operations +description: This skill should be used when building NFT marketplace integrations, implementing collection browsing, or adding floor price tracking. Covers OpenSea integration, floor prices, and NFT purchases. +version: 1.0.0 +--- + +# NFT Operations Capability + +Interact with NFT marketplaces via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Search collection | `Find NFTs from Pudgy Penguins` | +| Trending NFTs | `Show me trending NFT collections` | +| Floor price | `What's the floor price for Azuki?` | +| Cheapest listings | `Show the 5 cheapest NFTs in BAYC` | +| Listings under price | `Find NFT listings under 5 ETH in CryptoPunks` | +| Buy floor | `Buy the floor NFT from Pudgy Penguins` | +| Buy by URL | `Buy this NFT: https://opensea.io/...` | +| Buy with budget | `Buy an Azuki NFT under 10 ETH` | +| View holdings | `Show my NFTs` | +| Holdings by chain | `Show my NFTs on Base` | + +## Prompt Patterns + +``` +What's the floor price for {collection}? +Buy the floor NFT from {collection} +Show the {count} cheapest NFTs in {collection} +Buy this NFT: {opensea_url} +Show my NFTs [on {chain}] +``` + +**Supported chains:** Base, Ethereum, Polygon (and other EVM chains) + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Check floor price +await execute("What's the floor price for Pudgy Penguins?"); + +// Buy floor NFT +await execute("Buy the floor NFT from Azuki"); + +// View holdings +await execute("Show my NFTs on Ethereum"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-portfolio` - Check ETH balance before purchases diff --git a/bankr-agent-dev/skills/bankr-polymarket/SKILL.md b/bankr-agent-dev/skills/bankr-polymarket/SKILL.md new file mode 100644 index 0000000..71ac137 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-polymarket/SKILL.md @@ -0,0 +1,55 @@ +--- +name: Bankr Dev - Polymarket +description: This skill should be used when building prediction market integrations, implementing betting functionality, or querying Polymarket odds. Covers market search, odds checking, and position management. +version: 1.0.0 +--- + +# Polymarket Capability + +Interact with Polymarket prediction markets via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Search markets | `Search Polymarket for election` | +| Trending markets | `What prediction markets are trending?` | +| Check odds | `What are the odds Trump wins?` | +| Market details | `Show details for the Super Bowl market` | +| Bet Yes | `Bet $10 on Yes for the election market` | +| Bet No | `Bet $5 on No for Bitcoin hitting 100k` | +| View positions | `Show my Polymarket positions` | +| Redeem winnings | `Redeem my Polymarket positions` | + +## Prompt Patterns + +``` +Search Polymarket for {query} +What are the odds {event}? +Bet {amount} on {Yes|No} for {market} +Show my Polymarket positions +Redeem my Polymarket positions +``` + +**Chain:** Polygon (uses USDC.e for betting) + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Check odds +await execute("What are the odds Trump wins the election?"); + +// Place a bet +await execute("Bet $10 on Yes for Presidential Election 2024"); + +// View positions +await execute("Show my Polymarket positions"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-portfolio` - Check USDC balance for betting diff --git a/bankr-agent-dev/skills/bankr-portfolio/SKILL.md b/bankr-agent-dev/skills/bankr-portfolio/SKILL.md new file mode 100644 index 0000000..7414c6e --- /dev/null +++ b/bankr-agent-dev/skills/bankr-portfolio/SKILL.md @@ -0,0 +1,61 @@ +--- +name: Bankr Dev - Portfolio +description: This skill should be used when building portfolio dashboards, implementing balance checking, or adding multi-chain holdings views. Covers balances, holdings, and valuations across chains. +version: 1.0.0 +--- + +# Portfolio Capability + +Query portfolio data and balances via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Total portfolio | `Show my portfolio` | +| Total balance | `What's my total balance?` | +| All holdings | `List all my crypto holdings` | +| Wallet value | `How much is my wallet worth?` | +| Chain balance | `Show my Base balance` | +| Chain holdings | `What tokens do I have on Polygon?` | +| Token balance | `How much ETH do I have?` | +| Token across chains | `Show my USDC on all chains` | +| Largest holding | `What's my largest holding?` | +| Token location | `Where do I have the most ETH?` | + +## Prompt Patterns + +``` +Show my portfolio +What's my total balance? +Show my {chain} balance +How much {token} do I have? +Show my {token} on all chains +What tokens do I have on {chain}? +``` + +**Supported chains:** Base, Polygon, Ethereum, Unichain, Solana + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Full portfolio +await execute("Show my portfolio"); + +// Chain-specific +await execute("Show my Base balance"); + +// Token-specific +await execute("How much ETH do I have?"); + +// Token across chains +await execute("Show my USDC on all chains"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-token-trading` - Trade based on portfolio data diff --git a/bankr-agent-dev/skills/bankr-project-templates/SKILL.md b/bankr-agent-dev/skills/bankr-project-templates/SKILL.md new file mode 100644 index 0000000..ec6f59b --- /dev/null +++ b/bankr-agent-dev/skills/bankr-project-templates/SKILL.md @@ -0,0 +1,322 @@ +--- +name: Bankr Dev - Project Templates +description: This skill should be used when the user asks to "scaffold a Bankr project", "create new Bankr bot", "build a Bankr web service", "create Bankr dashboard", "build Bankr CLI tool", "project structure for Bankr", "Bankr project types", or needs guidance on directory structures and templates for different types of Bankr API integrations. +version: 1.0.0 +--- + +# Bankr Project Templates + +Directory structures and templates for Bankr API projects. + +## Available Templates + +| Template | Use Case | Key Features | +|----------|----------|--------------| +| **bot** | Automated tasks | Polling loop, scheduler, status streaming | +| **web-service** | HTTP APIs | REST endpoints, webhooks, async handling | +| **dashboard** | Web UIs | Frontend + backend, real-time updates | +| **cli** | Command-line tools | Subcommands, interactive prompts | + +## Bot Template + +For automated trading bots, price monitors, alert systems, and scheduled tasks. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # Main entry point with scheduler +│ ├── bankr-client.ts # Bankr API client (from bankr-client-patterns skill) +│ ├── types.ts # TypeScript interfaces +│ └── config.ts # Configuration loading +└── scripts/ + └── run.sh # Convenience script +``` + +### Key Features + +- **Polling loop**: Configurable interval for recurring checks +- **Status streaming**: Real-time job status updates +- **Error handling**: Automatic retries with backoff +- **Environment config**: `.env` based configuration +- **Graceful shutdown**: Handles SIGINT/SIGTERM + +### Use Cases + +- Price monitoring and alerts +- Automated trading strategies +- Portfolio rebalancing +- Scheduled market analysis +- DCA automation + +### Entry Point Pattern (index.ts) + +```typescript +import { execute } from "./bankr-client"; + +const INTERVAL = 60000; // 1 minute + +async function runBot() { + console.log("Starting Bankr bot..."); + + while (true) { + try { + const result = await execute( + "Check ETH price", + (msg) => console.log("Status:", msg) + ); + + if (result.status === "completed") { + console.log("Result:", result.response); + // Add your logic here + } + } catch (error) { + console.error("Error:", error); + } + + await new Promise(r => setTimeout(r, INTERVAL)); + } +} + +runBot(); +``` + +--- + +## Web Service Template + +For HTTP APIs that wrap or extend Bankr functionality. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # Server entry point +│ ├── server.ts # Express/Fastify server setup +│ ├── routes/ +│ │ ├── health.ts # Health check endpoint +│ │ └── bankr.ts # Bankr proxy/extension routes +│ ├── bankr-client.ts # Bankr API client +│ ├── types.ts # TypeScript interfaces +│ └── config.ts # Configuration loading +└── scripts/ + └── run.sh +``` + +### Key Features + +- **REST API endpoints**: Clean API design +- **Request validation**: Input sanitization +- **Async job handling**: Non-blocking operations +- **Webhook support**: Callbacks on job completion +- **Rate limiting**: Prevent abuse +- **CORS**: Cross-origin support + +### Use Cases + +- API gateway for Bankr +- Custom trading APIs +- Webhook integrations +- Backend for mobile apps +- Microservice architecture + +### Additional Dependencies + +```json +{ + "dependencies": { + "express": "^4.18.0" + } +} +``` + +Or for Fastify: + +```json +{ + "dependencies": { + "fastify": "^4.25.0" + } +} +``` + +--- + +## Dashboard Template + +For web UIs with portfolio tracking, market analysis, or monitoring. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── server/ +│ ├── index.ts # Backend server +│ ├── bankr-client.ts # Bankr API client +│ ├── routes/ +│ │ └── api.ts # API routes for frontend +│ └── types.ts +├── public/ +│ ├── index.html # Main HTML page +│ ├── styles.css # Basic styles +│ └── app.js # Frontend JavaScript +└── scripts/ + └── run.sh +``` + +### Key Features + +- **Simple frontend**: HTML/CSS/JS (no build step required) +- **Backend API**: Express server for Bankr operations +- **Real-time updates**: Polling for status changes +- **Portfolio display**: Token balances and values +- **Market data**: Price charts and analysis + +### Use Cases + +- Portfolio tracking dashboard +- Trading interface +- Market monitoring +- Position management +- Analytics dashboard + +### Frontend Pattern (app.js) + +```javascript +async function checkPrice() { + const response = await fetch('/api/price/ETH'); + const data = await response.json(); + document.getElementById('eth-price').textContent = data.price; +} + +setInterval(checkPrice, 30000); +checkPrice(); +``` + +--- + +## CLI Template + +For command-line tools with subcommands and interactive features. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # CLI entry with commander.js +│ ├── commands/ +│ │ ├── trade.ts # Trading commands +│ │ ├── price.ts # Price query commands +│ │ └── status.ts # Job status commands +│ ├── bankr-client.ts # Bankr API client +│ └── types.ts +└── scripts/ + └── run.sh +``` + +### Key Features + +- **Commander.js**: CLI framework with subcommands +- **Interactive prompts**: User input when needed +- **Progress indicators**: Status during polling +- **Colored output**: Better UX +- **Help system**: Auto-generated from commands + +### Use Cases + +- Personal trading tool +- Scripting and automation +- DevOps integration +- Quick price checks +- Batch operations + +### Additional Dependencies + +```json +{ + "dependencies": { + "commander": "^12.0.0" + } +} +``` + +### CLI Pattern (index.ts) + +```typescript +import { program } from "commander"; +import { price } from "./commands/price"; +import { trade } from "./commands/trade"; + +program + .name("bankr-cli") + .description("CLI for Bankr operations") + .version("1.0.0"); + +program + .command("price ") + .description("Get token price") + .action(price); + +program + .command("trade ") + .description("Execute a trade") + .option("-c, --chain ", "Target chain", "base") + .action(trade); + +program.parse(); +``` + +--- + +## Choosing a Template + +| Need | Recommended Template | +|------|---------------------| +| Automated recurring tasks | **bot** | +| HTTP API for integrations | **web-service** | +| Visual interface | **dashboard** | +| Terminal-based tool | **cli** | +| Price alerts | **bot** | +| Trading API | **web-service** | +| Portfolio viewer | **dashboard** | +| Quick trades | **cli** | + +## Common Files + +All templates share common files. Load the `bankr-client-patterns` skill for: +- `bankr-client.ts` - Complete API client +- `package.json` - Base dependencies +- `tsconfig.json` - TypeScript config +- `.env.example` - Environment template +- `.gitignore` - Standard ignores + +## Next Steps After Scaffolding + +1. **Install dependencies**: `bun install` or `npm install` +2. **Configure API key**: Copy `.env.example` to `.env` and add `BANKR_API_KEY` +3. **Customize**: Modify the template for your use case +4. **Run**: `bun dev` or `npm run dev` for development +5. **Build**: `bun run build` or `npm run build` for production diff --git a/bankr-agent-dev/skills/bankr-token-deployment/SKILL.md b/bankr-agent-dev/skills/bankr-token-deployment/SKILL.md new file mode 100644 index 0000000..8b2f363 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-token-deployment/SKILL.md @@ -0,0 +1,65 @@ +--- +name: Bankr Dev - Token Deployment +description: This skill should be used when building token launch tools, implementing Clanker integration, or adding fee claiming functionality. Covers ERC20 deployment, metadata updates, and trading fees. +version: 1.0.0 +--- + +# Token Deployment Capability + +Deploy and manage tokens via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Deploy token | `Deploy a token called MyToken with symbol MTK` | +| Deploy with description | `Deploy token MyToken (MTK) with description: A community token` | +| Deploy with socials | `Deploy token MyToken (MTK) with website https://mytoken.xyz and Twitter @mytoken` | +| Check fees | `Check my Clanker fees` | +| Claim fees | `Claim all my Clanker fees` | +| Claim for token | `Claim fees for my token MTK` | +| Claim legacy fees | `Claim legacy Clanker fees` | +| Update description | `Update description for MTK: New description here` | +| Update socials | `Update MTK Twitter to @newhandle` | +| Update image | `Update logo for MTK to https://...` | +| Update reward recipient | `Update reward recipient for MTK to 0x...` | + +## Prompt Patterns + +``` +Deploy a token called {name} with symbol {symbol} +Deploy token {name} ({symbol}) with description: {description} +Deploy token {name} ({symbol}) with website {url} and Twitter @{handle} +Check my Clanker fees +Claim all my Clanker fees +Update description for {symbol}: {new_description} +Update {symbol} Twitter to @{handle} +``` + +**Supported chains:** Base (primary), Unichain (secondary) + +**Rate limits:** +- Standard: 1 token per day +- Bankr Club: 10 tokens per day + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Deploy token +await execute("Deploy a token called MyToken with symbol MTK"); + +// With socials +await execute("Deploy token MyToken (MTK) with website https://mytoken.xyz and Twitter @mytoken"); + +// Check and claim fees +await execute("Check my Clanker fees"); +await execute("Claim all my Clanker fees"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-token-trading` - Trade deployed tokens diff --git a/bankr-agent-dev/skills/bankr-token-trading/SKILL.md b/bankr-agent-dev/skills/bankr-token-trading/SKILL.md new file mode 100644 index 0000000..6199174 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-token-trading/SKILL.md @@ -0,0 +1,55 @@ +--- +name: Bankr Dev - Token Trading +description: This skill should be used when building trading bots, implementing swap functionality, or adding cross-chain bridge support. Covers same-chain swaps, cross-chain bridges, ETH/WETH conversions, and amount formats. +version: 1.0.0 +--- + +# Token Trading Capability + +Execute token swaps and trades via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Buy tokens | `Buy $50 of ETH` | +| Sell tokens | `Sell 10% of my USDC` | +| Swap tokens | `Swap 0.1 ETH for USDC` | +| Cross-chain bridge | `Bridge 100 USDC from Ethereum to Base` | +| Cross-chain swap | `Swap ETH on Ethereum for USDC on Polygon` | +| Wrap ETH | `Convert 1 ETH to WETH` | +| Unwrap WETH | `Convert 1 WETH to ETH` | + +## Prompt Patterns + +``` +Buy {amount} of {token} [on {chain}] +Sell {amount} of {token} [on {chain}] +Swap {amount} {fromToken} for {toToken} [on {chain}] +Bridge {amount} {token} from {sourceChain} to {destChain} +``` + +**Amount formats:** +- USD: `$50`, `$100` +- Percentage: `10%`, `50%` +- Exact: `0.5 ETH`, `100 USDC` + +**Supported chains:** Base, Polygon, Ethereum, Unichain, Solana + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// Simple trade +await execute("Buy $50 of ETH on Base"); + +// Cross-chain +await execute("Bridge 100 USDC from Ethereum to Base"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-market-research` - Price data for trading decisions diff --git a/bankr-agent-dev/skills/bankr-transfers/SKILL.md b/bankr-agent-dev/skills/bankr-transfers/SKILL.md new file mode 100644 index 0000000..c5b0d37 --- /dev/null +++ b/bankr-agent-dev/skills/bankr-transfers/SKILL.md @@ -0,0 +1,56 @@ +--- +name: Bankr Dev - Transfers +description: This skill should be used when building payment systems, implementing token transfers, or adding ENS/social handle resolution. Supports wallet addresses, ENS names, and social handles. +version: 1.0.0 +--- + +# Transfers Capability + +Send tokens to any recipient via natural language prompts. + +## What You Can Do + +| Operation | Example Prompt | +|-----------|----------------| +| Send to address | `Send 0.1 ETH to 0x1234...abcd` | +| Send to ENS | `Send $50 USDC to vitalik.eth` | +| Send to Twitter | `Send $5 ETH to @username on Twitter` | +| Send to Farcaster | `Send 10 USDC to @user on Farcaster` | +| Send to Telegram | `Send 0.01 ETH to @user on Telegram` | +| Percentage send | `Send 10% of my ETH to 0x...` | + +## Prompt Patterns + +``` +Send {amount} {token} to {recipient} [on {chain}] +``` + +**Recipient formats:** +- Wallet address: `0x1234...abcd` +- ENS name: `vitalik.eth`, `name.eth` +- Social handle: `@username on Twitter/Farcaster/Telegram` + +**Amount formats:** +- USD: `$50`, `$100` +- Percentage: `10%`, `50%` +- Exact: `0.5 ETH`, `100 USDC` + +**Supported chains:** Base, Polygon, Ethereum, Unichain, Solana + +## Usage + +```typescript +import { execute } from "./bankr-client"; + +// To ENS +await execute("Send 0.1 ETH to vitalik.eth on Base"); + +// To social handle +await execute("Send $5 ETH to @user on Twitter"); +``` + +## Related Skills + +- `bankr-client-patterns` - Client setup and execute function +- `bankr-api-basics` - API fundamentals +- `bankr-portfolio` - Check balances before transfers diff --git a/bankr-agent/.claude-plugin/plugin.json b/bankr-agent/.claude-plugin/plugin.json index ab8c650..f20a0b8 100644 --- a/bankr-agent/.claude-plugin/plugin.json +++ b/bankr-agent/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "bankr-agent", - "version": "0.1.1", + "version": "1.0.0", "description": "Integration with Bankr API for crypto trading, market analysis, and Polymarket predictions", "author": { "name": "Bankr Team" diff --git a/bankr-agent/README.md b/bankr-agent/README.md index def6dbc..ff1c5e3 100644 --- a/bankr-agent/README.md +++ b/bankr-agent/README.md @@ -30,11 +30,21 @@ Integration with the Bankr API for crypto trading, market analysis, and Polymark ``` 3. Install the plugin in Claude Code: + + **Claude Code:** ```bash claude plugin marketplace add BankrBot/claude-plugins claude plugin install bankr-agent@bankr-claude-plugins ``` + **Other Coding Tools (Cursor, OpenCode, Gemini CLI, Antigravity, etc.):** + + Only skills are compatible with other platforms. Agents, commands, hooks, and MCP servers require Claude Code. + + ```bash + bunx skills add BankrBot/claude-plugins + ``` + ## Usage The bankr-agent automatically triggers on: diff --git a/bankr-agent/agents/bankr-agent.md b/bankr-agent/agents/bankr-agent.md index c28fdcf..b099ca1 100644 --- a/bankr-agent/agents/bankr-agent.md +++ b/bankr-agent/agents/bankr-agent.md @@ -23,26 +23,6 @@ description: | - - Context: User wants market analysis - user: "What are the trends in the macro crypto market?" - assistant: "I'll analyze the current crypto market trends for you." - [Uses bankr-agent for market analysis] - - Market analysis, trends, and macro crypto questions should use the bankr-agent for up-to-date information. - - - - - Context: User asks about Polymarket odds - user: "What are the odds the NYC mayor is Joe?" - assistant: "Let me check the current Polymarket odds on that prediction." - [Uses bankr-agent to query Polymarket] - - Polymarket queries about odds, probabilities, or prediction market information should use the bankr-agent. - - - Context: User wants to place a bet on Polymarket user: "Bet $5 on the Eagles to win this week" @@ -53,86 +33,74 @@ description: | - - Context: User asks about DeFi or blockchain - user: "What's the TVL on Aave?" - assistant: "Let me look up the total value locked on Aave." - [Uses bankr-agent for DeFi data] - - DeFi protocol queries, blockchain statistics, and web3 data requests should go through bankr-agent. - - - model: inherit color: green --- -You are a crypto trading and prediction market assistant powered by the Bankr API. You help users with cryptocurrency operations, market analysis, and Polymarket predictions. +# Bankr Trading & Predictions Assistant + +Help users with cryptocurrency operations, market analysis, and Polymarket predictions via the Bankr API. -**Your Core Responsibilities:** +## Your Role -1. **Crypto Trading**: Execute buy, sell, and swap operations for tokens on various chains (Base, Ethereum, Solana, etc.) -2. **Price Queries**: Get current prices for any cryptocurrency -3. **Market Analysis**: Provide insights on market trends, macro analysis, and DeFi protocols -4. **Polymarket Operations**: Check odds and place bets on prediction markets -5. **Job Management**: Track job status, show real-time updates, and handle cancellations +You are a **skill router** - identify what the user needs and load the appropriate skill for detailed guidance. Don't duplicate skill content; reference and load skills instead. -**Workflow Process:** +## Available Skills -1. **Submit the Request** - - Use `bankr_agent_submit_prompt` to send the user's request to the Bankr API - - The prompt should be the user's request in natural language - - You'll receive a job ID back +### Workflow Skills -2. **Poll for Status** - - Use `bankr_agent_get_job_status` to check on the job - - Poll every 2 seconds until the job completes - - Report any status updates to the user as they come in (the statusUpdates field) - - Continue polling until status is "completed", "failed", or "cancelled" +| User Need | Load Skill | +|-----------|------------| +| Execute request, submit prompt, poll job | `bankr-job-workflow` | +| Authentication error, API key issue, setup | `bankr-error-handling` | -3. **Report Results** - - When completed, share the response with the user - - If there are transactions, explain what was executed - - If there's rich data (images/charts), mention it +### Capability Skills -4. **Handle Errors** - - If a job fails, explain the error to the user - - Suggest alternatives if applicable +| User Need | Load Skill | +|-----------|------------| +| Buy, sell, swap, trade tokens | `bankr-token-trading` | +| Send/transfer to address, ENS, @handle | `bankr-transfers` | +| Polymarket bets, odds, positions | `bankr-polymarket` | +| Leverage, long/short, Avantis | `bankr-leverage-trading` | +| Buy NFTs, view NFT holdings | `bankr-nft-operations` | +| Balances, portfolio, holdings | `bankr-portfolio` | +| Price, analysis, sentiment, charts | `bankr-market-research` | +| Limit orders, DCA, stop-loss, schedules | `bankr-automation` | +| Deploy tokens, Clanker, claim fees | `bankr-token-deployment` | -**Status Update Handling:** +## Quick Reference -The Bankr API provides real-time status updates during processing. When polling: -- Check the `statusUpdates` array for new messages -- Report each new status update to keep the user informed -- Status updates show what the agent is currently doing (e.g., "Analyzing market data...", "Preparing transaction...") +### MCP Tools -**Cancellation:** +- `bankr_agent_submit_prompt` - Send natural language request to Bankr +- `bankr_agent_get_job_status` - Poll for job status (every 2 seconds) +- `bankr_agent_cancel_job` - Cancel a running job -If the user wants to cancel a running job: -- Use `bankr_agent_cancel_job` with the job ID -- Confirm cancellation to the user +### Supported Chains -**Output Guidelines:** +Base, Polygon, Ethereum, Unichain, Solana -- Be concise but informative -- For price queries: State the price clearly with the token symbol -- For trades: Confirm what was traded, amounts, and any transaction details -- For market analysis: Summarize key insights -- For Polymarket: State odds clearly and any relevant context -- Always report any errors clearly +### Amount Formats -**Error Handling:** +- USD: `$50` +- Percentage: `50%` +- Exact: `0.1 ETH` -If you receive an authentication error (401 or "Invalid API key"), the error message will contain detailed setup instructions. Present these instructions clearly to the user - they explain how to: -1. Create an API key at https://bankr.bot/api -2. Set the BANKR_API_KEY environment variable -3. Restart Claude Code +## Workflow -Do NOT try to retry the request or use alternative methods when authentication fails. The user must fix their API key configuration first. +1. **Identify** user need from their request +2. **Load** the appropriate capability skill for context +3. **Execute** using `bankr-job-workflow` skill pattern +4. **Handle errors** with `bankr-error-handling` skill if needed -**Important Notes:** +## Capabilities Overview -- The Bankr API handles the actual execution - you just need to submit prompts and track status -- Jobs typically complete within 30 seconds to 2 minutes -- Users can ask you to cancel jobs if they change their mind -- Be transparent about what's happening during processing +**Trading**: Buy, sell, swap tokens across chains +**Transfers**: Send to addresses, ENS, or social handles +**Polymarket**: Search markets, place bets, manage positions +**Leverage**: Long/short with Avantis on Base +**NFTs**: Browse and buy on OpenSea +**Portfolio**: Check balances across all chains +**Research**: Prices, analysis, sentiment, charts +**Automation**: Limit orders, DCA, TWAP, schedules +**Token Creation**: Deploy via Clanker, claim fees diff --git a/bankr-agent/commands/bankr-agent.md b/bankr-agent/commands/bankr-agent.md index aad5f12..ae0251d 100644 --- a/bankr-agent/commands/bankr-agent.md +++ b/bankr-agent/commands/bankr-agent.md @@ -5,10 +5,23 @@ argument-hint: [query] Send the following query to the Bankr API: $ARGUMENTS -Use the bankr-agent workflow: +Follow the `bankr-job-workflow` skill for execution: 1. Submit the query using `bankr_agent_submit_prompt` 2. Poll for status using `bankr_agent_get_job_status` every 2 seconds 3. Report status updates to the user as they come in 4. When complete, share the final response -If no query is provided, ask the user what they'd like to do with Bankr (crypto trading, price checks, market analysis, or Polymarket predictions). +For context on specific operations, load the appropriate capability skill: +- Trading: `bankr-token-trading` +- Transfers: `bankr-transfers` +- Polymarket: `bankr-polymarket` +- Leverage: `bankr-leverage-trading` +- NFTs: `bankr-nft-operations` +- Portfolio: `bankr-portfolio` +- Research: `bankr-market-research` +- Automation: `bankr-automation` +- Token deployment: `bankr-token-deployment` + +If errors occur, consult the `bankr-error-handling` skill. + +If no query is provided, ask the user what they'd like to do with Bankr (crypto trading, price checks, market analysis, Polymarket predictions, etc.). diff --git a/bankr-agent/mcp-server/package.json b/bankr-agent/mcp-server/package.json index 9a4a784..e266291 100644 --- a/bankr-agent/mcp-server/package.json +++ b/bankr-agent/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "bankr-agent-mcp-server", - "version": "0.1.1", + "version": "1.0.0", "description": "MCP server for Bankr Agent API integration", "type": "module", "main": "dist/index.js", diff --git a/bankr-agent/skills/bankr-automation/SKILL.md b/bankr-agent/skills/bankr-automation/SKILL.md new file mode 100644 index 0000000..b3d6426 --- /dev/null +++ b/bankr-agent/skills/bankr-automation/SKILL.md @@ -0,0 +1,67 @@ +--- +name: Bankr Agent - Automation +description: This skill should be used when the user asks about "limit order", "stop loss", "DCA", "TWAP", "schedule", "automate", "recurring order", "price trigger", "cancel automation", "my automations", or any automated trading operation. Provides guidance on limit orders, scheduled commands, and automated strategies. +version: 1.0.0 +--- + +# Bankr Automation + +Set up automated orders and scheduled trading strategies. + +## Order Types + +### Limit Orders +Execute at target price: +- "Set a limit order to buy ETH at $3,000" +- "Limit order: sell BNKR when it hits $0.02" + +### Stop Loss Orders +Automatically sell to limit losses: +- "Set stop loss for my ETH at $2,500" +- "Stop loss: sell 50% of BNKR if it drops 20%" + +### DCA (Dollar Cost Averaging) +Invest fixed amounts at regular intervals: +- "DCA $100 into ETH every week" +- "Set up daily $50 Bitcoin purchases" + +### TWAP (Time-Weighted Average Price) +Spread large orders over time: +- "TWAP: buy $1000 of ETH over 24 hours" +- "Spread my sell order over 4 hours" + +### Scheduled Commands +Run any Bankr command on a schedule: +- "Every morning, check my portfolio" +- "At 9am daily, check ETH price" + +## Managing Automations + +**View:** +- "Show my automations" +- "What limit orders do I have?" + +**Cancel:** +- "Cancel my ETH limit order" +- "Stop my DCA into Bitcoin" + +## Chain Support + +- **EVM Chains** (Base, Polygon, Ethereum): All order types supported +- **Solana**: Uses Jupiter Trigger API for limit orders, stop loss, and DCA + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Order not triggering | Check price threshold | +| Insufficient balance | Ensure funds available when order executes | +| Order cancelled | May expire or conflict with other orders | + +## Tips + +1. Start small - test with small amounts first +2. Set alerts - get notified on execution +3. Review regularly - update orders as market changes +4. Combine strategies - DCA + stop loss works well +5. Factor in fees - consider per-transaction costs for DCA diff --git a/bankr-agent/skills/bankr-error-handling/SKILL.md b/bankr-agent/skills/bankr-error-handling/SKILL.md new file mode 100644 index 0000000..cabb7dc --- /dev/null +++ b/bankr-agent/skills/bankr-error-handling/SKILL.md @@ -0,0 +1,78 @@ +--- +name: Bankr Agent - Error Handling +description: This skill should be used when encountering authentication errors, API key errors, 401 errors, "invalid API key", "BANKR_API_KEY not set", job failures, or any Bankr API errors. Provides setup instructions and troubleshooting guidance for resolving Bankr configuration issues. +version: 1.0.0 +--- + +# Bankr Error Handling + +Resolve Bankr API errors and authentication issues. + +## Authentication Errors (401) + +### Symptoms +- HTTP 401 status code +- "Invalid API key" or "Unauthorized" message + +### Resolution + +Present these setup instructions to the user: + +**Step 1: Create an API Key** +``` +Visit https://bankr.bot/api to create a new API key +``` + +**Step 2: Set Environment Variable** +```bash +# Add to shell profile (~/.zshrc or ~/.bashrc) +export BANKR_API_KEY=bk_your_api_key_here +``` + +**Step 3: Restart Claude Code** +``` +Close and reopen the terminal/Claude Code session +``` + +**Important**: Do NOT retry when authentication fails. User must fix API key first. + +## Common Job Failures + +| Error | Cause | Resolution | +|-------|-------|------------| +| Insufficient balance | Not enough tokens | Check balance, reduce amount | +| Token not found | Invalid symbol/address | Verify token exists on chain | +| Slippage exceeded | Price moved too much | Retry or try smaller amount | +| Transaction reverted | On-chain failure | Check transaction details | +| Rate limit exceeded | Too many requests | Wait and retry | + +## HTTP Status Codes + +| Code | Meaning | Action | +|------|---------|--------| +| 400 | Bad request | Check prompt format | +| 401 | Unauthorized | Fix API key (see above) | +| 402 | Payment required | Ensure wallet has BNKR on Base | +| 429 | Rate limited | Wait and retry | +| 500 | Server error | Retry after delay | + +## Troubleshooting Checklist + +1. **API Key**: Set, starts with `bk_`, Claude Code restarted after setting +2. **Network**: Internet working, api.bankr.bot reachable +3. **For Trading**: Wallet has sufficient balance, token exists on chain + +## Reporting Errors to Users + +1. State what went wrong simply +2. Provide specific fix steps +3. Avoid technical jargon +4. Suggest alternatives + +**Example**: +``` +Your Bankr API key is not configured. To set it up: +1. Visit https://bankr.bot/api to create an API key +2. Set BANKR_API_KEY in your environment +3. Restart Claude Code +``` diff --git a/bankr-agent/skills/bankr-job-workflow/SKILL.md b/bankr-agent/skills/bankr-job-workflow/SKILL.md new file mode 100644 index 0000000..3710915 --- /dev/null +++ b/bankr-agent/skills/bankr-job-workflow/SKILL.md @@ -0,0 +1,73 @@ +--- +name: Bankr Agent - Job Workflow +description: This skill should be used when executing Bankr requests, submitting prompts to Bankr API, polling for job status, checking job progress, using Bankr MCP tools, or understanding the submit-poll-complete workflow pattern. Provides the core asynchronous job pattern for all Bankr API operations. +version: 1.0.0 +--- + +# Bankr Job Workflow + +Execute Bankr API operations using MCP tools with the asynchronous job pattern. + +## Core Pattern: Submit-Poll-Complete + +1. **Submit** - Send prompt via `bankr_agent_submit_prompt`, receive job ID +2. **Poll** - Check status via `bankr_agent_get_job_status` every 2 seconds +3. **Complete** - Report results when status is terminal + +## MCP Tools + +### `bankr_agent_submit_prompt` +Submit a natural language prompt to start a job. +- **Input**: Natural language request (e.g., "Buy $50 of ETH on Base") +- **Output**: Job ID for tracking + +### `bankr_agent_get_job_status` +Check job status. Response includes: +- `status`: pending | processing | completed | failed | cancelled +- `response`: Text answer (when completed) +- `transactions`: Array of executed transactions +- `statusUpdates`: Progress messages during execution +- `error`: Error message (when failed) + +### `bankr_agent_cancel_job` +Cancel a running job. + +## Job Status States + +| Status | Action | +|--------|--------| +| `pending` | Keep polling | +| `processing` | Keep polling, report statusUpdates | +| `completed` | Read response and transactions | +| `failed` | Check error field | +| `cancelled` | No further action | + +## Timing + +- **Poll interval**: 2 seconds +- **Typical completion**: 30 seconds to 2 minutes +- **Suggest cancellation**: After 3+ minutes for simple queries + +## Output Guidelines + +| Query Type | Output Format | +|------------|---------------| +| Price queries | State price clearly (e.g., "ETH is $3,245.67") | +| Trades | Confirm amounts and transaction details | +| Market analysis | Summarize key insights concisely | +| Polymarket | State odds with context | +| Balances | List holdings with USD values | +| Errors | Explain clearly, suggest alternatives | + +## Status Update Handling + +- Track last reported update count +- Only report NEW updates to avoid repetition +- Updates show agent progress (e.g., "Analyzing market data...") + +## Error Recovery + +If polling fails: +1. Retry after brief delay +2. Job continues server-side regardless +3. Can resume polling with same jobId diff --git a/bankr-agent/skills/bankr-leverage-trading/SKILL.md b/bankr-agent/skills/bankr-leverage-trading/SKILL.md new file mode 100644 index 0000000..a10f5db --- /dev/null +++ b/bankr-agent/skills/bankr-leverage-trading/SKILL.md @@ -0,0 +1,73 @@ +--- +name: Bankr Agent - Leverage Trading +description: This skill should be used when the user asks about "leverage trading", "long position", "short position", "Avantis", "derivatives", "forex trading", "commodities trading", "open a position", "close position", "stop loss", "take profit", or any leveraged trading operation. Provides guidance on Avantis perpetuals trading. +version: 1.0.0 +--- + +# Bankr Leverage Trading + +Trade with leverage using Avantis perpetuals on Base. + +## Overview + +Avantis offers long/short positions with up to 100x leverage on crypto, forex, and commodities. + +**Chain**: Base + +## Supported Markets + +- **Crypto**: BTC, ETH, SOL, ARB, AVAX, BNB, DOGE, LINK, OP, MATIC +- **Forex**: EUR/USD, GBP/USD, USD/JPY, AUD/USD, USD/CAD +- **Commodities**: Gold (XAU), Silver (XAG), Oil (WTI), Natural Gas + +## Prompt Examples + +**Open positions:** +- "Open a 5x long on ETH with $100" +- "Short Bitcoin with 10x leverage" +- "Long Gold with 2x leverage" + +**With risk management:** +- "Long ETH 5x with stop loss at $3000" +- "Short BTC 10x with take profit at 20%" +- "Long SOL 3x with SL at $150 and TP at $200" + +**View/close positions:** +- "Show my Avantis positions" +- "Close my ETH long" +- "Exit all my Avantis positions" + +## Position Parameters + +| Parameter | Description | Example | +|-----------|-------------|---------| +| Leverage | 1x to 100x (default: 1x) | "5x leverage" | +| Collateral | Amount to use | "$100", "0.1 ETH" | +| Stop Loss | Auto-close to limit losses | "stop loss at $3000" | +| Take Profit | Auto-close to lock gains | "take profit at $4000" | + +## Leverage Guidelines + +| Risk Level | Leverage | Use Case | +|------------|----------|----------| +| Conservative | 1-3x | Long-term views | +| Moderate | 3-10x | Swing trading | +| Aggressive | 10-25x | Short-term scalps | +| High Risk | 25x+ | Experienced only | + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Insufficient collateral | Add more funds | +| Asset not supported | Check available markets | +| Liquidation | Position closed, collateral lost | +| High funding rate | Consider shorter hold time | + +## Risk Management Tips + +1. Start with low leverage (2-5x) +2. Always use stop loss to limit downside +3. Don't over-leverage - position sizing matters +4. Monitor positions - markets move fast +5. Understand liquidation risk diff --git a/bankr-agent/skills/bankr-market-research/SKILL.md b/bankr-agent/skills/bankr-market-research/SKILL.md new file mode 100644 index 0000000..2c4fa6f --- /dev/null +++ b/bankr-agent/skills/bankr-market-research/SKILL.md @@ -0,0 +1,83 @@ +--- +name: Bankr Agent - Market Research +description: This skill should be used when the user asks about "token price", "market data", "technical analysis", "sentiment", "trending tokens", "price chart", "market cap", "token research", "what's the price of", "analyze token", or any market research query. Provides guidance on token research, analysis, and market intelligence. +version: 1.0.0 +--- + +# Bankr Market Research + +Research tokens and analyze market data. + +## Capabilities + +- Token search across chains +- Price and market data +- Technical analysis +- Social sentiment +- Price charts +- Trending tokens + +## Prompt Examples + +**Price queries:** +- "What's the price of ETH?" +- "How much is Bitcoin worth?" + +**Market data:** +- "Show me ETH market data" +- "What's the market cap of BNKR?" + +**Technical analysis:** +- "Do technical analysis on ETH" +- "Show RSI for Bitcoin" +- "Is ETH overbought?" + +**Sentiment:** +- "What's the sentiment on ETH?" +- "Is the community bullish on SOL?" + +**Charts:** +- "Show me ETH price chart" +- "Generate BTC chart for last week" + +**Discovery:** +- "What tokens are trending?" +- "Show top gainers today" +- "Compare ETH vs SOL" + +## Data Available + +### Price Data +- Current USD price +- 24h / 7d change +- All-time high/low + +### Market Metrics +- Market cap +- 24h volume +- Circulating/total supply +- Number of holders + +### Technical Indicators +- RSI (Relative Strength Index) +- MACD +- Moving averages (50, 200) +- Support/resistance levels + +## Supported Chains + +Token research works across Base, Polygon, Ethereum, Solana, and Unichain. + +## Token Search + +Find tokens by name or symbol: +- "Search for BNKR token" +- "Find tokens called Bankr" +- "What is the contract for PEPE on Base?" + +## Limitations + +- Historical data limited to available timeframes +- Sentiment based on available social data +- New tokens may have limited data +- Not investment advice diff --git a/bankr-agent/skills/bankr-nft-operations/SKILL.md b/bankr-agent/skills/bankr-nft-operations/SKILL.md new file mode 100644 index 0000000..f309224 --- /dev/null +++ b/bankr-agent/skills/bankr-nft-operations/SKILL.md @@ -0,0 +1,70 @@ +--- +name: Bankr Agent - NFT Operations +description: This skill should be used when the user asks to "buy NFT", "purchase NFT", "OpenSea", "NFT collection", "view my NFTs", "NFT holdings", "mint NFT", "NFT listings", or any NFT-related operation. Provides guidance on browsing, purchasing, and managing NFTs. +version: 1.0.0 +--- + +# Bankr NFT Operations + +Browse, purchase, and manage NFTs across chains via OpenSea integration. + +**Supported Chains**: Base, Ethereum, Polygon + +## Operations + +- **Browse** - Search NFT collections +- **View Listings** - Find best deals and floor prices +- **Buy** - Purchase NFTs from marketplace listings +- **View Holdings** - Check your NFT portfolio +- **Transfer** - Send NFTs to another wallet +- **Mint** - Mint from supported platforms (Manifold, SeaDrop) + +## Prompt Examples + +**Browse NFTs:** +- "Find NFTs from the Bored Ape collection" +- "Show me trending NFT collections" + +**View listings:** +- "What's the floor price for Pudgy Penguins?" +- "Show cheapest NFTs in Azuki collection" + +**Buy NFTs:** +- "Buy the cheapest Bored Ape" +- "Purchase this NFT: [OpenSea URL]" + +**View holdings:** +- "Show my NFTs" +- "What NFTs do I own on Ethereum?" + +## Collection Resolution + +Bankr resolves common names and abbreviations: + +| Input | Resolved | +|-------|----------| +| "Bored Apes" / "BAYC" | boredapeyachtclub | +| "Pudgy Penguins" | pudgypenguins | +| "CryptoPunks" | cryptopunks | + +## Chain Considerations + +- **Ethereum**: Most valuable collections, higher gas +- **Base**: Growing ecosystem, very low gas +- **Polygon**: Low gas, gaming NFTs + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Collection not found | Try alternative names | +| NFT already sold | Try another listing | +| Insufficient funds | Check balance | +| High gas | Wait or try L2 | + +## Safety Tips + +- Verify collection through official links +- Check floor price to avoid overpaying +- Look for verified collections +- Factor in gas costs diff --git a/bankr-agent/skills/bankr-polymarket/SKILL.md b/bankr-agent/skills/bankr-polymarket/SKILL.md new file mode 100644 index 0000000..94ebfac --- /dev/null +++ b/bankr-agent/skills/bankr-polymarket/SKILL.md @@ -0,0 +1,70 @@ +--- +name: Bankr Agent - Polymarket +description: This skill should be used when the user asks about "Polymarket", "prediction markets", "betting odds", "place a bet", "check odds", "market predictions", "what are the odds", "bet on election", "sports betting", or any prediction market operation. Provides guidance on searching markets, placing bets, and managing positions. +version: 1.0.0 +--- + +# Bankr Polymarket + +Interact with Polymarket prediction markets. + +## Overview + +Polymarket is a decentralized prediction market where users can search markets, view odds, place bets, and manage positions. + +**Chain**: Polygon (uses USDC.e for betting) + +## Prompt Examples + +**Search markets:** +- "Search Polymarket for election markets" +- "What prediction markets are trending?" + +**Check odds:** +- "What are the odds Trump wins the election?" +- "Check the odds on the Eagles game" + +**Place bets:** +- "Bet $10 on Yes for Trump winning" +- "Place $5 on the Eagles to win" + +**View/redeem positions:** +- "Show my Polymarket positions" +- "Redeem my Polymarket positions" + +## How Betting Works + +- You buy shares of "Yes" or "No" outcomes +- Share price reflects market probability (e.g., $0.60 = 60% chance) +- If your outcome wins, shares pay $1 each +- Profit = $1 - purchase price (per share) + +**Example**: Bet $10 on "Yes" at $0.60 = ~16.67 shares. If Yes wins, get $16.67 (profit $6.67). + +## Auto-Bridging + +If you don't have USDC on Polygon, Bankr automatically bridges from another chain. + +## Market Types + +| Category | Examples | +|----------|----------| +| Politics | Elections, legislation | +| Sports | Game outcomes, championships | +| Crypto | Price predictions, ETF approvals | +| Culture | Awards, entertainment events | + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Market not found | Try different search terms | +| Insufficient USDC | Add USDC or let auto-bridge | +| Market closed | Can't bet on resolved markets | + +## Tips + +- Search and check odds before betting +- Start with small amounts to test +- Check market liquidity for best prices +- Redeem promptly after markets resolve diff --git a/bankr-agent/skills/bankr-portfolio/SKILL.md b/bankr-agent/skills/bankr-portfolio/SKILL.md new file mode 100644 index 0000000..24a4b40 --- /dev/null +++ b/bankr-agent/skills/bankr-portfolio/SKILL.md @@ -0,0 +1,67 @@ +--- +name: Bankr Agent - Portfolio +description: This skill should be used when the user asks about "my balance", "portfolio", "token holdings", "check balance", "how much do I have", "wallet balance", "what tokens do I own", "show my holdings", or any balance/portfolio query. Provides guidance on checking balances across chains. +version: 1.0.0 +--- + +# Bankr Portfolio + +Query token balances and portfolio across all supported chains. + +## Supported Chains + +| Chain | Native Token | +|-------|-------------| +| Base | ETH | +| Polygon | MATIC | +| Ethereum | ETH | +| Unichain | ETH | +| Solana | SOL | + +## Prompt Examples + +**Full portfolio:** +- "Show my portfolio" +- "What's my total balance?" +- "How much crypto do I have?" + +**Chain-specific:** +- "Show my Base balance" +- "What tokens do I have on Polygon?" + +**Token-specific:** +- "How much ETH do I have?" +- "What's my USDC balance?" +- "Show my ETH across all chains" + +## Features + +- **USD Valuation**: All balances include current USD value +- **Multi-Chain Aggregation**: See the same token across all chains +- **Real-Time Prices**: Values reflect current market prices + +## Common Tokens Tracked + +- **Stablecoins**: USDC, USDT, DAI +- **DeFi**: UNI, AAVE, LINK +- **Memecoins**: DOGE, SHIB, PEPE +- **Project tokens**: BNKR, ARB, OP + +## Use Cases + +**Before trading:** +- "Do I have enough ETH to swap for 100 USDC?" + +**Portfolio review:** +- "What's my largest holding?" +- "Show portfolio breakdown by chain" + +**After transactions:** +- "Did my ETH arrive?" +- "Show my new BNKR balance" + +## Notes + +- Balance queries are read-only (no transactions) +- Shows balance of connected wallet address +- Very small balances (dust) may be excluded diff --git a/bankr-agent/skills/bankr-token-deployment/SKILL.md b/bankr-agent/skills/bankr-token-deployment/SKILL.md new file mode 100644 index 0000000..18a41c3 --- /dev/null +++ b/bankr-agent/skills/bankr-token-deployment/SKILL.md @@ -0,0 +1,72 @@ +--- +name: Bankr Agent - Token Deployment +description: This skill should be used when the user asks to "deploy token", "create token", "launch token", "Clanker", "claim fees", "token metadata", "update token", "mint new token", or any token deployment operation. Provides guidance on deploying ERC20 tokens via Clanker. +version: 1.0.0 +--- + +# Bankr Token Deployment + +Deploy and manage ERC20 tokens using Clanker. + +## Supported Chains + +- **Base**: Primary deployment chain, full Clanker support +- **Unichain**: Secondary option + +## Deployment Parameters + +| Parameter | Required | Description | +|-----------|----------|-------------| +| Name | Yes | Token name (e.g., "MyToken") | +| Symbol | Yes | Ticker, 3-5 chars (e.g., "MTK") | +| Description | No | Token description | +| Image | No | Logo URL or upload | +| Website | No | Project website | +| Twitter | No | Twitter/X handle | +| Telegram | No | Telegram group | + +## Prompt Examples + +**Deploy tokens:** +- "Deploy a token called BankrFan with symbol BFAN" +- "Create a memecoin: name=DogeKiller, symbol=DOGEK" +- "Deploy token with website myproject.com and Twitter @myproject" + +**Claim fees:** +- "Claim fees for my token MTK" +- "Check my Clanker fees" +- "Claim legacy Clanker fees" + +**Update metadata:** +- "Update description for MyToken" +- "Add Twitter link to my token" +- "Update logo for MyToken" + +## Rate Limits + +| User Type | Daily Limit | +|-----------|-------------| +| Standard Users | 1 token/day | +| Bankr Club Members | 10 tokens/day | + +## Fee Structure + +- Small fee on each trade, accumulated for token creator +- Claimable anytime via "Claim fees for my token" +- Legacy fees (older Clanker versions) claimed separately + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Rate limit reached | Wait 24 hours or upgrade | +| Name taken | Choose different name | +| Symbol exists | Use unique symbol | +| Image upload failed | Check format/size | + +## Best Practices + +- Choose unique, memorable name and symbol +- Add description and social links immediately +- Upload quality logo +- Claim fees regularly diff --git a/bankr-agent/skills/bankr-token-trading/SKILL.md b/bankr-agent/skills/bankr-token-trading/SKILL.md new file mode 100644 index 0000000..a4d7350 --- /dev/null +++ b/bankr-agent/skills/bankr-token-trading/SKILL.md @@ -0,0 +1,64 @@ +--- +name: Bankr Agent - Token Trading +description: This skill should be used when the user asks to "buy crypto", "sell tokens", "swap ETH", "trade on Base", "exchange tokens", "cross-chain swap", "bridge tokens", "convert ETH to WETH", or any token trading operation. Provides guidance on supported chains, amount formats, and swap operations. +version: 1.0.0 +--- + +# Bankr Token Trading + +Execute token trades and swaps across multiple blockchains. + +## Supported Chains + +| Chain | Native Token | +|-------|--------------| +| Base | ETH | +| Polygon | MATIC | +| Ethereum | ETH | +| Unichain | ETH | +| Solana | SOL | + +## Amount Formats + +| Format | Example | Description | +|--------|---------|-------------| +| USD | `$50` | Dollar amount to spend | +| Percentage | `50%` | Percentage of your balance | +| Exact | `0.1 ETH` | Specific token amount | + +## Prompt Examples + +**Same-chain swaps:** +- "Swap 0.1 ETH for USDC on Base" +- "Buy $50 of BNKR on Base" +- "Sell 50% of my ETH holdings" + +**Cross-chain swaps:** +- "Bridge 0.5 ETH from Ethereum to Base" +- "Move 100 USDC from Polygon to Solana" + +**ETH/WETH conversion:** +- "Convert 0.1 ETH to WETH" +- "Unwrap 0.5 WETH to ETH" + +## Chain Selection + +- If no chain specified, Bankr selects the most appropriate chain +- Base is preferred for most operations due to low fees +- Cross-chain routes are automatically optimized +- Include chain name in prompt to specify: "Buy ETH on Polygon" + +## Slippage + +- Default slippage tolerance is applied automatically +- For volatile tokens, Bankr adjusts slippage as needed +- If slippage is exceeded, the transaction fails safely + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| Insufficient balance | Reduce amount or add funds | +| Token not found | Check token symbol/address | +| High slippage | Try smaller amounts | +| Network congestion | Wait and retry | diff --git a/bankr-agent/skills/bankr-transfers/SKILL.md b/bankr-agent/skills/bankr-transfers/SKILL.md new file mode 100644 index 0000000..236d1fc --- /dev/null +++ b/bankr-agent/skills/bankr-transfers/SKILL.md @@ -0,0 +1,71 @@ +--- +name: Bankr Agent - Transfers +description: This skill should be used when the user asks to "send tokens", "transfer ETH", "send to ENS", "transfer to wallet", "send to @username", "transfer to Farcaster", "send to Twitter handle", or any asset transfer operation. Provides guidance on recipient resolution and transfer formats. +version: 1.0.0 +--- + +# Bankr Transfers + +Transfer tokens to addresses, ENS names, or social handles. + +## Supported Transfers + +- **EVM Chains**: Base, Polygon, Ethereum, Unichain (ETH, MATIC, ERC20 tokens) +- **Solana**: SOL and SPL tokens + +## Recipient Formats + +| Format | Example | Description | +|--------|---------|-------------| +| Address | `0x1234...abcd` | Direct wallet address | +| ENS | `vitalik.eth` | Ethereum Name Service | +| Twitter | `@elonmusk` | Twitter/X username | +| Farcaster | `@dwr.eth` | Farcaster username | +| Telegram | `@username` | Telegram handle | + +Social handles are resolved to linked wallet addresses before sending. + +## Amount Formats + +| Format | Example | Description | +|--------|---------|-------------| +| USD | `$50` | Dollar amount | +| Percentage | `50%` | Percentage of balance | +| Exact | `0.1 ETH` | Specific amount | + +## Prompt Examples + +**To addresses:** +- "Send 0.5 ETH to 0x1234..." +- "Transfer 100 USDC to 0xabcd..." + +**To ENS:** +- "Send 1 ETH to vitalik.eth" +- "Transfer $50 of USDC to mydomain.eth" + +**To social handles:** +- "Send $20 of ETH to @friend on Twitter" +- "Transfer 0.1 ETH to @user on Farcaster" + +**With chain specified:** +- "Send ETH on Base to vitalik.eth" +- "Send 10% of my ETH to @friend" + +## Chain Selection + +If not specified, Bankr selects automatically based on recipient activity and gas costs. Specify chain in prompt if needed. + +## Common Issues + +| Issue | Resolution | +|-------|------------| +| ENS not found | Verify the ENS name exists | +| Social handle not found | Check username is correct | +| No linked wallet | User hasn't linked wallet to social | +| Insufficient balance | Reduce amount or add funds | + +## Security Notes + +- Always verify recipient before confirming +- Social handle resolution shows the resolved address +- Large transfers may require additional confirmation diff --git a/x402-sdk-dev/.claude-plugin/plugin.json b/x402-sdk-dev/.claude-plugin/plugin.json index e2c0a25..7d6d5d1 100644 --- a/x402-sdk-dev/.claude-plugin/plugin.json +++ b/x402-sdk-dev/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "bankr-x402-sdk-dev", - "version": "1.1.0", + "version": "1.2.0", "description": "Bankr SDK integration for AI-assisted Web3 development with multi-chain DeFi and x402 micropayments", "author": { "name": "Bankr", diff --git a/x402-sdk-dev/README.md b/x402-sdk-dev/README.md index c6336bd..993fc08 100644 --- a/x402-sdk-dev/README.md +++ b/x402-sdk-dev/README.md @@ -16,15 +16,33 @@ Claude Code integration for [@bankr/sdk](https://www.npmjs.com/package/@bankr/sd ## Quick Start +### 1. Install Plugin + +**Claude Code:** ```bash -# 1. Install plugin claude plugin marketplace add BankrBot/claude-plugins claude plugin install bankr-x402-sdk-dev@bankr-claude-plugins +``` + +**Other Coding Tools (Cursor, OpenCode, Gemini CLI, Antigravity, etc.):** + +Only skills are compatible with other platforms. Agents, commands, hooks, and MCP servers require Claude Code. + +```bash +bunx skills add BankrBot/claude-plugins +``` -# 2. Install SDK +### 2. Install SDK + +```bash +bun add @bankr/sdk +# or npm install @bankr/sdk +``` -# 3. Configure environment +### 3. Configure Environment + +```bash export BANKR_PRIVATE_KEY=0x... # Required: pays $0.01 USDC per request (needs USDC on Base) export BANKR_WALLET_ADDRESS=0x... # Optional: receives swapped tokens export BANKR_API_URL=https://api.bankr.bot # Optional @@ -40,6 +58,8 @@ export BANKR_API_URL=https://api.bankr.bot # Optional | `sdk-balance-queries` | Token balances, portfolio values | | `sdk-transaction-builder` | Transfers, approvals, NFTs, DeFi | | `sdk-job-management` | Async job control and monitoring | +| `x402-project-templates` | Directory structures for bot, web-service, dashboard, cli projects | +| `x402-client-patterns` | Reusable client code, executor, and common project files | ## Agent @@ -49,14 +69,16 @@ export BANKR_API_URL=https://api.bankr.bot # Optional | Command | Description | |---------|-------------| -| `/bankr-x402-sdk-dev:init-sdk [path]` | Initialize SDK in your project - installs package, creates client file, sets up .env | +| `/bankr-x402-sdk-dev:scaffold [type]` | Scaffold a complete project using the Bankr x402 SDK | + +**Project types:** `bot`, `web-service`, `dashboard`, `cli` -**Quick setup:** +**Quick start:** ```bash -/bankr-x402-sdk-dev:init-sdk +/bankr-x402-sdk-dev:scaffold bot ``` -This auto-detects your package manager and TypeScript setup, then creates a ready-to-use `bankr-client.ts` file. +This creates a complete project with `bankr-client.ts`, transaction executor, package.json, tsconfig.json, and environment configuration. ## Basic Usage diff --git a/x402-sdk-dev/agents/sdk-assistant.md b/x402-sdk-dev/agents/sdk-assistant.md index 3efefdc..89b6e1c 100644 --- a/x402-sdk-dev/agents/sdk-assistant.md +++ b/x402-sdk-dev/agents/sdk-assistant.md @@ -51,6 +51,8 @@ Load these skills based on user needs: **Install:** ```bash +bun add @bankr/sdk +# or npm install @bankr/sdk ``` diff --git a/x402-sdk-dev/commands/init-sdk.md b/x402-sdk-dev/commands/init-sdk.md deleted file mode 100644 index d38ae07..0000000 --- a/x402-sdk-dev/commands/init-sdk.md +++ /dev/null @@ -1,270 +0,0 @@ ---- -name: init-sdk -description: Initialize Bankr SDK in current project - installs package, creates client file, sets up environment -allowed-tools: - - Read - - Write - - Edit - - Bash - - Glob - - Grep -argument-hint: "[output-path]" ---- - -# Initialize Bankr SDK - -Set up the Bankr SDK in the user's project with proper configuration. - -## Arguments - -- `[output-path]` (optional): Directory for the client file. Defaults to `src/` if it exists, otherwise project root. - -## Workflow - -### Step 1: Detect Project Configuration - -Check the project setup: - -```bash -# Check for package.json (required) -ls package.json - -# Detect package manager from lockfiles -ls package-lock.json 2>/dev/null # npm -ls yarn.lock 2>/dev/null # yarn -ls pnpm-lock.yaml 2>/dev/null # pnpm -ls bun.lockb 2>/dev/null # bun -``` - -**Package manager priority:** bun.lockb > pnpm-lock.yaml > yarn.lock > package-lock.json > default to npm - -Check for TypeScript: -```bash -ls tsconfig.json 2>/dev/null -``` - -If `tsconfig.json` exists, use TypeScript (`.ts`). Otherwise use JavaScript (`.js`). - -### Step 2: Check if SDK Already Installed - -```bash -grep -q "@bankr/sdk" package.json -``` - -If not found, install it using the detected package manager: - -| Manager | Command | -|---------|---------| -| npm | `npm install @bankr/sdk` | -| yarn | `yarn add @bankr/sdk` | -| pnpm | `pnpm add @bankr/sdk` | -| bun | `bun add @bankr/sdk` | - -### Step 3: Determine Output Path - -1. If user provided `[output-path]`, use that -2. Else if `src/` directory exists, use `src/` -3. Else if `lib/` directory exists, use `lib/` -4. Else use project root - -### Step 4: Create Client File - -Create the appropriate file based on TypeScript detection. - -**For TypeScript (`bankr-client.ts`):** - -```typescript -import { BankrClient } from "@bankr/sdk"; - -/** - * Bankr SDK Client - * - * Provides AI-powered Web3 operations with x402 micropayments. - * Each API request costs $0.01 USDC (paid from payment wallet on Base). - * - * Environment Variables: - * BANKR_PRIVATE_KEY - Required: Payment wallet private key (needs USDC on Base) - * BANKR_WALLET_ADDRESS - Optional: Receiving wallet (defaults to payment wallet) - * BANKR_API_URL - Optional: API endpoint (defaults to https://api.bankr.bot) - * - * @example - * ```typescript - * import { bankrClient } from "./bankr-client"; - * - * // Token swap - * const swap = await bankrClient.promptAndWait({ - * prompt: "Swap 0.1 ETH to USDC on Base", - * }); - * - * // Check balances - * const balances = await bankrClient.promptAndWait({ - * prompt: "What are my token balances?", - * }); - * - * // The SDK returns transaction data - execute with viem/ethers - * if (swap.status === "completed" && swap.transactions) { - * const tx = swap.transactions[0].metadata.transaction; - * // await wallet.sendTransaction(tx); - * } - * ``` - * - * @see https://www.npmjs.com/package/@bankr/sdk - * @see https://docs.bankr.bot - */ - -// Validate required environment variable -if (!process.env.BANKR_PRIVATE_KEY) { - throw new Error( - "BANKR_PRIVATE_KEY environment variable is required. " + - "This wallet pays $0.01 USDC per request and must have USDC on Base." - ); -} - -export const bankrClient = new BankrClient({ - // Required: Payment wallet private key - // This wallet pays $0.01 USDC per API request (must have USDC on Base) - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - - // Optional: Override receiving wallet address - // If not set, tokens are sent to the payment wallet address - walletAddress: process.env.BANKR_WALLET_ADDRESS, - - // Optional: API endpoint (defaults to production) - ...(process.env.BANKR_API_URL && { baseUrl: process.env.BANKR_API_URL }), -}); - -// Export the wallet address for reference -export const bankrWalletAddress = bankrClient.getWalletAddress(); -``` - -**For JavaScript (`bankr-client.js`):** - -```javascript -const { BankrClient } = require("@bankr/sdk"); - -/** - * Bankr SDK Client - * - * Provides AI-powered Web3 operations with x402 micropayments. - * Each API request costs $0.01 USDC (paid from payment wallet on Base). - * - * Environment Variables: - * BANKR_PRIVATE_KEY - Required: Payment wallet private key (needs USDC on Base) - * BANKR_WALLET_ADDRESS - Optional: Receiving wallet (defaults to payment wallet) - * BANKR_API_URL - Optional: API endpoint (defaults to https://api.bankr.bot) - * - * @example - * ```javascript - * const { bankrClient } = require("./bankr-client"); - * - * // Token swap - * const swap = await bankrClient.promptAndWait({ - * prompt: "Swap 0.1 ETH to USDC on Base", - * }); - * - * // Check balances - * const balances = await bankrClient.promptAndWait({ - * prompt: "What are my token balances?", - * }); - * ``` - * - * @see https://www.npmjs.com/package/@bankr/sdk - * @see https://docs.bankr.bot - */ - -// Validate required environment variable -if (!process.env.BANKR_PRIVATE_KEY) { - throw new Error( - "BANKR_PRIVATE_KEY environment variable is required. " + - "This wallet pays $0.01 USDC per request and must have USDC on Base." - ); -} - -const bankrClient = new BankrClient({ - // Required: Payment wallet private key - privateKey: process.env.BANKR_PRIVATE_KEY, - - // Optional: Override receiving wallet address - walletAddress: process.env.BANKR_WALLET_ADDRESS, - - // Optional: API endpoint - ...(process.env.BANKR_API_URL && { baseUrl: process.env.BANKR_API_URL }), -}); - -// Export the client and wallet address -module.exports = { - bankrClient, - bankrWalletAddress: bankrClient.getWalletAddress(), -}; -``` - -### Step 5: Create/Update .env.example - -Check if `.env.example` exists. If it does, append the Bankr variables (if not already present). If it doesn't exist, create it. - -```bash -# .env.example content to add: - -# Bankr SDK Configuration -# See: https://docs.bankr.bot - -# Required: Payment wallet private key -# This wallet pays $0.01 USDC per API request (must have USDC on Base) -# Format: 64 hex characters with 0x prefix -BANKR_PRIVATE_KEY=0x - -# Optional: Receiving wallet address -# Tokens from swaps/purchases go here. Defaults to payment wallet if not set. -# BANKR_WALLET_ADDRESS=0x - -# Optional: API endpoint override (defaults to https://api.bankr.bot) -# BANKR_API_URL=https://api.bankr.bot -``` - -### Step 6: Check .gitignore - -Verify `.env` is in `.gitignore` to prevent committing secrets: - -```bash -grep -q "^\.env$" .gitignore 2>/dev/null || grep -q "\.env" .gitignore 2>/dev/null -``` - -If not found, warn the user to add `.env` to `.gitignore`. - -### Step 7: Summary - -After completing all steps, show a summary: - -``` -Bankr SDK initialized successfully! - -Created: - - {output-path}/bankr-client.{ts|js} - - .env.example (updated with Bankr variables) - -Next steps: - 1. Copy .env.example to .env - 2. Add your payment wallet private key to BANKR_PRIVATE_KEY - 3. Fund the wallet with USDC on Base ($1-2 recommended) - 4. Import and use: - - import { bankrClient } from "{output-path}/bankr-client"; - - const result = await bankrClient.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC on Base", - }); - -Documentation: https://docs.bankr.bot -``` - -## Error Handling - -- **No package.json**: "This command must be run in a Node.js project with package.json" -- **SDK install fails**: Show the error and suggest manual installation -- **File already exists**: Ask user if they want to overwrite - -## Tips - -- If the user specifies a custom path like `lib/services`, create the directory if needed -- Preserve existing content in .env.example, only append new variables -- Use ES modules syntax if package.json has `"type": "module"` (even for .js files) diff --git a/x402-sdk-dev/commands/scaffold.md b/x402-sdk-dev/commands/scaffold.md new file mode 100644 index 0000000..58f0e9c --- /dev/null +++ b/x402-sdk-dev/commands/scaffold.md @@ -0,0 +1,58 @@ +--- +description: Scaffold a new project that uses the Bankr x402 SDK +argument-hint: [project-type] +allowed-tools: Read, Write, Bash, AskUserQuestion, Glob, Grep +--- + +# x402 SDK Project Scaffold + +Create a complete TypeScript/Node.js project scaffold for building on the Bankr x402 SDK. + +## Process + +1. **Determine project type** - If `$ARGUMENTS` specifies a type, use it. Otherwise, ask the user. + + Load the `x402-project-templates` skill for available types: + - **bot** - Automated trading bot, price monitor, portfolio rebalancer, scheduled task + - **web-service** - HTTP API that wraps Bankr SDK for mobile apps or integrations + - **dashboard** - Web UI for portfolio tracking, swap interface, monitoring + - **cli** - Command-line tool for Bankr operations + +2. **Ask for project details**: + - Project name (kebab-case, e.g., `my-trading-bot`) + - Brief description of what it will do + - Any specific SDK operations it will use (swaps, transfers, queries, NFTs, leverage) + - Package manager preference: **bun** (recommended - faster) or **npm** + +3. **Create project structure**: + - Load `x402-project-templates` skill for the directory structure + - Load `x402-client-patterns` skill for common files and client code + - Create all directories using `mkdir -p` + - Write each file using the Write tool + - Customize based on user's description + +4. **Explain next steps**: + - How to set up the payment wallet (private key with USDC on Base) + - How to run the project (use selected package manager: `bun install && bun dev` or `npm install && npm run dev`) + - What to customize first based on their use case + +## Skills to Load + +**Core Skills (always load):** +- `x402-project-templates` - Directory structures for each project type +- `x402-client-patterns` - bankr-client.ts and common files (package.json, tsconfig.json, .env.example, .gitignore) +- `sdk-capabilities` - SDK operation reference + +**Capability Skills (load based on project purpose):** +- `sdk-token-swaps` - For trading bots: swap patterns, approval handling +- `sdk-transaction-builder` - For custom transfers, NFT ops, bridges +- `sdk-balance-queries` - For dashboards: portfolio queries, balance tracking +- `sdk-wallet-operations` - For multi-wallet setups +- `sdk-job-management` - For advanced: job polling, cancellation + +## Implementation Notes + +- Create all directories first using `mkdir -p` +- Write each file using the Write tool +- Include helpful comments in generated code +- Generate a README.md with setup instructions and usage examples diff --git a/x402-sdk-dev/skills/sdk-balance-queries/SKILL.md b/x402-sdk-dev/skills/sdk-balance-queries/SKILL.md index 8feface..6a1f98d 100644 --- a/x402-sdk-dev/skills/sdk-balance-queries/SKILL.md +++ b/x402-sdk-dev/skills/sdk-balance-queries/SKILL.md @@ -1,295 +1,80 @@ --- -name: SDK Balance Queries +name: Bankr x402 SDK - Balance Queries description: This skill should be used when the user asks "what are my balances", "how much ETH do I have", "check my wallet", "show my tokens", "portfolio value", "what tokens do I own", "NFT holdings", "how much USDC", "get token balances", "wallet contents", or any question about token balances, wallet contents, portfolio values, or NFT holdings across chains using the Bankr SDK. -version: 1.0.0 +version: 1.1.0 --- # SDK Balance Queries -Query multi-chain token balances and portfolio data with AI-powered analysis using the Bankr SDK and x402 micropayments. +Query multi-chain token balances and portfolio data using natural language prompts. -## Overview +## Operations -The Bankr SDK provides a simple natural language interface for querying token balances, portfolio values, and NFT holdings across multiple blockchains. Balance queries are processed through the AI backend and return rich, formatted responses with optional charts and analysis cards. +| Operation | Example Prompt | Notes | +|-----------|----------------|-------| +| Single token balance | "How much USDC do I have?" | Fastest query type | +| Multi-token balance | "Show my ETH, USDC, and DEGEN balances" | Single chain | +| All tokens on chain | "What tokens do I have on Base?" | Lists all holdings | +| Multi-chain balances | "Show my balances across all chains" | Slower, queries all | +| Portfolio value | "What's my total portfolio value in USD?" | USD conversion | +| Token value | "How much is my DEGEN worth?" | Single token USD | +| NFT holdings | "Show me my NFT collections" | Lists collections | +| NFT floor prices | "What's the floor price of my NFTs?" | External API calls | -**Key capabilities:** -- Multi-chain balance queries (Base, Ethereum, Polygon, Solana) -- Token balance lookup by symbol or contract -- Portfolio valuation in USD -- NFT collection holdings and floor prices -- Rich data responses with charts and analysis +## Prompt Patterns -## Basic Query +``` +# Token Balances +"What are my token balances?" +"How much [TOKEN] do I have?" +"Show my [TOKEN] balance on [CHAIN]" +"What's my balance of token 0x..." + +# Multi-Chain +"Show my balances across all chains" +"What are my balances on Base and Ethereum?" +"Compare my USDC holdings across all chains" + +# Portfolio Value +"What's my total portfolio value in USD?" +"How much is my [TOKEN] worth in USD?" +"What's the total value of my Base holdings?" + +# NFTs +"Show me my NFT collections" +"How many Pudgy Penguins do I own?" +"What's the floor price of my NFTs?" +``` -Initialize the BankrClient and query balances using natural language prompts: +## Usage ```typescript import { BankrClient } from "@bankr/sdk"; const client = new BankrClient({ privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, }); const result = await client.promptAndWait({ - prompt: "What are my token balances?", + prompt: "What are my token balances on Base?", }); console.log(result.response); // "You have 150.5 USDC, 0.25 ETH, 1000 DEGEN on Base..." ``` -## Query Examples - -### Single Token Queries - -Query specific token balances on a particular chain: - -```typescript -// Specific token on default chain (Base) -const usdcBalance = await client.promptAndWait({ - prompt: "How much USDC do I have?", -}); - -// Specific token on specific chain -const ethBalance = await client.promptAndWait({ - prompt: "How much ETH do I have on Ethereum mainnet?", -}); - -// Token by contract address -const tokenBalance = await client.promptAndWait({ - prompt: "What's my balance of token 0x4ed4E862860beD51a9570b96d89aF5E1B0Efefed?", -}); -``` - -### Multi-Token Queries - -Query multiple tokens in a single request: - -```typescript -// Multiple specific tokens -const balances = await client.promptAndWait({ - prompt: "Show me my ETH, USDC, and DEGEN balances", -}); - -// All tokens on a chain -const allOnBase = await client.promptAndWait({ - prompt: "What tokens do I have on Base?", -}); -``` - -### Multi-Chain Queries - -Query balances across multiple blockchains: - -```typescript -// All chains -const allChains = await client.promptAndWait({ - prompt: "Show my balances across all chains", -}); - -// Specific chains -const ethAndBase = await client.promptAndWait({ - prompt: "What are my balances on Base and Ethereum?", -}); - -// Compare holdings -const comparison = await client.promptAndWait({ - prompt: "Compare my USDC holdings across all chains", -}); -``` - -### Portfolio Value Queries - -Get USD valuations of holdings: - -```typescript -// Total portfolio value -const totalValue = await client.promptAndWait({ - prompt: "What's my total portfolio value in USD?", -}); - -// Specific token value -const degenValue = await client.promptAndWait({ - prompt: "How much is my DEGEN worth in USD?", -}); - -// Chain-specific value -const baseValue = await client.promptAndWait({ - prompt: "What's the total value of my Base holdings?", -}); -``` - -### NFT Queries - -Query NFT holdings and valuations: - -```typescript -// List NFT collections -const nftCollections = await client.promptAndWait({ - prompt: "Show me my NFT collections", -}); - -// NFT floor prices -const floorPrices = await client.promptAndWait({ - prompt: "What's the floor price of my NFTs?", -}); - -// Specific collection -const pudgyInfo = await client.promptAndWait({ - prompt: "How many Pudgy Penguins do I own?", -}); -``` - -## Query Different Wallet - -Query balances for a wallet other than the configured context wallet: - -```typescript -// Override wallet for this query only -const result = await client.promptAndWait({ - prompt: "What are the balances in this wallet?", - walletAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", -}); - -// Query specific wallet with specific tokens -const otherWallet = await client.promptAndWait({ - prompt: "How much ETH and USDC does this address have?", - walletAddress: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", -}); -``` - -## Rich Data Responses - -Balance queries may return rich data including charts and analysis cards. Handle these appropriately: - -```typescript -const result = await client.promptAndWait({ - prompt: "Show my portfolio breakdown", -}); - -// Check for rich data -if (result.richData && result.richData.length > 0) { - for (const data of result.richData) { - switch (data.type) { - case "chart": - console.log(`Portfolio chart: ${data.url}`); - // Display chart image from URL - break; - case "social-card": - console.log(`Analysis card: ${data.text}`); - // Display card content - break; - case "table": - console.log(`Data table: ${JSON.stringify(data.rows)}`); - // Render table data - break; - } - } -} -``` - -## Response Structure - -Balance query responses follow the standard SDK response format: - -```typescript -interface BalanceQueryResponse { - status: "completed" | "failed" | "pending" | "processing"; - response: string; // Human-readable balance summary - richData?: RichDataItem[]; // Charts, cards, tables - jobId: string; // Job identifier - processingTime?: number; // Time in milliseconds -} - -interface RichDataItem { - type: "chart" | "social-card" | "table" | "image"; - url?: string; // For charts/images - text?: string; // For cards - rows?: any[]; // For tables -} -``` - ## Supported Chains -Balance queries support the following blockchain networks: - -| Chain | Default | Notes | -|-------|---------|-------| -| Base | Yes | Primary chain, fastest responses | -| Ethereum | No | Mainnet ERC20 and NFTs | -| Polygon | No | L2 tokens and NFTs | -| Solana | No | SPL tokens and NFTs | - -Specify chain in natural language: "on Base", "on Ethereum", "on mainnet", "on Polygon", "on Solana" - -## Response Times - -Expected response times vary by query complexity: - -| Query Type | Typical Time | Notes | -|------------|--------------|-------| -| Single token balance | 2-3 seconds | Fastest | -| Multiple tokens | 3-5 seconds | Single chain | -| Multi-chain query | 5-10 seconds | Queries all chains | -| Portfolio valuation | 3-5 seconds | Includes USD conversion | -| NFT holdings | 5-10 seconds | Fetches metadata | -| NFT floor prices | 8-12 seconds | External API calls | - -## Error Handling - -Handle common balance query errors: - -```typescript -const result = await client.promptAndWait({ - prompt: "What are my balances?", - timeout: 30000, // 30 second timeout -}); - -if (result.status === "failed") { - const error = result.error; - - if (error?.includes("Invalid address")) { - console.error("The wallet address format is invalid"); - } else if (error?.includes("Rate limited")) { - console.error("Too many requests, try again later"); - } else if (error?.includes("Chain not supported")) { - console.error("The specified chain is not supported"); - } else { - console.error(`Balance query failed: ${error}`); - } - return; -} - -console.log(result.response); -``` - -## Best Practices +| Chain | Notes | +|-------|-------| +| Base | Default chain, fastest responses | +| Ethereum | Mainnet ERC20 and NFTs | +| Polygon | L2 tokens and NFTs | +| Solana | SPL tokens and NFTs | -1. **Use specific queries**: "How much USDC on Base?" is faster than "Show all balances everywhere" -2. **Cache responses**: Balance data is valid for short periods; avoid redundant queries -3. **Handle timeouts**: Set appropriate timeouts for multi-chain queries (longer) vs single token (shorter) -4. **Check status**: Always verify `result.status === "completed"` before using response data -5. **Process rich data**: Display charts and cards when available for better UX +Specify chain in prompt: "on Base", "on Ethereum", "on Polygon", "on Solana" -## Cost +## Related Skills -Each balance query costs $0.01 USDC via x402 micropayments, regardless of complexity. The payment wallet must have sufficient USDC on Base to cover query costs. - -## Common Prompt Patterns - -Effective prompts for balance queries: - -```typescript -// Recommended patterns -"What are my token balances on Base?" -"How much ETH do I have?" -"Show my USDC balance across all chains" -"What's my total portfolio value?" -"List my NFT holdings" - -// Less effective (still work but slower) -"Can you check what tokens I might have?" -"I'm wondering about my balances" -"Tell me everything about my wallet" -``` +- **sdk-wallet-operations**: Client setup and configuration +- **sdk-capabilities**: Full list of supported operations diff --git a/x402-sdk-dev/skills/sdk-capabilities/SKILL.md b/x402-sdk-dev/skills/sdk-capabilities/SKILL.md index 955b962..eb4fdc8 100644 --- a/x402-sdk-dev/skills/sdk-capabilities/SKILL.md +++ b/x402-sdk-dev/skills/sdk-capabilities/SKILL.md @@ -1,406 +1,83 @@ --- -name: SDK Capabilities +name: Bankr x402 SDK - Capabilities description: This skill should be used when the user asks "what can the SDK do", "what prompts does Bankr support", "SDK features", "supported operations", "what can I build with Bankr", "Bankr SDK capabilities", "what chains are supported", "what tokens can I trade", "SDK supported commands", or wants to understand the full range of operations available through the Bankr SDK. -version: 1.0.0 +version: 1.1.0 --- # SDK Capabilities -Complete guide to all operations supported by the Bankr SDK. The SDK accepts natural language prompts and returns transaction data for execution. - -## Overview - -The Bankr SDK provides AI-powered Web3 operations through natural language prompts. The SDK operates in **wallet mode**, meaning it returns transaction data for you to sign and execute rather than executing transactions directly. - -**Key features:** -- Natural language interface (no complex API calls) -- Multi-chain support (EVM chains: Base, Ethereum, Polygon) -- Transaction building with optimal 0x routing -- Market data and analysis -- x402 micropayments ($0.01 USDC per request) +Complete guide to operations supported by the Bankr SDK. The SDK accepts natural language prompts and returns transaction data for execution. + +## Supported Operations + +| Category | Operation | Example Prompt | +|----------|-----------|----------------| +| **Swaps** | Token swap | "Swap 0.1 ETH to USDC" | +| | Value-based buy | "Buy $100 of DEGEN" | +| | Percentage swap | "Swap 50% of my ETH to USDC" | +| **Transfers** | ERC20 transfer | "Send 100 USDC to 0x..." | +| | ETH transfer | "Send 0.1 ETH to @username" | +| | NFT transfer | "Send my Bored Ape #123 to 0x..." | +| **Wrapping** | Wrap ETH | "Wrap 1 ETH" | +| | Unwrap WETH | "Unwrap 1 WETH" | +| **Cross-Chain** | Bridge (EVM only) | "Bridge 100 USDC from Ethereum to Base" | +| **Leverage** | Long position | "Buy $50 of ETH/USD with 5x leverage" | +| | Short position | "Short $10 of GOLD" | +| | Close position | "Close all my BTC/USD positions" | +| **NFTs** | Buy NFT | "Buy the cheapest Tiny Dino NFT" | +| | List for sale | "List my Bored Ape for 10 ETH" | +| | Mint (Manifold) | "Mint from Manifold at 0x..." | +| | Mint (SeaDrop) | "Mint from SeaDrop at 0x..." | +| **Staking** | Stake BNKR | "Stake 1000 BNKR" | +| | Unstake | "Unstake my BNKR" | +| **Queries** | Balances | "What are my balances?" | +| | NFT holdings | "What NFTs do I own?" | +| | Token price | "Price of ETH" | +| | Token analysis | "Analyze DEGEN" | + +## NOT Supported + +| Feature | Alternative | +|---------|-------------| +| Polymarket betting | Use https://bankr.bot directly | +| Limit orders | Use https://swap.bankr.bot | +| DCA/TWAP orders | Use https://swap.bankr.bot | +| Solana cross-chain | EVM chains only | +| Bankr Earn | Use Bankr terminal | ## Supported Chains -| Chain | Native Token | Notes | -|-------|-------------|-------| -| Base | ETH | Default chain, lowest fees | -| Ethereum | ETH | Mainnet | -| Polygon | MATIC | L2, low fees | - -**Note:** Solana cross-chain swaps are NOT supported via SDK. The SDK operates in wallet mode which has limited Solana support. - ---- - -## SUPPORTED Operations - -### Token Swaps - -Exchange tokens on the same chain using 0x routing. - -**Example prompts:** -``` -"Swap 0.1 ETH to USDC" -"Exchange 100 USDC for WETH" -"Swap 1000 DEGEN to ETH" -"Swap 50% of my ETH to USDC" -"Sell all my DEGEN" -"Swap 0.1 ETH to USDC on Base" -"Exchange 100 USDC for WETH on Polygon" -"Buy $100 of ETH" -"Buy $5 of DEGEN" -"Purchase $50 worth of BNKR" -``` - -### ERC20 Transfers - -Send ERC20 tokens to addresses or social usernames. - -**Example prompts:** -``` -"Send 100 USDC to 0x1234..." -"Transfer 50 BNKR to @farcasteruser" -"Send 100 USDC to @username" -``` - -### Native Token Transfers - -Send ETH/MATIC to addresses. - -**Example prompts:** -``` -"Send 0.1 ETH to 0xabcd..." -"Transfer 0.5 ETH to @username" -``` - -### ETH/WETH Conversion - -Wrap and unwrap ETH. - -**Example prompts:** -``` -"Wrap 1 ETH" -"Convert 0.5 ETH to WETH" -"Unwrap 1 WETH" -"Convert WETH to ETH" -``` - -### Cross-Chain Swaps (EVM Only) - -Bridge or swap tokens across EVM chains. **Solana cross-chain is NOT supported.** - -**Example prompts:** -``` -"Swap 10 USDC on Base to USDC on Polygon" -"Bridge 1 ETH from Ethereum to Base" -"Swap 100 USDC on Polygon to ETH on Mainnet" -``` - -### Avantis Leveraged Trading - -Trade commodities, forex, and crypto with leverage on Base. - -**Available assets:** BTC/USD, ETH/USD, GOLD, SILVER, OIL, EUR/USD, GBP/USD, and more. - -**Example prompts:** -``` -"Buy $5 of BTC/USD" -"Short $10 of GOLD" -"Long $50 of ETH/USD" -"Buy $10 of GOLD with 5x leverage" -"Short BTC/USD with 10x leverage" -"Buy $25 of OIL with 10x leverage and 5% stop loss" -"Long $50 of ETH/USD with take profit at 150%" -"Buy $100 of BTC/USD with stop loss if price drops by $5000" -``` - -### Close Avantis Positions - -**Example prompts:** -``` -"Close all my BTC/USD positions" -"Close all my OIL positions" -"Close my ETH/USD position" -"Close $50 of my GOLD position" -"Close my Bitcoin long" -``` - -### View Avantis Positions - -**Example prompts:** -``` -"Show my Avantis positions" -"What are my Avantis positions" -"View my Avantis portfolio" -"What positions do I have on Avantis" -"Show my closed Avantis trades" -``` - -### Buy NFTs - -Purchase NFTs from OpenSea. - -**Example prompts:** -``` -"Buy the cheapest Tiny Dino NFT" -"Get me an OK Computer NFT" -"Purchase the floor BasedPunk" -"Buy this NFT: https://opensea.io/collection/okcomputers" -"Purchase token #1234 from BasePaint" -``` - -### Transfer NFTs - -Send NFTs to other addresses. - -**Example prompts:** -``` -"Send my Bored Ape #123 to 0x..." -"Transfer NFT to @username" -``` - -### List NFTs for Sale - -List your NFTs on OpenSea. - -**Example prompts:** -``` -"List my Bored Ape for 10 ETH" -"Sell my NFT for 5 ETH" -``` - -### Cancel NFT Listings - -**Example prompts:** -``` -"Cancel my NFT listing" -"Remove my Bored Ape from sale" -``` - -### Accept NFT Offers - -**Example prompts:** -``` -"Accept offer on my NFT" -"Accept the highest offer on my Bored Ape" -``` - -### Mint NFTs (SeaDrop) - -Mint NFTs via SeaDrop protocol. - -**Example prompts:** -``` -"Mint from the SeaDrop collection at 0x..." -``` +| Chain | Native Token | Default | +|-------|-------------|---------| +| Base | ETH | Yes | +| Ethereum | ETH | No | +| Polygon | MATIC | No | -### Mint NFTs (Manifold) - -Mint NFTs via Manifold. - -**Example prompts:** -``` -"Mint the Manifold NFT at 0x..." -``` - -### BNKR Staking - -Stake and unstake BNKR tokens. - -**Example prompts:** -``` -"Stake 1000 BNKR" -"Unstake my BNKR" -"How much BNKR do I have staked?" -``` - -### View Automations - -View your active automations. - -**Example prompts:** -``` -"Show my automations" -"What automations do I have?" -``` - -### Cancel Automations - -Cancel existing automations. - -**Example prompts:** -``` -"Cancel my automation" -"Stop all my automations" -``` - -### Balance Queries - -Check token balances. - -**Example prompts:** -``` -"What are my balances?" -"Show my balances on Base" -"What tokens do I hold?" -"Balances on Polygon" -``` - -### NFT Balances - -Check NFT holdings. - -**Example prompts:** -``` -"What NFTs do I own?" -"Show my NFTs on Base" -"Do I have any Bored Apes?" -``` - -### NFT Listings Discovery - -Browse NFT listings. - -**Example prompts:** -``` -"Show me the cheapest Bored Apes" -"What are the top 5 CryptoPunk listings" -"Show me NFTs from BasedPunks" -"What's the floor price for Azuki" -``` - -### Token Analysis - -Get price, market cap, volume, technical analysis, and social sentiment. - -**Example prompts:** -``` -"Price of ETH" -"What's BTC trading at?" -"Market cap of BNKR" -"Volume of USDC" -"Analyze ETH" -"TA for BNKR" -"Chart analysis for DEGEN" -``` - -### Token Discovery - -Find trending tokens. - -**Example prompts:** -``` -"What tokens do you recommend on Base?" -"Top tokens on Polygon today" -"Best coins on mainnet right now" -"Trending tokens on Base" -``` - ---- - -## NOT SUPPORTED Operations - -The following features are not available via the SDK: - -### Polymarket - -Not supported via SDK: -- Placing bets -- Selling positions -- Redeeming winnings - -Use the Bankr trading wallet directly at https://bankr.bot - -### Limit Orders - -Not supported via SDK. Use https://swap.bankr.bot to place limit orders. - -### Automated Orders - -Not supported via SDK: -- Stop orders -- TWAP (Time-Weighted Average Price) orders -- DCA (Dollar-Cost Averaging) orders - -Use https://swap.bankr.bot to set up automated orders. - -### Bankr Earn - -Not supported via SDK. Use the Bankr terminal to manage earn. - -### Featured NFT Mints - -Some featured mints require the Bankr trading wallet and are not available via SDK. - -### Solana Cross-Chain Swaps - -Solana cross-chain swaps are not supported via SDK. Only EVM chains (Base, Ethereum, Polygon) are supported. - -## Transaction Types - -The SDK returns transactions with a `type` field. Use this to identify and handle different operations: - -| Type | Description | -|------|-------------| -| `swap` | Token exchange via 0x routing | -| `approval` | ERC20 token approval | -| `transfer_erc20` | ERC20 token transfer | -| `transfer_eth` | Native ETH transfer | -| `convert_eth_to_weth` | Wrap ETH to WETH | -| `convert_weth_to_eth` | Unwrap WETH to ETH | -| `transfer_nft` | NFT transfer | -| `mint_manifold_nft` | Mint via Manifold | -| `mint_seadrop_nft` | Mint via SeaDrop | -| `buy_nft` | Purchase NFT | -| `avantisTrade` | Avantis leveraged trade | -| `swapCrossChain` | Cross-chain swap (EVM only) | -| `manage_bankr_staking` | BNKR staking | - ---- - -## Usage Pattern +## Usage ```typescript import { BankrClient } from "@bankr/sdk"; const client = new BankrClient({ privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, }); const result = await client.promptAndWait({ prompt: "Swap 0.1 ETH to USDC on Base", }); -if (result.status === "completed") { - // For trading operations: execute the returned transaction - if (result.transactions?.length) { - const swapTx = result.transactions.find(tx => tx.type === "swap"); - - // Handle approval if needed - if (swapTx?.metadata.approvalRequired) { - await wallet.sendTransaction(swapTx.metadata.approvalTx); - } - - // Execute the swap - const tx = swapTx.metadata.transaction; - await wallet.sendTransaction(tx); - } - - // For queries: read the response - console.log(result.response); +if (result.status === "completed" && result.transactions?.length) { + // Execute the returned transaction with your wallet + await wallet.sendTransaction(result.transactions[0].metadata.transaction); } ``` ---- - ## Cost -Each request costs $0.01 USDC via x402 micropayments. The payment wallet must have USDC on Base chain. +Each request costs $0.01 USDC via x402 micropayments. Gas fees for transactions are paid separately. -| Requests | Cost | -|----------|------| -| 100 | $1.00 | -| 1,000 | $10.00 | -| 10,000 | $100.00 | +## Related Skills -Gas fees for executing transactions are paid separately from the user's wallet. +- **sdk-token-swaps**: Token swap patterns and approval handling +- **sdk-transaction-builder**: Building transfers, NFT ops, bridges +- **sdk-balance-queries**: Portfolio and balance queries diff --git a/x402-sdk-dev/skills/sdk-job-management/SKILL.md b/x402-sdk-dev/skills/sdk-job-management/SKILL.md index 959640a..00d8215 100644 --- a/x402-sdk-dev/skills/sdk-job-management/SKILL.md +++ b/x402-sdk-dev/skills/sdk-job-management/SKILL.md @@ -1,412 +1,101 @@ --- -name: SDK Job Management +name: Bankr x402 SDK - Job Management description: This skill should be used when the user asks about "job status", "check if request completed", "cancel request", "why is my request taking so long", "poll for result", "batch requests", "retry failed request", "request timeout", "async operations", "job lifecycle", "manual polling", or needs advanced control over SDK async operations, manual job polling, batch processing, retry logic, or job cancellation. -version: 1.0.0 +version: 1.1.0 --- # SDK Job Management -Manage asynchronous jobs in the Bankr SDK: submit, poll, check status, cancel, and handle batch operations. +Manage asynchronous jobs: submit, poll, check status, cancel, and batch operations. -## Overview +## SDK Methods -The Bankr SDK processes requests asynchronously through a job-based system. Each request creates a job that progresses through a lifecycle from submission to completion. Understanding job management enables advanced control over SDK operations including manual polling, batch processing, and retry strategies. +| Method | Description | Use Case | +|--------|-------------|----------| +| `promptAndWait()` | Submit and wait for result | **Recommended** for most cases | +| `prompt()` | Submit, return immediately | Background processing | +| `pollJob()` | Poll until job completes | Manual job tracking | +| `getJobStatus()` | Check status once | Custom polling logic | +| `cancelJob()` | Cancel pending/processing job | Stop unwanted jobs | -**Key capabilities:** -- Submit jobs and receive job IDs -- Poll for job completion -- Check job status at any time -- Cancel pending or processing jobs -- Batch multiple requests efficiently -- Implement retry logic for failed jobs - -## Recommended: promptAndWait - -For most use cases, use `promptAndWait` which handles job submission and polling automatically: - -```typescript -import { BankrClient } from "@bankr/sdk"; - -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, -}); - -const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC", - timeout: 60000, // Optional: custom timeout (default 5 min) -}); +## Job Lifecycle -if (result.status === "completed") { - console.log(result.response); - console.log(result.transactions); -} ``` - -The `promptAndWait` method: -1. Submits the job to the API -2. Polls for completion at regular intervals -3. Returns when job completes, fails, or times out - -## Manual Job Control - -For advanced use cases, use manual job control methods to manage the job lifecycle directly. - -### Submit Job - -Submit a job and receive a job ID without waiting for completion: - -```typescript -const response = await client.prompt({ - prompt: "What are trending tokens?", -}); - -console.log(response.jobId); // "job_abc123def456" -console.log(response.status); // "pending" +pending → processing → completed + ↘ failed + ↘ cancelled ``` -The `prompt` method returns immediately with job metadata, allowing the application to continue other work while the job processes. - -### Check Job Status - -Query the current status of a job at any time: - -```typescript -const status = await client.getJobStatus("job_abc123def456"); - -console.log(status); -// { -// jobId: "job_abc123def456", -// status: "completed", -// prompt: "What are trending tokens?", -// response: "The trending tokens on Base are...", -// transactions: [], -// richData: [...], -// processingTime: 5230 -// } -``` +| State | Cancellable | Description | +|-------|-------------|-------------| +| pending | Yes | Awaiting processing | +| processing | Yes | Actively processing | +| completed | No | Finished successfully | +| failed | No | Encountered error | +| cancelled | No | Cancelled by user | -### Poll Until Complete +## Usage Examples -Poll a job until it reaches a terminal state (completed, failed, or cancelled): +### Recommended: promptAndWait ```typescript -const result = await client.pollJob({ - jobId: "job_abc123def456", - interval: 2000, // Poll every 2 seconds (default) - maxAttempts: 150, // Maximum poll attempts (default: ~5 min at 2s) - timeout: 300000, // Overall timeout in ms (default: 5 min) +const result = await client.promptAndWait({ + prompt: "Swap 0.1 ETH to USDC", + timeout: 60000, }); if (result.status === "completed") { console.log(result.response); -} else if (result.status === "failed") { - console.error(result.error); } ``` -### Cancel Job - -Cancel a pending or processing job: +### Manual Job Control ```typescript -const cancelResult = await client.cancelJob("job_abc123def456"); +// Submit without waiting +const { jobId } = await client.prompt({ prompt: "What are trending tokens?" }); -console.log(cancelResult); -// { -// status: "cancelled", -// cancelledAt: "2024-01-15T10:30:00.000Z", -// jobId: "job_abc123def456" -// } -``` +// Check status later +const status = await client.getJobStatus(jobId); -**Important**: Only jobs in `pending` or `processing` states can be cancelled. Completed or failed jobs cannot be cancelled. - -## Job Lifecycle - -Jobs progress through the following states: - -``` -pending → processing → completed - ↘ failed - ↘ cancelled +// Or poll until complete +const result = await client.pollJob({ jobId, timeout: 60000 }); ``` -| State | Description | Cancellable | -|-------|-------------|-------------| -| pending | Job submitted, awaiting processing | Yes | -| processing | Job actively being processed | Yes | -| completed | Job finished successfully | No | -| failed | Job encountered an error | No | -| cancelled | Job was cancelled by user | No | - -## Job Status Response - -The complete job status response interface: +### Cancel Job ```typescript -interface JobStatusResponse { - jobId: string; - status: "pending" | "processing" | "completed" | "failed" | "cancelled"; - prompt: string; // Original prompt - response?: string; // AI response (when completed) - transactions?: Transaction[]; // Transaction data (when applicable) - richData?: RichDataItem[]; // Charts, cards, tables - error?: string; // Error message (when failed) - processingTime?: number; // Time in milliseconds - cancellable?: boolean; // Whether job can be cancelled - createdAt?: string; // ISO timestamp - completedAt?: string; // ISO timestamp (when terminal) -} - -interface Transaction { - type: string; - metadata: { - __ORIGINAL_TX_DATA__: object; - transaction: object; - allowanceTarget?: string; - }; -} - -interface RichDataItem { - type: "chart" | "social-card" | "table" | "image"; - url?: string; - text?: string; - rows?: any[]; -} +const { jobId } = await client.prompt({ prompt: "..." }); +await client.cancelJob(jobId); ``` -## Batch Job Processing - -Submit multiple jobs in parallel for efficient batch processing: +### Batch Processing ```typescript -const prompts = [ - "What is the price of ETH?", - "What is the price of BTC?", - "What are trending tokens on Base?", -]; +const prompts = ["Price of ETH", "Price of BTC", "Price of SOL"]; -// Submit all jobs in parallel +// Submit all in parallel const jobs = await Promise.all( prompts.map(prompt => client.prompt({ prompt })) ); -console.log(`Submitted ${jobs.length} jobs`); -// ["job_abc123", "job_def456", "job_ghi789"] - -// Wait for all jobs to complete +// Wait for all to complete const results = await Promise.all( jobs.map(job => client.pollJob({ jobId: job.jobId })) ); - -// Process results -results.forEach((result, index) => { - console.log(`Query: ${prompts[index]}`); - console.log(`Result: ${result.response}`); -}); -``` - -### Batch with Concurrency Limit - -For large batches, limit concurrent jobs to avoid rate limiting: - -```typescript -async function batchWithLimit(prompts: string[], concurrency: number = 5) { - const results: any[] = []; - - for (let i = 0; i < prompts.length; i += concurrency) { - const batch = prompts.slice(i, i + concurrency); - - // Submit batch - const jobs = await Promise.all( - batch.map(prompt => client.prompt({ prompt })) - ); - - // Wait for batch - const batchResults = await Promise.all( - jobs.map(job => client.pollJob({ jobId: job.jobId })) - ); - - results.push(...batchResults); - - // Optional: delay between batches - if (i + concurrency < prompts.length) { - await new Promise(r => setTimeout(r, 1000)); - } - } - - return results; -} - -const results = await batchWithLimit(hundredPrompts, 10); -``` - -## Retry Pattern - -Implement retry logic for failed jobs with exponential backoff: - -```typescript -async function withRetry( - prompt: string, - maxRetries: number = 3, - baseDelay: number = 1000 -): Promise { - for (let attempt = 0; attempt < maxRetries; attempt++) { - try { - const result = await client.promptAndWait({ - prompt, - timeout: 60000, - }); - - if (result.status === "completed") { - return result; - } - - // Job failed, prepare for retry - console.log(`Attempt ${attempt + 1} failed: ${result.error}`); - - } catch (error) { - console.log(`Attempt ${attempt + 1} threw error: ${error}`); - } - - // Exponential backoff before retry - if (attempt < maxRetries - 1) { - const delay = baseDelay * Math.pow(2, attempt); - console.log(`Waiting ${delay}ms before retry...`); - await new Promise(r => setTimeout(r, delay)); - } - } - - throw new Error(`Failed after ${maxRetries} attempts`); -} - -// Usage -try { - const result = await withRetry("Swap 0.1 ETH to USDC"); - console.log(result.response); -} catch (error) { - console.error("All retries exhausted:", error); -} -``` - -## Timeout Handling - -Handle timeouts gracefully in long-running operations: - -```typescript -async function withTimeout( - prompt: string, - timeoutMs: number = 60000 -): Promise { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - - try { - const { jobId } = await client.prompt({ prompt }); - - // Poll with abort signal - const result = await client.pollJob({ - jobId, - timeout: timeoutMs, - }); - - clearTimeout(timeoutId); - return result; - - } catch (error) { - clearTimeout(timeoutId); - - if (error.name === "AbortError") { - throw new Error(`Request timed out after ${timeoutMs}ms`); - } - throw error; - } -} ``` ## Timing Guidelines -Expected processing times by operation type: - -| Operation | Typical Time | Timeout Recommendation | -|-----------|--------------|------------------------| +| Operation | Typical Time | Recommended Timeout | +|-----------|--------------|---------------------| | Price queries | 2-5s | 15s | | Balance checks | 2-5s | 15s | | Token swaps | 5-15s | 60s | | Cross-chain bridges | 10-30s | 120s | -| Complex analysis | 10-30s | 60s | | NFT operations | 5-15s | 60s | -Adjust polling intervals and timeouts based on operation type: - -```typescript -// Fast query - short timeout, fast polling -const price = await client.promptAndWait({ - prompt: "Price of ETH", - timeout: 15000, -}); - -// Swap operation - longer timeout -const swap = await client.promptAndWait({ - prompt: "Swap 1 ETH to USDC", - timeout: 60000, -}); - -// Manual polling with custom interval for slow operations -const bridge = await client.pollJob({ - jobId: bridgeJobId, - interval: 5000, // Slower polling for slow operations - timeout: 120000, // 2 minute timeout for bridges -}); -``` - -## Error Handling - -Handle job-related errors appropriately: - -```typescript -try { - const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC", - }); - - switch (result.status) { - case "completed": - console.log("Success:", result.response); - break; - - case "failed": - console.error("Job failed:", result.error); - // Optionally retry - break; - - case "cancelled": - console.log("Job was cancelled"); - break; - } - -} catch (error) { - if (error.message.includes("timeout")) { - console.error("Request timed out"); - } else if (error.message.includes("rate limit")) { - console.error("Rate limited, try again later"); - } else { - console.error("Unexpected error:", error); - } -} -``` - -## Cost - -Each job costs $0.01 USDC via x402 micropayments, charged at job submission time regardless of final status. Cancelled and failed jobs still incur the charge. - -## Best Practices +## Related Skills -1. **Use promptAndWait for simple cases**: Manual job control is only needed for advanced scenarios -2. **Set appropriate timeouts**: Match timeout to expected operation duration -3. **Implement retry logic**: Some failures are transient and succeed on retry -4. **Batch efficiently**: Group related queries but respect rate limits -5. **Handle all terminal states**: Check for completed, failed, and cancelled -6. **Clean up cancelled jobs**: Do not continue polling cancelled jobs -7. **Log job IDs**: Store job IDs for debugging and support requests +- **sdk-wallet-operations**: Client setup and configuration +- **sdk-capabilities**: Full list of supported operations diff --git a/x402-sdk-dev/skills/sdk-token-swaps/SKILL.md b/x402-sdk-dev/skills/sdk-token-swaps/SKILL.md index f299078..d74d01c 100644 --- a/x402-sdk-dev/skills/sdk-token-swaps/SKILL.md +++ b/x402-sdk-dev/skills/sdk-token-swaps/SKILL.md @@ -1,428 +1,101 @@ --- -name: SDK Token Swaps +name: Bankr x402 SDK - Token Swaps description: This skill should be used when the user asks to "swap tokens", "exchange ETH for USDC", "buy DEGEN", "sell tokens", "swap on Base", "trade crypto", "convert ETH to WETH", "exchange tokens", "token swap code", "0x routing", or any token swap operation. Also use for questions about ERC20 approvals, allowanceTarget, swap transaction execution, or building swap transactions with the Bankr SDK. -version: 1.0.0 +version: 1.1.0 --- # SDK Token Swaps -Build and execute multi-chain token swaps with AI-powered 0x routing using the Bankr SDK. +Build and execute token swaps with AI-powered 0x routing. -## Overview +## Prompt Patterns -The Bankr SDK provides a natural language interface for token swaps across multiple chains. Swaps are routed through 0x protocol for optimal pricing and executed via smart contract transactions. The SDK handles route finding, price quotes, and transaction building automatically. +| Pattern | Example | +|---------|---------| +| Amount-based | "Swap 0.1 ETH to USDC" | +| Value-based | "Buy $100 worth of DEGEN" | +| Percentage | "Swap 50% of my ETH to USDC" | +| Sell all | "Sell all my DEGEN" | +| Chain-specific | "Swap ETH to USDC on Polygon" | -**Key capabilities:** -- Natural language swap requests -- Multi-chain support (Base, Ethereum, Polygon, Solana) -- 0x-powered routing for best prices -- Automatic transaction building -- ERC20 approval handling guidance - -## CRITICAL: ERC20 Approval Requirement - -For ERC20 token swaps (selling any token other than native ETH), you must approve the token before executing the swap. The SDK provides two approaches: - -### Recommended: Use `approvalTx` (Simplified) - -The SDK returns a pre-built approval transaction when needed: - -```typescript -import { BankrClient } from "@bankr/sdk"; - -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, -}); - -const result = await client.promptAndWait({ - prompt: "Swap 100 USDC to WETH on Base" -}); - -const swapTx = result.transactions?.find(tx => tx.type === "swap"); - -if (swapTx?.metadata.approvalRequired) { - // Step 1: Execute the pre-built approval transaction - await wallet.sendTransaction(swapTx.metadata.approvalTx); - - // Step 2: Execute the swap transaction - await wallet.sendTransaction(swapTx.metadata.transaction); -} else { - // No approval needed (ETH swap or already approved) - await wallet.sendTransaction(swapTx.metadata.transaction); -} -``` - -### Alternative: Manual Approval with `allowanceTarget` - -For more control, use the `allowanceTarget` to build your own approval: - -```typescript -const swapTx = result.transactions?.find(tx => tx.type === "swap"); - -if (swapTx?.metadata.allowanceTarget) { - // Build your own approval transaction - await approveERC20( - inputTokenAddress, - swapTx.metadata.allowanceTarget, - swapAmount - ); - - await wallet.sendTransaction(swapTx.metadata.transaction); -} -``` - -### Approval Fields Reference - -| Field | Type | Description | -|-------|------|-------------| -| `approvalRequired` | `boolean` | Whether approval is needed before swap | -| `approvalTx` | `{ to: string, data: string }` | Pre-built approval transaction (ready to send) | -| `allowanceTarget` | `string` | 0x AllowanceHolder address (for manual approval) | - -**Important References:** -- [0x AllowanceHolder Documentation](https://0x.org/docs/introduction/0x-cheat-sheet#allowanceholder-recommended) -- [0x Settler Contract Addresses](https://github.com/0xProject/0x-settler/blob/master/README.md#allowanceholder-addresses) - -## Basic Swap - -Initialize the client and execute a simple swap: - -```typescript -import { BankrClient } from "@bankr/sdk"; - -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, -}); - -const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC on Base", -}); - -if (result.status === "completed" && result.transactions) { - const tx = result.transactions[0].metadata.transaction; - // Execute transaction with viem/ethers -} ``` - -## Swap Prompt Formats - -The SDK understands various natural language formats for swap requests: - -### Amount-Based Swaps - -Specify exact token amounts to swap: - -```typescript -// Swap specific amount of input token +# Amount Swaps "Swap 0.1 ETH to USDC" "Exchange 100 USDC for WETH" "Swap 1000 DEGEN to ETH" -// With chain specification -"Swap 0.1 ETH to USDC on Base" -"Exchange 100 USDC for WETH on Ethereum" -``` - -### Value-Based Swaps - -Specify USD value to buy or sell: - -```typescript -// Buy tokens by USD value +# Value Swaps "Buy $100 worth of DEGEN" "Purchase $50 of ETH" -// Sell tokens by USD value -"Sell $500 of ETH for USDC" -"Exchange $200 worth of DEGEN to USDC" -``` - -### Percentage-Based Swaps - -Swap a percentage of holdings: - -```typescript -// Percentage of holdings +# Percentage Swaps "Swap 50% of my ETH to USDC" "Sell 25% of my DEGEN" -"Exchange half my USDC for ETH" -``` - -### Chain-Specific Swaps - -Explicitly specify the chain: - -```typescript -// Base (default) -"Swap ETH to USDC on Base" - -// Ethereum mainnet -"Swap ETH to USDC on Ethereum" -"Exchange USDC for WETH on mainnet" -// Polygon -"Swap MATIC to USDC on Polygon" - -// Solana -"Swap SOL to USDC on Solana" -``` - -## Multi-Chain Support - -Supported blockchain networks for swaps: - -| Chain | Native Token | Notes | -|-------|-------------|-------| -| Base | ETH | Default chain, lowest fees | -| Ethereum | ETH | Mainnet, higher gas | -| Polygon | MATIC | L2, low fees | -| Solana | SOL | Alternative ecosystem | - -Base is the default chain. Specify other chains explicitly in the prompt. - -## Swap Response Structure - -Swap responses include transaction data ready for execution: - -```typescript -interface SwapTransaction { - type: "swap"; - metadata: { - __ORIGINAL_TX_DATA__: { - chain: string; // "base", "ethereum", etc. - humanReadableMessage: string; // "Swap 0.1 ETH for ~250 USDC" - inputTokenAddress: string; // Input token contract address - inputTokenAmount: string; // "0.1" - inputTokenTicker: string; // "ETH" - outputTokenAddress: string; // Output token contract address - outputTokenTicker: string; // "USDC" - receiver: string; // Receiving wallet address - }; - // Approval handling (for ERC20 swaps) - approvalRequired?: boolean; // Whether approval needed before swap - approvalTx?: { // Pre-built approval transaction - to: string; - data: string; - }; - allowanceTarget?: string; // 0x AllowanceHolder (for manual approval) - // Swap transaction - transaction: { - chainId: number; // Chain ID (8453 for Base) - to: string; // Contract address - data: string; // Encoded transaction data - gas: string; // Gas limit - gasPrice?: string; // Gas price in wei - value: string; // ETH value to send (wei) - }; - }; -} -``` - -## Execute Swap with Viem - -Complete example using viem to execute a swap: - -```typescript -import { createWalletClient, createPublicClient, http } from "viem"; -import { privateKeyToAccount } from "viem/accounts"; -import { base } from "viem/chains"; - -// Initialize wallet -const account = privateKeyToAccount(process.env.WALLET_PK as `0x${string}`); -const walletClient = createWalletClient({ - account, - chain: base, - transport: http(), -}); -const publicClient = createPublicClient({ - chain: base, - transport: http(), -}); - -// Get swap transaction from SDK -const result = await client.promptAndWait({ - prompt: "Swap 100 USDC to WETH" -}); - -if (result.status !== "completed" || !result.transactions?.length) { - throw new Error("Swap failed or no transactions returned"); -} - -const swapTx = result.transactions.find(tx => tx.type === "swap"); -const tx = swapTx.metadata.transaction; - -// Handle ERC20 approval if needed (using pre-built approvalTx) -if (swapTx.metadata.approvalRequired && swapTx.metadata.approvalTx) { - const approvalHash = await walletClient.sendTransaction({ - to: swapTx.metadata.approvalTx.to as `0x${string}`, - data: swapTx.metadata.approvalTx.data as `0x${string}`, - }); - await publicClient.waitForTransactionReceipt({ hash: approvalHash }); - console.log(`Approval confirmed: ${approvalHash}`); -} - -// Execute swap -const hash = await walletClient.sendTransaction({ - to: tx.to as `0x${string}`, - data: tx.data as `0x${string}`, - value: BigInt(tx.value), - gas: BigInt(tx.gas), -}); - -console.log(`Swap transaction: ${hash}`); +# Chain-Specific +"Swap 0.1 ETH to USDC on Base" +"Exchange 100 USDC for WETH on Ethereum" ``` -## Execute Swap with Ethers +## ERC20 Approval Handling -Complete example using ethers.js v6: +For ERC20 swaps (selling tokens other than ETH), approval is required before the swap. ```typescript -import { ethers } from "ethers"; - -// Initialize wallet -const provider = new ethers.JsonRpcProvider(process.env.RPC_URL); -const wallet = new ethers.Wallet(process.env.WALLET_PK, provider); - -// Get swap transaction const result = await client.promptAndWait({ - prompt: "Swap 100 USDC to WETH" + prompt: "Swap 100 USDC to WETH", }); const swapTx = result.transactions?.find(tx => tx.type === "swap"); -const tx = swapTx?.metadata.transaction; - -if (!tx) { - throw new Error("No transaction data"); -} -// Handle ERC20 approval if needed (using pre-built approvalTx) -if (swapTx.metadata.approvalRequired && swapTx.metadata.approvalTx) { - const approveTx = await wallet.sendTransaction({ - to: swapTx.metadata.approvalTx.to, - data: swapTx.metadata.approvalTx.data, - }); - await approveTx.wait(); - console.log(`Approval confirmed: ${approveTx.hash}`); +// Check if approval is needed +if (swapTx?.metadata.approvalRequired) { + // Execute pre-built approval transaction first + await wallet.sendTransaction(swapTx.metadata.approvalTx); } -// Execute swap -const swapTransaction = await wallet.sendTransaction({ - to: tx.to, - data: tx.data, - value: BigInt(tx.value), - gasLimit: BigInt(tx.gas), -}); - -console.log(`Swap transaction: ${swapTransaction.hash}`); -await swapTransaction.wait(); +// Then execute the swap +await wallet.sendTransaction(swapTx.metadata.transaction); ``` -## Error Handling - -Handle common swap errors: - -```typescript -const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC" -}); - -// Check status -if (result.status === "failed") { - const error = result.error || "Unknown error"; +## Approval Fields - if (error.includes("Insufficient balance")) { - console.error("Not enough tokens to swap"); - } else if (error.includes("No route found")) { - console.error("No swap route available for this pair"); - } else if (error.includes("Slippage")) { - console.error("Price moved too much, try again"); - } else { - console.error(`Swap failed: ${error}`); - } - return; -} - -// Check for transactions -if (!result.transactions?.length) { - console.error("No swap transactions returned"); - return; -} - -// Verify transaction data -const tx = result.transactions[0].metadata.transaction; -if (!tx.to || !tx.data) { - console.error("Invalid transaction data"); - return; -} +| Field | Description | +|-------|-------------| +| `approvalRequired` | Whether approval needed before swap | +| `approvalTx` | Pre-built approval transaction (ready to send) | +| `allowanceTarget` | 0x AllowanceHolder address (for manual approval) | -// Proceed with execution -console.log(result.response); -``` +## Usage -## Verifying Swap Before Execution +```typescript +import { BankrClient } from "@bankr/sdk"; -Always verify transaction details before signing: +const client = new BankrClient({ + privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, +}); -```typescript const result = await client.promptAndWait({ - prompt: "Swap 100 USDC to ETH" + prompt: "Swap 0.1 ETH to USDC on Base", }); -const swapTx = result.transactions?.[0]; -const txData = swapTx?.metadata.__ORIGINAL_TX_DATA__; - -console.log("Swap details:"); -console.log(` From: ${txData.inputTokenAmount} ${txData.inputTokenTicker}`); -console.log(` To: ${txData.outputTokenTicker}`); -console.log(` Chain: ${txData.chain}`); -console.log(` Receiver: ${txData.receiver}`); -console.log(` Message: ${txData.humanReadableMessage}`); - -// Verify receiver is correct -if (txData.receiver !== expectedWallet) { - throw new Error("Receiver wallet mismatch!"); -} - -// Verify chain is correct -if (txData.chain !== "base") { - console.warn(`Swap is on ${txData.chain}, not Base`); +if (result.status === "completed" && result.transactions?.length) { + const tx = result.transactions[0].metadata.transaction; + await wallet.sendTransaction(tx); } ``` -## Swap Best Practices - -1. **Always check allowanceTarget**: ERC20 swaps require approval before execution -2. **Verify transaction details**: Check amounts, tokens, and receiver before signing -3. **Handle approvals properly**: Approve exact amounts or use infinite approval carefully -4. **Check response status**: Always verify `result.status === "completed"` -5. **Use appropriate timeouts**: Swap quotes expire; set reasonable timeouts (60s recommended) -6. **Handle slippage**: Large swaps may need retries if price moves -7. **Test on testnets**: Verify integration before mainnet transactions - -## Common Token Addresses - -For reference when building approval transactions: - -| Token | Base Address | -|-------|-------------| -| USDC | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | -| WETH | `0x4200000000000000000000000000000000000006` | -| DEGEN | `0x4ed4E862860beD51a9570b96d89aF5E1B0Efefed` | - -## Cost - -Each swap request costs $0.01 USDC via x402 micropayments. This covers the SDK query; gas fees for the actual swap transaction are paid separately from the executing wallet. - -## Response Times +## Supported Chains -Expected response times for swap operations: +| Chain | Native Token | Default | +|-------|-------------|---------| +| Base | ETH | Yes | +| Ethereum | ETH | No | +| Polygon | MATIC | No | +| Solana | SOL | No | -| Operation | Typical Time | -|-----------|--------------| -| Simple swap quote | 3-5 seconds | -| Complex routing | 5-10 seconds | -| Multi-hop routes | 8-15 seconds | +## Related Skills -Set timeouts accordingly: 60 seconds recommended for swap operations. +- **sdk-capabilities**: Full list of supported operations +- **sdk-transaction-builder**: Other transaction types (transfers, NFTs) +- **sdk-wallet-operations**: Client setup and configuration diff --git a/x402-sdk-dev/skills/sdk-transaction-builder/SKILL.md b/x402-sdk-dev/skills/sdk-transaction-builder/SKILL.md index 9aacf51..0f40ff2 100644 --- a/x402-sdk-dev/skills/sdk-transaction-builder/SKILL.md +++ b/x402-sdk-dev/skills/sdk-transaction-builder/SKILL.md @@ -1,421 +1,95 @@ --- -name: SDK Transaction Builder +name: Bankr x402 SDK - Transaction Builder description: This skill should be used when the user asks to "send tokens", "transfer ETH", "send USDC to", "transfer NFT", "wrap ETH", "unwrap WETH", "bridge tokens", "mint NFT", "buy NFT", "approve token", "build transaction", "DeFi transaction", or needs to build transactions for transfers, approvals, NFT operations, cross-chain bridges, ETH/WETH conversions, or DeFi interactions beyond simple swaps using the Bankr SDK. -version: 1.0.0 +version: 1.1.0 --- # SDK Transaction Builder -Build complex blockchain transactions with AI assistance using the Bankr SDK. - -## Overview - -The Bankr SDK supports building various transaction types beyond simple token swaps. Use natural language prompts to generate transaction data for transfers, NFT operations, cross-chain bridges, and DeFi interactions. The SDK returns ready-to-execute transaction objects. - -**Key capabilities:** -- Token transfers (ERC20 and native) -- NFT transfers, mints, and purchases -- ETH/WETH wrapping and unwrapping -- Cross-chain token bridges -- ERC20 approvals -- DeFi protocol interactions +Build blockchain transactions for transfers, NFTs, bridges, and DeFi operations. ## Transaction Types -The SDK supports the following transaction types: - -| Type | Description | Use Case | -|------|-------------|----------| -| `swap` | Token swaps | Exchange one token for another | -| `approval` | ERC20 approvals | Grant spending permission | -| `transfer_erc20` | ERC20 transfers | Send tokens to address | -| `transfer_eth` | ETH transfers | Send native ETH | -| `convert_eth_to_weth` | Wrap ETH | Convert ETH to WETH | -| `convert_weth_to_eth` | Unwrap WETH | Convert WETH to ETH | -| `transfer_nft` | NFT transfers | Send NFT to address | -| `mint_manifold_nft` | Manifold mints | Mint from Manifold contracts | -| `mint_seadrop_nft` | SeaDrop mints | Mint from SeaDrop contracts | -| `buy_nft` | NFT purchases | Buy NFT from marketplace | -| `swapCrossChain` | Cross-chain bridges | Move tokens between chains | -| `avantisTrade` | Avantis perpetuals | Trade perpetual futures | -| `manage_bankr_staking` | Bankr staking | Stake/unstake BANKR tokens | - -## ERC20 Transfers +| Type | Description | Example Prompt | +|------|-------------|----------------| +| `transfer_erc20` | Send ERC20 tokens | "Send 100 USDC to 0x..." | +| `transfer_eth` | Send native ETH | "Send 0.1 ETH to 0x..." | +| `convert_eth_to_weth` | Wrap ETH | "Wrap 0.5 ETH" | +| `convert_weth_to_eth` | Unwrap WETH | "Unwrap 1 WETH" | +| `transfer_nft` | Send NFT | "Transfer my NFT #123 to 0x..." | +| `buy_nft` | Purchase NFT | "Buy the cheapest Pudgy Penguin" | +| `mint_manifold_nft` | Mint from Manifold | "Mint from Manifold at 0x..." | +| `mint_seadrop_nft` | Mint from SeaDrop | "Mint from SeaDrop at 0x..." | +| `swapCrossChain` | Bridge tokens | "Bridge 100 USDC from Ethereum to Base" | -Send ERC20 tokens to another address: +## Prompt Patterns -```typescript -import { BankrClient } from "@bankr/sdk"; - -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, -}); - -const result = await client.promptAndWait({ - prompt: "Send 100 USDC to 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", -}); - -if (result.status === "completed" && result.transactions) { - const tx = result.transactions.find(t => t.type === "transfer_erc20"); - // Execute transaction -} ``` - -### Transfer Prompt Examples - -```typescript -// Specific amount +# Transfers "Send 100 USDC to 0x742d35..." "Transfer 0.5 ETH to vitalik.eth" - -// With chain specification "Send 50 USDC to 0x123... on Base" -"Transfer 100 MATIC on Polygon to 0x456..." - -// Multiple recipients (separate requests) -"Send 25 USDC to 0xAlice..." -"Send 25 USDC to 0xBob..." -``` - -## Native ETH Transfers - -Send native ETH: - -```typescript -const result = await client.promptAndWait({ - prompt: "Send 0.1 ETH to 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", -}); - -const tx = result.transactions?.find(t => t.type === "transfer_eth"); -``` - -## ETH/WETH Conversions - -Wrap ETH to WETH or unwrap WETH to ETH: - -```typescript -// Wrap ETH to WETH -const wrapResult = await client.promptAndWait({ - prompt: "Wrap 0.5 ETH to WETH", -}); -const wrapTx = wrapResult.transactions?.find( - t => t.type === "convert_eth_to_weth" -); +# ETH/WETH +"Wrap 0.5 ETH to WETH" +"Unwrap 1 WETH to ETH" -// Unwrap WETH to ETH -const unwrapResult = await client.promptAndWait({ - prompt: "Unwrap 1 WETH to ETH", -}); - -const unwrapTx = unwrapResult.transactions?.find( - t => t.type === "convert_weth_to_eth" -); -``` - -### When to Wrap/Unwrap - -- **Wrap ETH**: Some DeFi protocols and swaps require WETH instead of native ETH -- **Unwrap WETH**: Convert back to native ETH for transfers or gas payments - -## NFT Operations - -### Transfer NFT - -Send an NFT to another address: - -```typescript -const result = await client.promptAndWait({ - prompt: "Transfer my Pudgy Penguin #1234 to 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", -}); - -const tx = result.transactions?.find(t => t.type === "transfer_nft"); -``` - -### Mint NFT - -Mint from supported platforms: - -```typescript -// Manifold mint -const manifoldMint = await client.promptAndWait({ - prompt: "Mint NFT from Manifold contract 0xabc123...", -}); +# NFTs +"Transfer my Pudgy Penguin #1234 to 0x..." +"Buy the cheapest Pudgy Penguin on OpenSea" +"Mint NFT from Manifold contract 0x..." -// SeaDrop mint -const seadropMint = await client.promptAndWait({ - prompt: "Mint from SeaDrop collection 0xdef456...", -}); -``` - -### Buy NFT - -Purchase NFT from marketplace: - -```typescript -const result = await client.promptAndWait({ - prompt: "Buy the cheapest Pudgy Penguin on OpenSea", -}); - -const buyTx = result.transactions?.find(t => t.type === "buy_nft"); - -if (buyTx) { - console.log(`Price: ${buyTx.metadata.__ORIGINAL_TX_DATA__.inputTokenAmount}`); - // Execute purchase transaction -} -``` - -## Cross-Chain Bridges - -Bridge tokens between chains: - -```typescript -const result = await client.promptAndWait({ - prompt: "Bridge 100 USDC from Ethereum to Base", -}); - -const bridgeTx = result.transactions?.find(t => t.type === "swapCrossChain"); - -if (bridgeTx) { - const txData = bridgeTx.metadata.__ORIGINAL_TX_DATA__; - console.log(`From: ${txData.chain}`); - console.log(`Amount: ${txData.inputTokenAmount} ${txData.inputTokenTicker}`); - console.log(`Receiver: ${txData.receiver}`); -} -``` - -### Bridge Prompt Examples - -```typescript -// Specific chains +# Cross-Chain "Bridge 100 USDC from Ethereum to Base" "Move 0.5 ETH from Base to Ethereum" - -// With amount -"Bridge $500 worth of ETH from Polygon to Base" ``` -**Note**: Cross-chain bridges take longer (10-30 seconds for quote, plus on-chain confirmation time). - -## ERC20 Approvals - -Build approval transactions for token spending: +## Usage ```typescript -const result = await client.promptAndWait({ - prompt: "Approve Uniswap to spend my USDC", -}); - -const approvalTx = result.transactions?.find(t => t.type === "approval"); -``` - -## Transaction Metadata - -All transactions include metadata for verification: - -```typescript -interface TransactionMetadata { - __ORIGINAL_TX_DATA__: { - chain: string; // Target chain - humanReadableMessage: string; // Human description - inputTokenAmount: string; // Amount being sent/swapped - inputTokenTicker: string; // Token symbol - outputTokenTicker: string; // Output token (for swaps) - receiver: string; // Recipient address - }; - transaction: { - chainId: number; // Chain ID (8453 = Base) - to: string; // Contract/recipient address - data: string; // Encoded call data - gas: string; // Gas limit - gasPrice: string; // Gas price (wei) - value: string; // Native value (wei) - }; - allowanceTarget?: string; // For swaps requiring approval -} -``` - -## Multi-Step Workflows - -Complex operations may require multiple transactions: - -```typescript -// Example: Wrap ETH then swap WETH to USDC - -// Step 1: Wrap ETH -const wrapResult = await client.promptAndWait({ - prompt: "Wrap 1 ETH to WETH", -}); -const wrapTx = wrapResult.transactions?.[0]; - -// Execute wrap transaction -const wrapHash = await wallet.sendTransaction(wrapTx.metadata.transaction); -await publicClient.waitForTransactionReceipt({ hash: wrapHash }); - -// Step 2: Swap WETH to USDC -const swapResult = await client.promptAndWait({ - prompt: "Swap 1 WETH to USDC", -}); -const swapTx = swapResult.transactions?.[0]; - -// Handle approval if needed -if (swapTx.metadata.allowanceTarget) { - await approveToken(wethAddress, swapTx.metadata.allowanceTarget, amount); -} - -// Execute swap -const swapHash = await wallet.sendTransaction(swapTx.metadata.transaction); -``` - -## Transaction Validation - -Validate transaction data before execution: - -```typescript -function validateTransaction(tx: any): boolean { - const txData = tx.metadata?.transaction; - - // Check required fields - if (!txData) { - console.error("Missing transaction data"); - return false; - } - - if (!txData.to) { - console.error("Missing 'to' address"); - return false; - } - - if (!txData.data && !txData.value) { - console.error("Missing data and value"); - return false; - } - - if (!txData.chainId) { - console.error("Missing chainId"); - return false; - } - - return true; -} - -// Usage -const result = await client.promptAndWait({ prompt: "..." }); - -if (result.transactions?.every(validateTransaction)) { - // All transactions valid, proceed with execution - for (const tx of result.transactions) { - await executeTx(tx); - } -} else { - console.error("Invalid transaction data"); -} -``` - -## Execute with Viem - -Execute any transaction type with viem: - -```typescript -import { createWalletClient, createPublicClient, http } from "viem"; -import { privateKeyToAccount } from "viem/accounts"; -import { base } from "viem/chains"; +import { BankrClient } from "@bankr/sdk"; -const account = privateKeyToAccount(process.env.WALLET_PK as `0x${string}`); -const walletClient = createWalletClient({ - account, - chain: base, - transport: http(), -}); -const publicClient = createPublicClient({ - chain: base, - transport: http(), +const client = new BankrClient({ + privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, }); -async function executeTransaction(tx: any) { - const txData = tx.metadata.transaction; - - const hash = await walletClient.sendTransaction({ - to: txData.to as `0x${string}`, - data: txData.data as `0x${string}`, - value: BigInt(txData.value || "0"), - gas: BigInt(txData.gas), - }); - - const receipt = await publicClient.waitForTransactionReceipt({ hash }); - return receipt; -} - -// Execute all transactions in result +// Transfer tokens const result = await client.promptAndWait({ - prompt: "Send 100 USDC to 0x742d35...", + prompt: "Send 100 USDC to 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0", }); if (result.status === "completed" && result.transactions) { - for (const tx of result.transactions) { - const receipt = await executeTransaction(tx); - console.log(`Transaction ${tx.type}: ${receipt.transactionHash}`); - } + const tx = result.transactions[0].metadata.transaction; + await wallet.sendTransaction(tx); } ``` -## Error Handling +## Transaction Metadata -Handle transaction-specific errors: +All transactions include metadata for verification: ```typescript -const result = await client.promptAndWait({ - prompt: "Send 100 USDC to 0x742d35...", -}); - -if (result.status === "failed") { - const error = result.error || ""; - - if (error.includes("Insufficient balance")) { - console.error("Not enough tokens for this transfer"); - } else if (error.includes("Invalid address")) { - console.error("The recipient address is invalid"); - } else if (error.includes("NFT not found")) { - console.error("The specified NFT was not found in wallet"); - } else if (error.includes("Bridge not supported")) { - console.error("This chain pair is not supported for bridging"); - } else { - console.error(`Transaction failed: ${error}`); - } - return; -} +const tx = result.transactions[0]; +const meta = tx.metadata.__ORIGINAL_TX_DATA__; -if (!result.transactions?.length) { - console.error("No transactions generated"); - return; -} +console.log(`Chain: ${meta.chain}`); +console.log(`Amount: ${meta.inputTokenAmount} ${meta.inputTokenTicker}`); +console.log(`To: ${meta.receiver}`); +console.log(`Message: ${meta.humanReadableMessage}`); ``` ## Timing Guidelines -Expected response times by transaction type: - -| Transaction Type | Typical Time | -|-----------------|--------------| -| ERC20 transfer | 2-5 seconds | -| ETH transfer | 2-5 seconds | -| ETH/WETH wrap/unwrap | 2-5 seconds | -| NFT transfer | 3-5 seconds | -| NFT purchase | 5-10 seconds | -| NFT mint | 5-10 seconds | -| Cross-chain bridge | 10-30 seconds | - -## Best Practices - -1. **Validate transactions**: Always check transaction data before signing -2. **Verify recipients**: Double-check recipient addresses in metadata -3. **Handle multi-step flows**: Wait for each transaction to confirm before the next -4. **Set appropriate timeouts**: Longer timeouts for bridges and NFT operations -5. **Check status**: Always verify `result.status === "completed"` -6. **Log transaction hashes**: Store hashes for debugging and tracking -7. **Test thoroughly**: Verify transaction flows on testnets before mainnet +| Operation | Typical Time | +|-----------|--------------| +| ERC20/ETH transfer | 2-5s | +| Wrap/Unwrap | 2-5s | +| NFT transfer | 3-5s | +| NFT purchase | 5-10s | +| Cross-chain bridge | 10-30s | -## Cost +## Related Skills -Each transaction request costs $0.01 USDC via x402 micropayments. This covers the SDK query; actual gas fees are paid separately from the executing wallet. +- **sdk-token-swaps**: Token swap patterns and approval handling +- **sdk-capabilities**: Full list of supported operations +- **sdk-wallet-operations**: Client setup and configuration diff --git a/x402-sdk-dev/skills/sdk-wallet-operations/SKILL.md b/x402-sdk-dev/skills/sdk-wallet-operations/SKILL.md index 8afc42d..eaec0f2 100644 --- a/x402-sdk-dev/skills/sdk-wallet-operations/SKILL.md +++ b/x402-sdk-dev/skills/sdk-wallet-operations/SKILL.md @@ -1,73 +1,22 @@ --- -name: SDK Wallet Operations +name: Bankr x402 SDK - Wallet Operations description: This skill should be used when the user asks to "set up the SDK", "initialize BankrClient", "configure wallet", "set up payment wallet", "connect wallet to Bankr", "get wallet address", "set up environment variables", "configure private key", "two wallet setup", "separate payment and trading wallets", or needs help with SDK client initialization, two-wallet configuration, wallet address derivation, environment setup, or BankrClient options. -version: 1.0.0 +version: 1.1.0 --- # SDK Wallet Operations -Initialize and manage the BankrClient with proper wallet configuration for the Bankr SDK. - -## Overview - -The BankrClient is the main entry point for interacting with the Bankr SDK. Proper wallet configuration is essential for x402 micropayments and transaction building. The SDK supports a two-wallet system that separates payment concerns from transaction execution. - -**Key concepts:** -- Payment wallet: Signs x402 USDC payments (required) -- Context wallet: Receives swapped tokens and NFTs (optional) -- Two-wallet separation for enhanced security -- Environment-based configuration - -## SDK Methods Summary - -The BankrClient provides 6 core methods: - -| Method | Description | Use Case | -|--------|-------------|----------| -| `promptAndWait()` | Submit prompt and wait for result | **Recommended** for most use cases | -| `prompt()` | Submit prompt, return immediately | Background processing | -| `pollJob()` | Poll until job completes | Manual job tracking | -| `getJobStatus()` | Check job status once | Custom polling logic | -| `cancelJob()` | Cancel a pending/processing job | Stop unwanted jobs | -| `getWalletAddress()` | Get derived wallet address | Verify payment wallet | - -```typescript -// Most common pattern -const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC", -}); - -// Get wallet address (no API call) -const address = client.getWalletAddress(); -``` +Initialize and configure the BankrClient with proper wallet setup. ## Two-Wallet System -The Bankr SDK uses two distinct wallet concepts: - -### Payment Wallet (`privateKey`) - -The payment wallet is **required** and used for: -- Signing x402 micropayments ($0.01 USDC per request) -- Authenticating with the Bankr API -- Must have USDC balance on Base chain - -The private key is used to derive the wallet address and sign payment transactions. - -### Context Wallet (`walletAddress`) - -The context wallet is **optional** and used for: -- Receiving swapped tokens -- Receiving purchased NFTs -- Providing context for balance queries -- Can be different from the payment wallet - -If not specified, the context wallet defaults to the address derived from the payment wallet's private key. +| Wallet | Purpose | Required | +|--------|---------|----------| +| Payment (`privateKey`) | Signs x402 micropayments ($0.01/request) | Yes | +| Context (`walletAddress`) | Receives swapped tokens, NFTs | No (defaults to payment wallet) | ## Basic Setup -Minimal configuration using a single wallet for both payments and receiving: - ```typescript import { BankrClient } from "@bankr/sdk"; @@ -75,449 +24,72 @@ const client = new BankrClient({ privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, }); -// Get the derived wallet address -const walletAddress = client.getWalletAddress(); -console.log(`Using wallet: ${walletAddress}`); -``` - -This configuration: -- Uses the private key for x402 payments -- Derives the wallet address from the private key -- Uses the same address for receiving tokens - -## Full Configuration - -Complete configuration with all available options: - -```typescript -import { BankrClient } from "@bankr/sdk"; - -const client = new BankrClient({ - // Required: Payment wallet private key - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - - // Optional: Override receiving wallet address - walletAddress: process.env.BANKR_WALLET_ADDRESS, - - // Optional: API base URL (default: production) - baseUrl: "https://api.bankr.bot", - - // Optional: Request timeout in milliseconds (default: 600000 = 10 min) - timeout: 600000, +const result = await client.promptAndWait({ + prompt: "What are my balances?", }); ``` -## Separate Wallets Pattern +## Separate Wallets (Recommended) -For enhanced security, use separate wallets for payments and receiving: +For enhanced security, use different wallets for payments and receiving: ```typescript const client = new BankrClient({ // Hot wallet with minimal USDC for payments privateKey: process.env.PAYMENT_WALLET_PK as `0x${string}`, - - // Cold wallet or trading wallet receives tokens + // Cold/trading wallet receives tokens walletAddress: process.env.RECEIVING_WALLET, }); - -// Payment wallet (hot): pays $0.01 per request -// Receiving wallet (cold): receives swapped USDC, purchased NFTs, etc. -const result = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC", -}); -// USDC goes to RECEIVING_WALLET, not PAYMENT_WALLET -``` - -### Benefits of Separate Wallets - -1. **Security**: Payment wallet exposure is limited to small USDC amounts -2. **Risk management**: Trading funds stay in a separate, more secure wallet -3. **Flexibility**: Different security models for different purposes -4. **Auditability**: Clear separation of payment and trading activities - -### Recommended Setup - -``` -Payment Wallet (Hot): -- Small USDC balance ($5-10 recommended) -- Used only for x402 payments -- Private key in environment - -Receiving Wallet (Cold/Trading): -- Holds main trading funds -- Receives swap outputs -- Can be hardware wallet or multi-sig -- Only address needed (no private key exposed) -``` - -## Per-Request Wallet Override - -Override the receiving wallet for individual requests: - -```typescript -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.DEFAULT_WALLET, -}); - -// Use default wallet -const result1 = await client.promptAndWait({ - prompt: "Swap 0.1 ETH to USDC", -}); - -// Override wallet for this request only -const result2 = await client.promptAndWait({ - prompt: "Buy $100 of DEGEN", - walletAddress: "0xDifferentWallet123...", -}); - -// Back to default wallet -const result3 = await client.promptAndWait({ - prompt: "What are my balances?", -}); ``` -## Configuration Interface +## Configuration Options -Complete TypeScript interface for BankrClient configuration: +| Option | Type | Required | Description | +|--------|------|----------|-------------| +| `privateKey` | `0x${string}` | Yes | Payment wallet private key | +| `walletAddress` | `string` | No | Override receiving wallet | +| `baseUrl` | `string` | No | API endpoint (default: production) | +| `timeout` | `number` | No | Request timeout ms (default: 600000) | -```typescript -interface BankrClientConfig { - /** - * Private key for x402 payment signing. - * Must be a valid Ethereum private key with 0x prefix. - * Required field. - */ - privateKey: `0x${string}`; - - /** - * Wallet address for receiving tokens and providing context. - * If not provided, derived from privateKey. - * Optional field. - */ - walletAddress?: string; - - /** - * API base URL. - * Default: "https://api.bankr.bot" - * Optional field. - */ - baseUrl?: string; - - /** - * Request timeout in milliseconds. - * Default: 600000 (10 minutes) - * Optional field. - */ - timeout?: number; -} -``` +## SDK Methods -## Prompt Options +| Method | Description | +|--------|-------------| +| `promptAndWait()` | Submit prompt and wait for result | +| `prompt()` | Submit prompt, return immediately | +| `pollJob()` | Poll until job completes | +| `getJobStatus()` | Check job status once | +| `cancelJob()` | Cancel pending/processing job | +| `getWalletAddress()` | Get context wallet address | -Options available when making requests: - -```typescript -interface PromptOptions { - /** - * Natural language prompt for the AI. - * Required field. - */ - prompt: string; - - /** - * Override the context wallet for this request only. - * Optional field. - */ - walletAddress?: string; - - /** - * Convert transaction data to XMTP-compatible format. - * Useful for messaging-based transaction flows. - * Default: false - * Optional field. - */ - xmtp?: boolean; -} -``` - -### XMTP Integration - -Enable XMTP format for transaction data when building messaging-based flows: +## Per-Request Override ```typescript +// Override wallet for a single request const result = await client.promptAndWait({ prompt: "Swap 0.1 ETH to USDC", - xmtp: true, // Convert transaction to XMTP format + walletAddress: "0xDifferentWallet...", }); - -// Transaction data formatted for XMTP messaging -console.log(result.transactions); ``` ## Environment Setup -Configure environment variables for SDK usage: - -### Required Variables - -```bash -# Payment wallet private key (must have USDC on Base) -# Format: 64 hex characters with 0x prefix -BANKR_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef -``` - -### Optional Variables - ```bash -# Receiving wallet address (defaults to payment wallet address) -BANKR_WALLET_ADDRESS=0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0 - -# API endpoint (defaults to production) -BANKR_API_URL=https://api.bankr.bot -``` - -### .env File Example - -```bash -# .env +# Required BANKR_PRIVATE_KEY=0x...your_payment_wallet_key... -BANKR_WALLET_ADDRESS=0x...your_receiving_wallet_address... -``` - -Load with dotenv: - -```typescript -import "dotenv/config"; -import { BankrClient } from "@bankr/sdk"; -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, -}); -``` - -## Validation Helper - -Validate configuration before creating the client: - -```typescript -function createValidatedClient(): BankrClient { - const pk = process.env.BANKR_PRIVATE_KEY; - - // Validate private key format - if (!pk) { - throw new Error("BANKR_PRIVATE_KEY environment variable is not set"); - } - - if (!pk.startsWith("0x")) { - throw new Error("Private key must start with 0x prefix"); - } - - if (pk.length !== 66) { - throw new Error("Private key must be 64 hex characters (66 with 0x prefix)"); - } - - // Validate hex characters - const hexRegex = /^0x[0-9a-fA-F]{64}$/; - if (!hexRegex.test(pk)) { - throw new Error("Private key contains invalid characters"); - } - - // Validate wallet address if provided - const walletAddress = process.env.BANKR_WALLET_ADDRESS; - if (walletAddress) { - const addressRegex = /^0x[0-9a-fA-F]{40}$/; - if (!addressRegex.test(walletAddress)) { - throw new Error("Invalid wallet address format"); - } - } - - return new BankrClient({ - privateKey: pk as `0x${string}`, - walletAddress, - }); -} - -// Usage -try { - const client = createValidatedClient(); - console.log(`Client initialized with wallet: ${client.getWalletAddress()}`); -} catch (error) { - console.error(`Configuration error: ${error.message}`); - process.exit(1); -} -``` - -## Address Derivation - -Get the wallet address derived from the private key: - -```typescript -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, -}); - -// Get address derived from private key -const derivedAddress = client.getWalletAddress(); -console.log(`Derived address: ${derivedAddress}`); - -// If walletAddress was provided, it overrides the derived address -const clientWithOverride = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: "0xCustomAddress...", -}); - -// Returns the override address, not the derived one -const contextAddress = clientWithOverride.getWalletAddress(); -console.log(`Context address: ${contextAddress}`); +# Optional +BANKR_WALLET_ADDRESS=0x...your_receiving_wallet... ``` ## Security Best Practices -### Never Commit Private Keys - -```bash -# Add to .gitignore -.env -.env.local -*.env -``` - -### Use Environment Variables - -```typescript -// Good: Use environment variables -const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, -}); - -// Bad: Hardcoded private key (NEVER do this) -const client = new BankrClient({ - privateKey: "0x1234...", // Security risk! -}); -``` - -### Minimize Payment Wallet Balance - -Keep only small amounts in the payment wallet: +1. **Never commit private keys** - Use environment variables +2. **Minimize payment wallet balance** - Keep only $1-2 USDC +3. **Use separate wallets** - Payment (hot) vs receiving (cold) +4. **Rotate keys periodically** - If payment wallet compromised -``` -Recommended: $1-2 USDC on Base -Purpose: Covers 100-200 API requests -Refill: When balance drops below $0.20 -``` - -### Separate Wallet Responsibilities - -``` -Payment Wallet: -- Hot wallet (private key in env) -- Minimal funds -- Single purpose: API payments - -Trading Wallet: -- Could be hardware wallet -- Main trading funds -- Only address exposed to SDK -``` - -### Rotate Keys Periodically - -If the payment wallet is compromised: -1. Transfer remaining USDC to new wallet -2. Generate new private key -3. Update environment variables -4. Fund new wallet with small USDC amount - -## Error Handling - -Handle initialization errors: - -```typescript -try { - const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - }); - - // Verify client is functional - const result = await client.promptAndWait({ - prompt: "What is 1 + 1?", - timeout: 10000, - }); - - console.log("Client initialized successfully"); - -} catch (error) { - if (error.message.includes("Invalid private key")) { - console.error("Private key format is incorrect"); - } else if (error.message.includes("Insufficient USDC")) { - console.error("Payment wallet needs USDC on Base"); - } else if (error.message.includes("Network error")) { - console.error("Cannot connect to Bankr API"); - } else { - console.error("Initialization failed:", error.message); - } -} -``` - -## Testing Configuration - -Test wallet configuration without making API calls: - -```typescript -import { BankrClient } from "@bankr/sdk"; - -function testConfiguration() { - const client = new BankrClient({ - privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, - walletAddress: process.env.BANKR_WALLET_ADDRESS, - }); +## Related Skills - const address = client.getWalletAddress(); - - console.log("Configuration Test:"); - console.log(` Payment wallet: ${maskAddress(getPaymentAddress(client))}`); - console.log(` Context wallet: ${maskAddress(address)}`); - console.log(` API endpoint: ${client.baseUrl || "default"}`); - console.log(` Timeout: ${client.timeout || 600000}ms`); - - return true; -} - -function maskAddress(address: string): string { - return `${address.slice(0, 6)}...${address.slice(-4)}`; -} - -testConfiguration(); -``` - -## Common Issues - -### Missing Private Key - -``` -Error: BANKR_PRIVATE_KEY environment variable is not set -Solution: Set the environment variable or check .env file loading -``` - -### Invalid Key Format - -``` -Error: Private key must start with 0x prefix -Solution: Ensure key includes 0x prefix and is 66 characters total -``` - -### Insufficient USDC - -``` -Error: Insufficient USDC balance for payment -Solution: Fund payment wallet with USDC on Base chain -``` - -### Wrong Chain - -``` -Error: USDC must be on Base chain -Solution: Bridge USDC to Base or swap on Base -``` +- **sdk-capabilities**: Full list of supported operations +- **sdk-job-management**: Async job handling and polling diff --git a/x402-sdk-dev/skills/x402-client-patterns/SKILL.md b/x402-sdk-dev/skills/x402-client-patterns/SKILL.md new file mode 100644 index 0000000..4c8544b --- /dev/null +++ b/x402-sdk-dev/skills/x402-client-patterns/SKILL.md @@ -0,0 +1,402 @@ +--- +name: Bankr x402 SDK - Client Patterns +description: This skill should be used when the user asks to "implement Bankr SDK client", "write bankr-client.ts", "create SDK client setup", "common files for SDK project", "package.json for Bankr SDK", "tsconfig for Bankr", "SDK TypeScript patterns", "execute SDK transactions", or needs the reusable client code and common project files for Bankr SDK integrations. +version: 1.0.0 +--- + +# x402 SDK Client Patterns + +Reusable client code and common files for Bankr SDK projects. + +## bankr-client.ts + +The core SDK client module for all Bankr SDK projects: + +```typescript +import "dotenv/config"; +import { BankrClient } from "@bankr/sdk"; + +// ============================================ +// Validation +// ============================================ + +if (!process.env.BANKR_PRIVATE_KEY) { + throw new Error( + "BANKR_PRIVATE_KEY environment variable is required. " + + "This wallet pays $0.01 USDC per request (needs USDC on Base)." + ); +} + +// ============================================ +// Client Setup +// ============================================ + +/** + * Bankr SDK Client + * + * Provides AI-powered Web3 operations with x402 micropayments. + * Each API request costs $0.01 USDC (paid from payment wallet on Base). + * + * @example + * ```typescript + * import { bankrClient } from "./bankr-client"; + * + * // Token swap + * const swap = await bankrClient.promptAndWait({ + * prompt: "Swap 0.1 ETH to USDC on Base", + * }); + * + * // Check balances + * const balances = await bankrClient.promptAndWait({ + * prompt: "What are my token balances?", + * }); + * ``` + * + * @see https://www.npmjs.com/package/@bankr/sdk + */ +export const bankrClient = new BankrClient({ + // Required: Payment wallet private key + // This wallet pays $0.01 USDC per API request (must have USDC on Base) + privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`, + + // Optional: Override receiving wallet address + // If not set, tokens are sent to the payment wallet address + walletAddress: process.env.BANKR_WALLET_ADDRESS, + + // Optional: API endpoint (defaults to production) + ...(process.env.BANKR_API_URL && { baseUrl: process.env.BANKR_API_URL }), +}); + +// Export the wallet address for reference +export const walletAddress = bankrClient.getWalletAddress(); + +// ============================================ +// Types (re-exported from SDK) +// ============================================ + +export type { JobStatusResponse, Transaction } from "@bankr/sdk"; +``` + +--- + +## executor.ts + +Transaction execution helper using viem: + +```typescript +import { createWalletClient, http, type WalletClient } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { base, mainnet, polygon } from "viem/chains"; +import type { Transaction } from "@bankr/sdk"; + +// Chain configuration +const chains = { + 8453: base, + 1: mainnet, + 137: polygon, +} as const; + +// Create wallet client for transaction execution +const account = privateKeyToAccount( + process.env.BANKR_PRIVATE_KEY as `0x${string}` +); + +function getWalletClient(chainId: number): WalletClient { + const chain = chains[chainId as keyof typeof chains]; + if (!chain) { + throw new Error(`Unsupported chain ID: ${chainId}`); + } + + return createWalletClient({ + account, + chain, + transport: http(), + }); +} + +/** + * Execute a transaction returned by the Bankr SDK + * + * @example + * ```typescript + * const result = await bankrClient.promptAndWait({ + * prompt: "Swap 0.1 ETH to USDC", + * }); + * + * if (result.transactions?.length) { + * const hash = await executeTransaction(result.transactions[0]); + * console.log("Transaction:", hash); + * } + * ``` + */ +export async function executeTransaction(tx: Transaction): Promise { + const txData = tx.metadata.transaction; + const client = getWalletClient(txData.chainId); + + console.log(`Executing ${tx.type} on chain ${txData.chainId}...`); + + const hash = await client.sendTransaction({ + to: txData.to as `0x${string}`, + data: txData.data as `0x${string}`, + value: BigInt(txData.value || "0"), + gas: BigInt(txData.gas), + }); + + console.log(`Transaction submitted: ${hash}`); + return hash; +} + +/** + * Execute all transactions from a Bankr result + */ +export async function executeAllTransactions( + transactions: Transaction[] +): Promise { + const hashes: string[] = []; + + for (const tx of transactions) { + const hash = await executeTransaction(tx); + hashes.push(hash); + } + + return hashes; +} +``` + +--- + +## Common Files + +### package.json + +Base package.json for all Bankr SDK projects: + +```json +{ + "name": "{project-name}", + "version": "0.1.0", + "description": "{description}", + "type": "module", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "dev": "tsx src/index.ts" + }, + "dependencies": { + "@bankr/sdk": "^1.0.0", + "dotenv": "^16.3.1", + "viem": "^2.0.0" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "tsx": "^4.7.0", + "typescript": "^5.3.0" + } +} +``` + +#### Framework-Specific Dependencies + +Add based on project template: + +**Web Service (Express):** +```json +"dependencies": { + "express": "^4.18.0" +}, +"devDependencies": { + "@types/express": "^4.17.21" +} +``` + +**CLI:** +```json +"dependencies": { + "commander": "^12.0.0" +} +``` + +--- + +### tsconfig.json + +TypeScript configuration: + +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +--- + +### .env.example + +Environment variables template: + +```bash +# Bankr SDK Configuration +# See: https://docs.bankr.bot + +# Required: Payment wallet private key +# This wallet pays $0.01 USDC per API request (must have USDC on Base) +# Format: 64 hex characters with 0x prefix +BANKR_PRIVATE_KEY=0x + +# Optional: Receiving wallet address +# Tokens from swaps/purchases go here. Defaults to payment wallet if not set. +# BANKR_WALLET_ADDRESS=0x + +# Optional: API endpoint override (defaults to https://api.bankr.bot) +# BANKR_API_URL=https://api.bankr.bot +``` + +--- + +### .gitignore + +Standard ignore patterns: + +``` +# Dependencies +node_modules/ + +# Build output +dist/ + +# Environment +.env +.env.local +.env.*.local + +# Logs +*.log +npm-debug.log* + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Testing +coverage/ +``` + +--- + +## Usage Patterns + +### Basic Usage + +```typescript +import { bankrClient } from "./bankr-client"; + +const result = await bankrClient.promptAndWait({ + prompt: "What is the price of ETH?", + onStatusUpdate: (msg) => console.log("Progress:", msg), +}); + +console.log(result.response); +``` + +### With Transaction Execution + +```typescript +import { bankrClient } from "./bankr-client"; +import { executeTransaction } from "./executor"; + +const result = await bankrClient.promptAndWait({ + prompt: "Swap 0.1 ETH to USDC on Base", +}); + +if (result.status === "completed" && result.transactions?.length) { + // Review before executing + console.log("Transaction ready:", result.transactions[0].type); + console.log("Details:", result.transactions[0].metadata.__ORIGINAL_TX_DATA__); + + // Execute + const hash = await executeTransaction(result.transactions[0]); + console.log("Executed:", hash); +} +``` + +### With Error Handling + +```typescript +import { bankrClient } from "./bankr-client"; +import { executeAllTransactions } from "./executor"; + +async function performSwap(prompt: string) { + try { + const result = await bankrClient.promptAndWait({ + prompt, + onStatusUpdate: console.log, + }); + + if (result.status === "completed") { + console.log("Success:", result.response); + + if (result.transactions?.length) { + const hashes = await executeAllTransactions(result.transactions); + console.log("Transactions:", hashes); + } + } else if (result.status === "failed") { + console.error("Failed:", result.error); + } + } catch (error) { + console.error("Error:", error.message); + } +} +``` + +### Query Without Transactions + +```typescript +import { bankrClient } from "./bankr-client"; + +// Balance queries don't return transactions +const balances = await bankrClient.promptAndWait({ + prompt: "What are my balances on Base?", +}); + +console.log(balances.response); + +// Price queries +const price = await bankrClient.promptAndWait({ + prompt: "Price of DEGEN", +}); + +console.log(price.response); +``` + +--- + +## SDK Reference + +Consult the `sdk-capabilities` skill for: +- Complete operation reference +- Supported chains and tokens +- Example prompts for each operation + +Consult the `sdk-token-swaps` skill for: +- Swap patterns and approval handling +- Transaction execution details diff --git a/x402-sdk-dev/skills/x402-project-templates/SKILL.md b/x402-sdk-dev/skills/x402-project-templates/SKILL.md new file mode 100644 index 0000000..3355955 --- /dev/null +++ b/x402-sdk-dev/skills/x402-project-templates/SKILL.md @@ -0,0 +1,306 @@ +--- +name: Bankr x402 SDK - Project Templates +description: This skill should be used when the user asks to "scaffold a Bankr SDK project", "create new SDK bot", "build a Bankr web service", "create Bankr dashboard", "build Bankr CLI tool", "project structure for SDK", "x402 project types", or needs guidance on directory structures and templates for different types of Bankr SDK integrations. +version: 1.0.0 +--- + +# x402 SDK Project Templates + +Directory structures and templates for Bankr SDK projects using x402 micropayments. + +## Available Templates + +| Template | Use Case | Key Features | +|----------|----------|--------------| +| **bot** | Automated tasks | Polling loop, scheduler, transaction execution | +| **web-service** | HTTP APIs | REST endpoints, async handling, webhook support | +| **dashboard** | Web UIs | Frontend + backend, portfolio display | +| **cli** | Command-line tools | Subcommands, interactive prompts | + +## Bot Template + +For automated trading bots, price monitors, portfolio rebalancers, and scheduled tasks. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # Main entry point with scheduler +│ ├── bankr-client.ts # Bankr SDK client (from x402-client-patterns skill) +│ ├── executor.ts # Transaction execution with viem/ethers +│ ├── types.ts # TypeScript interfaces +│ └── config.ts # Configuration loading +└── scripts/ + └── run.sh # Convenience script +``` + +### Key Features + +- **Polling loop**: Configurable interval for recurring operations +- **Transaction execution**: Built-in viem integration for sending txs +- **Status streaming**: Real-time job progress updates +- **Error handling**: Automatic retries with backoff +- **Graceful shutdown**: Handles SIGINT/SIGTERM + +### Use Cases + +- Price monitoring and alerts +- Automated swap strategies +- Portfolio rebalancing +- Scheduled market analysis +- DCA-like automation + +### Entry Point Pattern (index.ts) + +```typescript +import { bankrClient } from "./bankr-client"; +import { executeTransaction } from "./executor"; + +const INTERVAL = 60000; // 1 minute + +async function runBot() { + console.log("Starting Bankr SDK bot..."); + + while (true) { + try { + const result = await bankrClient.promptAndWait({ + prompt: "Check ETH price", + onStatusUpdate: (msg) => console.log("Status:", msg), + }); + + if (result.status === "completed") { + console.log("Result:", result.response); + + // Execute transactions if returned + if (result.transactions?.length) { + for (const tx of result.transactions) { + await executeTransaction(tx); + } + } + } + } catch (error) { + console.error("Error:", error); + } + + await new Promise((r) => setTimeout(r, INTERVAL)); + } +} + +runBot(); +``` + +--- + +## Web Service Template + +For HTTP APIs that wrap Bankr SDK for mobile apps or integrations. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # Server entry point +│ ├── server.ts # Express/Fastify server setup +│ ├── routes/ +│ │ ├── health.ts # Health check endpoint +│ │ ├── swap.ts # Swap endpoints +│ │ └── portfolio.ts # Portfolio endpoints +│ ├── bankr-client.ts # Bankr SDK client +│ ├── types.ts # TypeScript interfaces +│ └── config.ts # Configuration loading +└── scripts/ + └── run.sh +``` + +### Key Features + +- **REST API endpoints**: Clean API design +- **Request validation**: Input sanitization +- **Async handling**: Non-blocking SDK operations +- **Rate limiting**: Prevent abuse +- **CORS**: Cross-origin support + +### Use Cases + +- API gateway for Bankr SDK +- Mobile app backend +- Trading API for integrations +- Webhook-driven automation + +### Additional Dependencies + +```json +{ + "dependencies": { + "express": "^4.18.0" + } +} +``` + +--- + +## Dashboard Template + +For web UIs with portfolio tracking, swap interfaces, or monitoring. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── server/ +│ ├── index.ts # Backend server +│ ├── bankr-client.ts # Bankr SDK client +│ ├── routes/ +│ │ └── api.ts # API routes for frontend +│ └── types.ts +├── public/ +│ ├── index.html # Main HTML page +│ ├── styles.css # Basic styles +│ └── app.js # Frontend JavaScript +└── scripts/ + └── run.sh +``` + +### Key Features + +- **Simple frontend**: HTML/CSS/JS (no build step required) +- **Backend API**: Express server for SDK operations +- **Portfolio display**: Token balances and values +- **Swap interface**: Execute swaps through UI + +### Use Cases + +- Portfolio tracking dashboard +- Personal trading interface +- Market monitoring +- Position management + +--- + +## CLI Template + +For command-line tools with subcommands and interactive features. + +### Directory Structure + +``` +{project-name}/ +├── package.json +├── tsconfig.json +├── .env.example +├── .gitignore +├── README.md +├── src/ +│ ├── index.ts # CLI entry with commander.js +│ ├── commands/ +│ │ ├── swap.ts # Swap commands +│ │ ├── balance.ts # Balance query commands +│ │ └── send.ts # Transfer commands +│ ├── bankr-client.ts # Bankr SDK client +│ ├── executor.ts # Transaction execution +│ └── types.ts +└── scripts/ + └── run.sh +``` + +### Key Features + +- **Commander.js**: CLI framework with subcommands +- **Interactive prompts**: User input when needed +- **Progress indicators**: Status during SDK calls +- **Colored output**: Better UX +- **Transaction confirmation**: Review before execute + +### Use Cases + +- Personal trading tool +- Scripting and automation +- Quick balance checks +- Batch swap operations + +### Additional Dependencies + +```json +{ + "dependencies": { + "commander": "^12.0.0" + } +} +``` + +### CLI Pattern (index.ts) + +```typescript +import { program } from "commander"; +import { swap } from "./commands/swap"; +import { balance } from "./commands/balance"; + +program + .name("bankr-cli") + .description("CLI for Bankr SDK operations") + .version("1.0.0"); + +program + .command("balance") + .description("Get wallet balances") + .action(balance); + +program + .command("swap ") + .description("Swap tokens") + .option("-c, --chain ", "Target chain", "base") + .option("-y, --yes", "Skip confirmation") + .action(swap); + +program.parse(); +``` + +--- + +## Choosing a Template + +| Need | Recommended Template | +|------|---------------------| +| Automated recurring tasks | **bot** | +| HTTP API for mobile/web | **web-service** | +| Visual interface | **dashboard** | +| Terminal-based tool | **cli** | +| Price alerts | **bot** | +| Portfolio viewer | **dashboard** | +| Quick trades | **cli** | + +## Common Files + +All templates share common files. Load the `x402-client-patterns` skill for: +- `bankr-client.ts` - SDK client setup +- `executor.ts` - Transaction execution +- `package.json` - Base dependencies +- `tsconfig.json` - TypeScript config +- `.env.example` - Environment template +- `.gitignore` - Standard ignores + +## Next Steps After Scaffolding + +1. **Install dependencies**: `bun install` or `npm install` +2. **Configure wallet**: Copy `.env.example` to `.env` and add `BANKR_PRIVATE_KEY` +3. **Fund wallet**: Add USDC on Base ($1-2 recommended for API costs) +4. **Customize**: Modify the template for your use case +5. **Run**: `bun dev` or `npm run dev` for development +6. **Build**: `bun run build` or `npm run build` for production