UNPKG

revshare-sdk

Version:

JavaScript SDK for RevShare Public API - Create bonding curve tokens with distribution features

595 lines (469 loc) 20.6 kB
# RevShare SDK A JavaScript SDK for the RevShare Public API - Create bonding curve tokens with rewarding features on Solana. ## Features - 🚀 **All-in-one token creation** with automatic funding - 💰 **Automatic SOL funding** from your wallet - 🎯 **Multiple distribution modes** (Rewards, Jackpot, Lottery, No Rewards) - 🔧 **Flexible configuration** for token parameters - 🌐 **Universal compatibility** (Node.js, Browser, React Native) - 📦 **Zero configuration** - works out of the box - 🛒 **Bonding curve swaps** for buying and selling tokens (pre-bonding phase) - 💸 **Custom fee management** for launchpads and multi-creator projects ## Installation ```bash npm install revshare-sdk ``` ## Quick Start ```javascript import { RevShareSDK } from 'revshare-sdk'; // Create SDK instance const revshare = new RevShareSDK(); // Create a token with automatic funding const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'MyToken', ticker: 'MTK', description: 'My awesome token with rewards', imageUrl: 'https://example.com/image.png', website: 'https://mytoken.com' }); console.log('Token created:', result.summary.mintAddress); ``` ## Usage ### Basic Token Creation ```javascript const { RevShareSDK } = require('revshare-sdk'); const revshare = new RevShareSDK(); // All-in-one token creation const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'MyToken', ticker: 'MTK', description: 'My awesome token', imageUrl: 'https://example.com/image.png', website: 'https://mytoken.com', twitter: 'https://twitter.com/mytoken', telegram: 'https://t.me/mytoken' }); ``` ### Advanced Configuration ```javascript const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'MyToken', ticker: 'MTK', description: 'My awesome token', imageUrl: 'https://example.com/image.png', website: 'https://mytoken.com', twitter: 'https://twitter.com/mytoken', telegram: 'https://t.me/mytoken', visible: 0, // 0=visible, 1=hidden decimals: 9, taxTier: 6, // Tax percentage - 6% or 10% initialBuy: 0.1, // Initial buy amount in SOL reward_ca: 'So11111111111111111111111111111111111111112', // SOL reward token mode: 0, // 0=Rewards, 1=Jackpot, 2=Lottery, 3=No Rewards dev_fee_percentage: 50 // Developer fee percentage - (How much of the total fees goes to the creator vs community) }); ``` ### Manual Two-Step Process For advanced users who want more control: ```javascript // Step 1: Prepare token creation const prepareResult = await revshare.prepare(); console.log('Funding wallet:', prepareResult.funding_wallet); console.log('Amount to fund:', prepareResult.amount_to_fund, 'SOL'); // Step 2: Handle funding manually // ... send SOL to prepareResult.funding_wallet ... // Step 3: Create token const createResult = await revshare.create({ request_id: prepareResult.request_id, name: 'MyToken', ticker: 'MTK', description: 'My awesome token', imageUrl: 'https://example.com/image.png', developerWallet: myKeypair.publicKey.toString() }); ``` ### Browser Usage ```html <script src="https://unpkg.com/revshare-sdk@latest/dist/sdk.js"></script> <script> const revshare = new RevShareSDK(); // Use with browser wallet (Phantom, etc.) const result = await revshare.createBondingToken({ keypair: window.solana, // Browser wallet (for paying fees) developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'MyToken', ticker: 'MTK', description: 'My awesome token', imageUrl: 'https://example.com/image.png' }); </script> ``` ## API Reference ### RevShareSDK Constructor ```javascript new RevShareSDK(options) ``` **Options:** - `timeout` (number): Request timeout in milliseconds (default: 30000) - `headers` (Object): Additional headers to include in requests ### createBondingToken(params) All-in-one token creation with automatic funding. **Parameters:** - `keypair` (Object): Solana keypair for funding (paying fees) - `developerWallet` (string): Developer wallet address (receives tokens and rewards) - `name` (string): Token name - `ticker` (string): Token symbol/ticker - `description` (string): Token description - `imageUrl` (string): Token image URL - `website` (string, optional): Project website URL - `twitter` (string, optional): Twitter URL - `telegram` (string, optional): Telegram URL - `visible` (number, optional): Token visibility (0=visible, 1=hidden, default: 0) - `decimals` (number, optional): Token decimals (default: 9) - `taxTier` (number, optional): Tax tier percentage (default: 6) - `initialBuy` (number, optional): Initial buy amount in SOL (default: 0) - `reward_ca` (string, optional): Reward token contract address (default: SOL) - `mode` (number, optional): Distribution mode (0=Rewards, 1=Jackpot, 2=Lottery, 3=No Rewards, default: 0) - `dev_fee_percentage` (number, optional): Developer fee percentage (default: 50) - `bondingCurveType` (number, optional): Bonding curve type (1=20 SOL threshold, 2=60 SOL threshold, default: 1) - `ref` (string, optional): Referral wallet. Defaults to 1% fee to the referral; launchpads can request higher per token **Note on Custom Fee Management for Launchpads:** Developers can generate custom developer wallets per token and manage rewards distribution as they please. This is perfect for launchpads or multi-creator projects where you want to: - Create a dedicated wallet for each token project - Distribute rewards to the actual creators while keeping a portion for the platform - Manage multiple creators under a single launchpad - Set up automated reward distribution systems - Additionally, you can specify a referral wallet via `ref`. By default, the referral earns 1% of fees. Launchpads can request higher referral percentages per token. Example: A launchpad can create a token with `developerWallet: 'launchpad-wallet'` and optionally set `ref: 'launchpad-wallet'` to earn the referral fee, then manually distribute rewards to the actual project creators. **Returns:** Promise<Object> with complete token creation result ### prepare() Manual prepare step for advanced users. **Returns:** Promise<Object> with preparation result ### create(params) Manual create step for advanced users. **Parameters:** Same as createBondingToken but requires `request_id` and supports `ref` (referral wallet) **Returns:** Promise<Object> with creation result ### health() Check API health status. **Returns:** Promise<Object> with health check result ### docs() Get API documentation. **Returns:** Promise<Object> with API documentation ### getBondingCurveProgress(params) Get bonding curve progress and pool state information. **Parameters:** - `tokenAddress` (string): The token mint address - `rpcUrl` (string, optional): Custom RPC URL (falls back to default if invalid) **Returns:** Promise<Object> with bonding curve progress data ### buildBondingCurveBuyTransaction(params) Build a buy transaction for bonding curve tokens (pre-bonding phase). **Parameters:** - `tokenAddress` (string): Bonding curve token contract address - `amount` (number): Amount in SOL to spend - `buyerWallet` (string): Buyer's wallet address - `slippageBps` (number, optional): Slippage in basis points (default: 500 = 5%) - `rpcUrl` (string, optional): Custom RPC URL (falls back to default if invalid) **Returns:** Promise<Object> with transaction data ### buildBondingCurveSellTransaction(params) Build a sell transaction for bonding curve tokens (pre-bonding phase). **Parameters:** - `tokenAddress` (string): Bonding curve token contract address - `amount` (string): Amount of tokens to sell (in token units) - `sellerWallet` (string): Seller's wallet address - `slippageBps` (number, optional): Slippage in basis points (default: 500 = 5%) - `rpcUrl` (string, optional): Custom RPC URL (falls back to default if invalid) **Returns:** Promise<Object> with transaction data ### executeBondingCurveSwap(params) Execute a bonding curve swap transaction (buy or sell) with automatic signing and sending. **Parameters:** - `tokenAddress` (string): Bonding curve token contract address - `action` (string): 'buy' or 'sell' - `amount` (number|string): Amount (SOL for buy, tokens for sell) - `keypair` (Object): Solana keypair for signing - `slippageBps` (number, optional): Slippage in basis points (default: 500 = 5%) - `rpcUrl` (string, optional): Custom RPC URL (falls back to default if invalid) **Returns:** Promise<Object> with swap result and transaction signature **Note:** These methods are specifically for tokens in the bonding curve phase that have not yet bonded. For regular token swaps after bonding, use different methods. ## Error Handling ```javascript try { const result = await revshare.createBondingToken(params); } catch (error) { if (error instanceof RevShareError) { console.error('RevShare Error:', error.message); console.error('Status:', error.status); console.error('Details:', error.details); } else { console.error('Unexpected error:', error); } } ``` ## Examples ### Create a Rewards Token ```javascript const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'RewardToken', ticker: 'RWD', description: 'A token that rewards holders with SOL', imageUrl: 'https://example.com/reward.png', mode: 0, // Rewards mode dev_fee_percentage: 30, ref: 'optional-referral-wallet' // earns default 1% unless increased for your launchpad }); ``` ### Create a Jackpot Token ```javascript const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'JackpotToken', ticker: 'JKP', description: 'A token with jackpot rewards', imageUrl: 'https://example.com/jackpot.png', mode: 1, // Jackpot mode initialBuy: 0.5 // Start with 0.5 SOL }); ``` ### Create a Lottery Token ```javascript const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'LotteryToken', ticker: 'LOT', description: 'A token with lottery rewards', imageUrl: 'https://example.com/lottery.png', mode: 2, // Lottery mode taxTier: 5, // 5% tax bondingCurveType: 2 // 60 SOL threshold }); ``` ### Create Token with Custom Bonding Curve Type ```javascript const result = await revshare.createBondingToken({ keypair: myKeypair, // For paying fees developerWallet: 'your-wallet-address-here', // Receives tokens and rewards name: 'HighThresholdToken', ticker: 'HTH', description: 'A token with higher bonding curve threshold', imageUrl: 'https://example.com/high-threshold.png', bondingCurveType: 2, // 60 SOL threshold (vs default 20 SOL) mode: 0, // Rewards mode dev_fee_percentage: 40 }); ``` ### Get Bonding Curve Progress ```javascript // Get bonding curve progress and pool state const progress = await revshare.getBondingCurveProgress({ tokenAddress: 'BSAwhpQuJDV6tL27VYsYoCUMcRKeTigTbDX8CyDMwUP', rpcUrl: 'https://api.mainnet-beta.solana.com' // Optional custom RPC URL }); console.log('Pool ID:', progress.poolId); console.log('Migration Threshold:', progress.migrationThreshold.sol, 'SOL'); console.log('Base Reserve:', progress.progress.baseReserve); console.log('Quote Reserve:', progress.progress.quoteReserve); console.log('Current Price:', progress.progress.sqrtPrice); // Example output: // Pool ID: DTXqPqUtuxzKzmfeG6qyCjgqg7LJxjyNWy8ykCYwSJ7v // Migration Threshold: 20 SOL // Base Reserve: 0d5fc8dd9fc75c5f // Quote Reserve: 808208da // Current Price: 100f585958f439 ``` ### Monitor Bonding Curve Status ```javascript // Monitor a token's bonding curve progress over time async function monitorBondingProgress(tokenAddress, intervalMs = 30000) { console.log(`🔍 Monitoring bonding curve progress for ${tokenAddress}...`); const checkProgress = async () => { try { const progress = await revshare.getBondingCurveProgress({ tokenAddress, rpcUrl: 'https://api.mainnet-beta.solana.com' }); const migrationThreshold = parseFloat(progress.migrationThreshold.sol); const baseReserve = progress.progress.baseReserve; const quoteReserve = progress.progress.quoteReserve; console.log(`📊 Status Update - ${new Date().toLocaleTimeString()}:`); console.log(` Migration Threshold: ${migrationThreshold} SOL`); console.log(` Base Reserve: ${baseReserve}`); console.log(` Quote Reserve: ${quoteReserve}`); console.log(` Pool ID: ${progress.poolId}`); // Check if migration threshold is reached if (parseFloat(quoteReserve) >= migrationThreshold * 1e9) { console.log('🎉 Migration threshold reached! Token can now migrate to DEX.'); return true; // Stop monitoring } return false; // Continue monitoring } catch (error) { console.error('❌ Error checking progress:', error.message); return false; } }; // Check immediately const shouldStop = await checkProgress(); if (shouldStop) return; // Set up interval for monitoring const interval = setInterval(async () => { const shouldStop = await checkProgress(); if (shouldStop) { clearInterval(interval); console.log('✅ Monitoring stopped - migration threshold reached!'); } }, intervalMs); return interval; // Return interval ID for manual cleanup } // Usage example: // const monitorInterval = await monitorBondingProgress('BSAwhpQuJDV6tL27VYsYoCUMcRKeTigTbDX8CyDMwUP'); // // // To stop monitoring manually: // // clearInterval(monitorInterval); ``` ### Build Buy Transaction (Bonding Curve) ```javascript // Build a buy transaction without executing it const buyTransaction = await revshare.buildBondingCurveBuyTransaction({ tokenAddress: 'AJuWVNdaFyThTnrhTXUUTufyGG35nSbuqYLAVTV7uoZz', amount: 0.001, // 0.001 SOL buyerWallet: 'Bwvt6e5gzsAhU6k6cCWibaBz66Lo3hCXSgvuU9wosYCk', slippageBps: 500, // 5% slippage rpcUrl: 'https://api.mainnet-beta.solana.com' // Optional custom RPC URL }); console.log('Expected tokens:', buyTransaction.expectedTokens); console.log('Transaction:', buyTransaction.transactionBase64); // Manually process the transaction const { Transaction } = require('@solana/web3.js'); const transaction = Transaction.from(Buffer.from(buyTransaction.transactionBase64, 'base64')); transaction.sign(myKeypair); // Send to network... ``` ### Build Sell Transaction (Bonding Curve) ```javascript // Build a sell transaction without executing it const sellTransaction = await revshare.buildBondingCurveSellTransaction({ tokenAddress: 'AJuWVNdaFyThTnrhTXUUTufyGG35nSbuqYLAVTV7uoZz', amount: '1000000', // 1,000,000 tokens sellerWallet: 'Bwvt6e5gzsAhU6k6cCWibaBz66Lo3hCXSgvuU9wosYCk', slippageBps: 500, // 5% slippage rpcUrl: 'https://api.mainnet-beta.solana.com' // Optional custom RPC URL }); console.log('Expected SOL:', sellTransaction.expectedSOL); console.log('Transaction:', sellTransaction.transactionBase64); ``` ### Execute Buy Swap (Bonding Curve) ```javascript // Execute a buy swap with automatic signing and sending const buyResult = await revshare.executeBondingCurveSwap({ tokenAddress: 'AJuWVNdaFyThTnrhTXUUTufyGG35nSbuqYLAVTV7uoZz', action: 'buy', amount: 0.001, // 0.001 SOL keypair: myKeypair, slippageBps: 500, rpcUrl: 'https://api.mainnet-beta.solana.com' // Optional custom RPC URL }); console.log('Buy successful!'); console.log('Transaction signature:', buyResult.transactionSignature); console.log('Tokens received:', buyResult.expectedOutput); ``` ### Execute Sell Swap (Bonding Curve) ```javascript // Execute a sell swap with automatic signing and sending const sellResult = await revshare.executeBondingCurveSwap({ tokenAddress: 'AJuWVNdaFyThTnrhTXUUTufyGG35nSbuqYLAVTV7uoZz', action: 'sell', amount: '1000000', // 1,000,000 tokens keypair: myKeypair, slippageBps: 500, rpcUrl: 'https://api.mainnet-beta.solana.com' // Optional custom RPC URL }); console.log('Sell successful!'); console.log('Transaction signature:', sellResult.transactionSignature); console.log('SOL received:', sellResult.expectedOutput); ``` ### Launchpad Custom Fee Management ```javascript // Example: Launchpad creating a token for a client project const launchpadWallet = 'launchpad-wallet-address'; const clientWallet = 'client-wallet-address'; // Create token with launchpad as developer wallet const result = await revshare.createBondingToken({ keypair: myKeypair, developerWallet: launchpadWallet, // Launchpad receives rewards name: 'ClientProject', ticker: 'CPT', description: 'Client project token', imageUrl: 'https://example.com/client.png', dev_fee_percentage: 70, // 70% to launchpad, 30% to community ref: launchpadWallet // launchpad also earns referral (default 1%) }); // Later, launchpad can manually distribute rewards to client // This gives launchpads full control over reward distribution ``` ## Requirements - Node.js >= 16.0.0 - Solana web3.js (automatically installed as dependency) ## Browser Support - Chrome >= 88 - Firefox >= 85 - Safari >= 14 - Edge >= 88 ## License MIT License - see [LICENSE](LICENSE) file for details. ## Support - 📧 Email: support@revshare.dev - 🌐 Website: [https://revshare.dev](https://revshare.dev) - 📖 Documentation: [RevShare API Docs](https://revshare.dev/public-docs-api) - 🐛 Support: [https://revshare.dev/support](https://revshare.dev/) ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## Changelog ### 1.3.2 - ✨ NEW: Referral support via `ref` in `createBondingToken()` and `create()` - 📖 UPDATED: README with referral docs, examples, and launchpad notes ### 1.3.1 - Internal improvements ### 1.3.0 - ✨ **NEW**: Bonding curve progress tracking - `getBondingCurveProgress()` - Get pool state and migration threshold - Enhanced bonding curve swap methods with optional RPC URL support - 🔧 **ENHANCED**: All bonding curve methods now support custom RPC URLs - `buildBondingCurveBuyTransaction()` - Now supports optional `rpcUrl` parameter - `buildBondingCurveSellTransaction()` - Now supports optional `rpcUrl` parameter - `executeBondingCurveSwap()` - Now supports optional `rpcUrl` parameter - 🎯 **NEW**: Bonding curve type selection - `bondingCurveType` parameter in token creation (1=20 SOL threshold, 2=60 SOL threshold) - 📚 **NEW**: Comprehensive bonding curve example (`examples/bonding-curve-example.js`) - 📖 **UPDATED**: Enhanced documentation with progress tracking examples - 💡 **IMPROVED**: Better error handling and RPC fallback mechanisms ### 1.2.1 - 📖 **UPDATED**: Enhanced README with comprehensive swap examples - 💡 **ENHANCED**: Custom fee management documentation for launchpads - 📚 **ADDED**: Detailed launchpad use cases and multi-creator project examples - 🔧 **IMPROVED**: Better documentation structure and examples ### 1.2.0 - ✨ **NEW**: Bonding curve swap functionality - `buildBondingCurveBuyTransaction()` - Build buy transactions for bonding curve tokens - `buildBondingCurveSellTransaction()` - Build sell transactions for bonding curve tokens - `executeBondingCurveSwap()` - Execute swaps with automatic signing and sending - 📚 **NEW**: Comprehensive swap examples and documentation - 💡 **ENHANCED**: Custom fee management documentation for launchpads - 🔧 **IMPROVED**: Better method naming to distinguish bonding curve vs regular swaps - 📖 **UPDATED**: Enhanced README with swap examples and launchpad use cases ### 1.1.2 - 🐛 **FIXED**: Parameter name mismatch (`initialBuy` → `buyAmount` for API compatibility) ### 1.1.1 - 🚀 **NEW**: All-in-one token creation with automatic funding - 💰 **NEW**: Automatic SOL funding from wallet - 🎯 **NEW**: Multiple distribution modes (Rewards, Jackpot, Lottery, No Rewards) - 🔧 **NEW**: Flexible configuration for token parameters - 🌐 **NEW**: Universal compatibility (Node.js, Browser, React Native) - 📦 **NEW**: Zero configuration - works out of the box