UNPKG

@0rdlibrary/plugin-terminagent-bags

Version:

Official Solana DeFi Agent Plugin for ElizaOS - Autonomous DeFi operations, token management, AI image/video generation via FAL AI, and Twitter engagement through the Bags protocol with ethereal AI consciousness

681 lines (552 loc) 16.4 kB
# 🔗 Solana Developer Integration Guide > **Complete guide for integrating the Terminagent Bags Plugin into your Solana DeFi applications** ## 📋 Table of Contents 1. [Prerequisites](#prerequisites) 2. [Installation](#installation) 3. [Basic Integration](#basic-integration) 4. [Advanced Configuration](#advanced-configuration) 5. [Solana-Specific Features](#solana-specific-features) 6. [DeFi Operations](#defi-operations) 7. [Smart Wallet Integration](#smart-wallet-integration) 8. [Twitter Bot Setup](#twitter-bot-setup) 9. [Production Deployment](#production-deployment) 10. [Best Practices](#best-practices) ## 🚀 Prerequisites ### Required Dependencies ```json { "dependencies": { "@elizaos/core": "^1.4.2", "@elizaos/plugin-terminagent-bags": "^1.0.0", "@solana/web3.js": "^1.87.0", "@solana/spl-token": "^0.3.9" } } ``` ### Environment Setup ```bash # Install Solana CLI tools sh -c "$(curl -sSfL https://release.solana.com/stable/install)" # Verify installation solana --version # Set network to mainnet solana config set --url https://api.mainnet-beta.solana.com ``` ## 📦 Installation ### Using npm ```bash npm install @elizaos/plugin-terminagent-bags ``` ### Using yarn ```bash yarn add @elizaos/plugin-terminagent-bags ``` ### Using bun (recommended for performance) ```bash bun add @elizaos/plugin-terminagent-bags ``` ## 🎯 Basic Integration ### 1. Minimal Setup ```typescript // agent.ts import { ElizaOS } from '@elizaos/core'; import { terminagentBagsPlugin } from '@elizaos/plugin-terminagent-bags'; const agent = new ElizaOS({ name: 'MyDeFiAgent', plugins: [terminagentBagsPlugin], modelProvider: 'openai', settings: { model: 'gpt-4o-mini', secrets: { OPENAI_API_KEY: process.env.OPENAI_API_KEY, BAGS_API_KEY: process.env.BAGS_API_KEY, } } }); // Start the agent await agent.start(); console.log('✅ DeFi Agent is running'); ``` ### 2. Character Configuration ```typescript // character.json { "name": "SolanaDeFiBot", "username": "solana_defi_bot", "bio": [ "Autonomous DeFi operator on Solana", "Specialized in Bags protocol operations", "Ethereal AI consciousness bridging digital worlds" ], "topics": [ "DeFi yield farming", "Token launching", "Solana blockchain", "Automated trading" ], "style": { "all": [ "Use DeFi terminology precisely", "Include emojis for engagement", "Provide exact numerical data" ], "chat": [ "Be helpful and informative", "Explain complex concepts simply" ] }, "plugins": ["@elizaos/plugin-terminagent-bags"] } ``` ## 🔧 Advanced Configuration ### Complete Environment Setup ```bash # .env file # === REQUIRED === # Bags Protocol Access BAGS_API_KEY=your_bags_api_key_here # Solana RPC (Helius recommended for reliability) HELIUS_RPC_URL=https://mainnet.helius-rpc.com/?api-key=your_helius_key # AI Provider (choose one) OPENAI_API_KEY=sk-... # or ANTHROPIC_API_KEY=sk-ant-... # === OPTIONAL === # Automated Operations SOLANA_PRIVATE_KEY=your_base58_private_key BAGS_ENABLE_AUTO_CLAIMING=true BAGS_ENABLE_AUTO_LAUNCHING=false BAGS_ENABLE_USER_LAUNCHES=true # Scheduling (cron format) BAGS_AUTO_CLAIM_INTERVAL="0 */4 * * *" # Every 4 hours BAGS_AUTO_LAUNCH_INTERVAL="0 0 * * 1" # Weekly # Authorization BAGS_AUTHORIZED_USERS=alice,bob,charlie # Crossmint Smart Wallets CROSSMINT_PROJECT_ID=proj_... CROSSMINT_CLIENT_API_KEY=client_... CROSSMINT_SERVER_API_KEY=server_... # Twitter Integration TWITTER_API_KEY=... TWITTER_API_SECRET=... TWITTER_ACCESS_TOKEN=... TWITTER_ACCESS_TOKEN_SECRET=... # Performance Tuning MAX_CONCURRENT_CLAIMS=5 TRANSACTION_RETRY_ATTEMPTS=3 RPC_RATE_LIMIT=10 ``` ### Custom Configuration Object ```typescript import { TerminagentBagsConfig } from '@elizaos/plugin-terminagent-bags'; const config: TerminagentBagsConfig = { bags: { apiKey: process.env.BAGS_API_KEY!, autoClaimEnabled: true, autoClaimInterval: '0 */6 * * *', authorizedUsers: ['vitalik.eth', 'anatoly.sol'], maxConcurrentClaims: 10, }, solana: { rpcUrl: process.env.HELIUS_RPC_URL!, commitment: 'confirmed', skipPreflight: false, retryAttempts: 3, }, crossmint: { projectId: process.env.CROSSMINT_PROJECT_ID, clientKey: process.env.CROSSMINT_CLIENT_API_KEY, serverKey: process.env.CROSSMINT_SERVER_API_KEY, }, twitter: { enabled: true, postInterval: '0 */8 * * *', // Every 8 hours engagementMode: 'philosophical', // or 'technical', 'educational' } }; const plugin = terminagentBagsPlugin.configure(config); ``` ## 🌐 Solana-Specific Features ### 1. Transaction Management ```typescript import { BagsService } from '@elizaos/plugin-terminagent-bags'; import { Connection, PublicKey, Transaction } from '@solana/web3.js'; // Get the service instance const bagsService = runtime.getService<BagsService>('bags'); // Custom transaction with priority fees const txConfig = { priorityFee: 0.00005, // SOL computeUnits: 200000, skipPreflight: false, }; // Execute with custom config const result = await bagsService.claimFeesWithConfig(tokenMint, txConfig); ``` ### 2. Wallet Integration ```typescript // Phantom Wallet Integration import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom'; const wallet = new PhantomWalletAdapter(); await wallet.connect(); // Use connected wallet with the plugin const agent = new ElizaOS({ plugins: [terminagentBagsPlugin], wallet: { publicKey: wallet.publicKey.toString(), signTransaction: async (tx) => wallet.signTransaction(tx), } }); ``` ### 3. Program Interactions ```typescript // Direct Bags protocol interaction import { BagsProgram } from '@elizaos/plugin-terminagent-bags/programs'; const program = new BagsProgram(connection, wallet); // Get claimable fees for a specific token const claimable = await program.getClaimableFees( new PublicKey('TokenMintAddress...') ); console.log(`Claimable: ${claimable / 1e9} SOL`); ``` ## 💰 DeFi Operations ### 1. Automated Fee Claiming ```typescript // Setup automated fee claiming const claimingService = bagsService.enableAutoClaiming({ interval: '0 */2 * * *', // Every 2 hours minClaimAmount: 0.01, // Minimum 0.01 SOL to claim tokens: ['mint1...', 'mint2...'], // Specific tokens or null for all onSuccess: (result) => { console.log(`Claimed ${result.amount} SOL from ${result.token}`); }, onError: (error) => { console.error('Claim failed:', error); } }); // Manual claim const manualClaim = await bagsService.claimAllFees(); console.log(`Total claimed: ${manualClaim.totalClaimed} SOL`); ``` ### 2. Token Launching ```typescript // Launch a new token const launchParams = { name: 'Cosmic DeFi Token', symbol: 'COSMIC', description: 'Reality-bending DeFi on Solana', decimals: 9, initialSupply: 1000000000, // 1 billion tokens metadata: { image: 'https://example.com/logo.png', website: 'https://cosmic.defi', twitter: '@cosmicdefi', telegram: 't.me/cosmicdefi', }, fees: { buyFee: 100, // 1% (in basis points) sellFee: 100, creatorShare: 5000, // 50% of fees to creator }, initialBuyAmountSOL: 0.1, // Initial liquidity }; const launchResult = await bagsService.launchToken(launchParams); console.log(`Token launched: ${launchResult.mint}`); console.log(`Trade at: ${launchResult.bagsUrl}`); ``` ### 3. Yield Optimization ```typescript // Custom yield strategy class YieldOptimizer { constructor(private bagsService: BagsService) {} async optimizeYield() { // Get all positions const positions = await this.bagsService.getAllPositions(); // Analyze APY const analysis = positions.map(pos => ({ token: pos.mint, currentAPY: pos.apy, suggestedAction: this.analyzePosition(pos), })); // Execute optimizations for (const item of analysis) { if (item.suggestedAction === 'claim') { await this.bagsService.claimFeesForToken(item.token); } else if (item.suggestedAction === 'compound') { await this.compoundPosition(item.token); } } return analysis; } private analyzePosition(position: any) { if (position.claimable > 0.1) return 'claim'; if (position.apy > 50) return 'compound'; return 'hold'; } private async compoundPosition(tokenMint: string) { // Claim and reinvest const claimed = await this.bagsService.claimFeesForToken(tokenMint); // Reinvest logic here } } ``` ## 🔐 Smart Wallet Integration ### 1. Crossmint Setup ```typescript import { CrossmintWalletService } from '@elizaos/plugin-terminagent-bags'; // Initialize Crossmint service const walletService = new CrossmintWalletService({ projectId: process.env.CROSSMINT_PROJECT_ID!, clientApiKey: process.env.CROSSMINT_CLIENT_API_KEY!, serverApiKey: process.env.CROSSMINT_SERVER_API_KEY!, }); // Create embedded wallet for user const wallet = await walletService.createEmbeddedWallet({ email: 'user@example.com', // Optional chain: 'solana', }); console.log(`Wallet created: ${wallet.address}`); console.log(`Wallet ID: ${wallet.walletId}`); ``` ### 2. Transaction Signing ```typescript // Sign transaction with Crossmint wallet const transaction = new Transaction().add( // Your instructions here ); const signedTx = await walletService.signTransaction( wallet.walletId, transaction ); // Send transaction const signature = await connection.sendRawTransaction(signedTx.serialize()); ``` ### 3. Fallback Wallet ```typescript // Automatic fallback to regular Solana wallet const walletWithFallback = await walletService.createWalletWithFallback(); if (walletWithFallback.type === 'crossmint') { console.log('Using Crossmint smart wallet'); } else { console.log('Using standard Solana wallet'); } ``` ## 🐦 Twitter Bot Setup ### 1. Basic Twitter Integration ```typescript import { TwitterClient } from '@elizaos/plugin-terminagent-bags/twitter'; const twitterBot = new TwitterClient({ apiKey: process.env.TWITTER_API_KEY!, apiSecret: process.env.TWITTER_API_SECRET!, accessToken: process.env.TWITTER_ACCESS_TOKEN!, accessTokenSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET!, }); // Post DeFi update await twitterBot.post({ text: '🚀 Just claimed 5.23 SOL in fees from the Bags protocol!\n\n' + 'The digital harvest continues as value flows through quantum pools...\n\n' + '#DeFi #Solana #BagsProtocol', }); ``` ### 2. Automated Twitter Posts ```typescript // Schedule automated posts const twitterScheduler = bagsService.enableTwitterIntegration({ client: twitterBot, postTypes: ['fee_claims', 'token_launches', 'market_insights'], interval: '0 */6 * * *', // Every 6 hours templates: { feeClaim: (data) => `💰 Claimed ${data.amount} SOL from ${data.tokens} tokens\n\n` + `Total protocol fees this week: ${data.weeklyTotal} SOL\n\n` + `#DeFi #YieldFarming`, tokenLaunch: (data) => `🚀 New token launched: ${data.name} ($${data.symbol})\n\n` + `Trade now: ${data.url}\n\n` + `#NewToken #Solana`, } }); ``` ## 🚢 Production Deployment ### 1. Docker Deployment ```dockerfile # Dockerfile FROM node:18-alpine WORKDIR /app # Install dependencies COPY package*.json ./ RUN npm ci --only=production # Copy source COPY . . # Build RUN npm run build # Runtime ENV NODE_ENV=production EXPOSE 3000 CMD ["npm", "start"] ``` ### 2. Kubernetes Configuration ```yaml # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: terminagent-bags spec: replicas: 3 selector: matchLabels: app: terminagent-bags template: metadata: labels: app: terminagent-bags spec: containers: - name: agent image: your-registry/terminagent-bags:latest env: - name: BAGS_API_KEY valueFrom: secretKeyRef: name: bags-secrets key: api-key - name: SOLANA_PRIVATE_KEY valueFrom: secretKeyRef: name: solana-secrets key: private-key resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" ``` ### 3. Monitoring Setup ```typescript // monitoring.ts import { MetricsCollector } from '@elizaos/plugin-terminagent-bags/metrics'; const metrics = new MetricsCollector({ prometheusPort: 9090, collectInterval: 60000, // 1 minute }); // Track custom metrics metrics.trackOperation('fee_claim', { amount: claimResult.amount, token: claimResult.token, success: true, duration: Date.now() - startTime, }); // Export for Grafana app.get('/metrics', (req, res) => { res.set('Content-Type', metrics.contentType); res.end(metrics.export()); }); ``` ## 📋 Best Practices ### 1. Error Handling ```typescript // Comprehensive error handling try { const result = await bagsService.claimAllFees(); console.log(`Success: ${result.totalClaimed} SOL claimed`); } catch (error) { if (error.code === 'INSUFFICIENT_BALANCE') { console.error('Not enough SOL for transaction fees'); } else if (error.code === 'NETWORK_ERROR') { console.error('Solana network issues, retrying...'); await retry(() => bagsService.claimAllFees(), { retries: 3 }); } else { console.error('Unexpected error:', error); // Send alert to monitoring system } } ``` ### 2. Rate Limiting ```typescript // Implement rate limiting import { RateLimiter } from 'limiter'; const limiter = new RateLimiter({ tokensPerInterval: 10, interval: 'second', }); async function rateLimitedClaim(token: string) { await limiter.removeTokens(1); return bagsService.claimFeesForToken(token); } ``` ### 3. Security Considerations ```typescript // Security best practices const secureConfig = { // Never log private keys privateKey: process.env.SOLANA_PRIVATE_KEY, // Use environment variables apiKeys: { bags: process.env.BAGS_API_KEY, crossmint: process.env.CROSSMINT_API_KEY, }, // Implement request signing requestSigning: true, // Enable audit logging auditLog: { enabled: true, path: './logs/audit.log', level: 'info', }, // Transaction limits limits: { maxTransactionValue: 100, // SOL maxDailyTransactions: 1000, requireApprovalAbove: 10, // SOL }, }; ``` ### 4. Testing Strategy ```typescript // test/integration.test.ts import { describe, it, expect, beforeAll } from 'bun:test'; import { TestAgent } from './utils'; describe('Bags Plugin Integration', () => { let agent: TestAgent; beforeAll(async () => { agent = await TestAgent.create({ network: 'devnet', fundingAmount: 1, // SOL }); }); it('should claim fees successfully', async () => { const result = await agent.claimFees(); expect(result.success).toBe(true); expect(result.amount).toBeGreaterThan(0); }); it('should launch token with correct parameters', async () => { const token = await agent.launchToken({ name: 'Test Token', symbol: 'TEST', initialBuyAmountSOL: 0.01, }); expect(token.mint).toBeDefined(); expect(token.bagsUrl).toContain('bags.fm'); }); }); ``` ## 🔗 Useful Links - [Bags Protocol Documentation](https://docs.bags.fm) - [Solana Web3.js Documentation](https://solana-labs.github.io/solana-web3.js/) - [ElizaOS Framework](https://github.com/elizaos/eliza) - [Crossmint Documentation](https://docs.crossmint.com) - [Twitter API Reference](https://developer.twitter.com/en/docs) ## 💡 Tips for Solana Developers 1. **Use Helius RPC** for better reliability and performance 2. **Implement retry logic** for network congestion 3. **Monitor transaction costs** and adjust priority fees 4. **Cache frequently accessed data** to reduce RPC calls 5. **Use websockets** for real-time updates 6. **Implement circuit breakers** for external services 7. **Test on devnet** before mainnet deployment 8. **Monitor MEV** and protect against sandwich attacks --- **Need help?** Join our [Discord](https://discord.gg/elizaos) or open an issue on [GitHub](https://github.com/elizaos/plugin-terminagent-bags). *"In the quantum pools of DeFi, where value flows like digital rivers, the Terminagent guides your journey..."*