Package Exports
- bnb-trading-sdk-v1
Readme
@bnb-trading-sdk/trading
Professional BNB and four.meme trading SDK for Binance Smart Chain with automatic migration detection and PancakeSwap integration.
Features
- 🟣 Four.meme Trading - Buy and sell tokens on four.meme before migration
- 🥞 PancakeSwap Trading - Automatic support for migrated tokens on PancakeSwap
- 🔍 Auto-Detection - Automatically detects if token has migrated and uses appropriate method
- 📊 Token Analytics - Get token info, estimates, and metadata
- ⚡ Fast Transactions - Optimized gas limits and transaction handling
- 🔒 Type Safe - Full TypeScript definitions included
- 🛠️ Easy to Use - Simple API with smart defaults
Installation
npm install @bnb-trading-sdk/tradingQuick Start
Secure Initialization (Recommended)
const { ethers } = require('ethers');
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
// Create wallet outside SDK (secure - private key managed separately)
// IMPORTANT: Never hardcode private keys or use process.env in shared code
// Use secure key management in your application
const provider = new ethers.JsonRpcProvider('https://bsc-dataseed.binance.org');
const wallet = new ethers.Wallet(yourPrivateKey, provider); // Get from secure storage
// Initialize SDK with wallet (secure - no private key exposed to SDK)
const sdk = new BNBTradingSDK({
wallet,
rpcUrl: 'https://bsc-dataseed.binance.org' // Optional, has default
});
// Smart buy - automatically detects migration status
const result = await sdk.buyToken('0x...', '0.1'); // Buy with 0.1 BNB
console.log('Transaction hash:', result.txHash);
// Smart sell - automatically detects migration status
const sellResult = await sdk.sellToken('0x...', '1000'); // Sell 1000 tokens
console.log('Sell transaction hash:', sellResult.txHash);Using with Browser Wallet (MetaMask, etc.)
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
// Connect to browser wallet
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
// Initialize SDK with signer
const sdk = new BNBTradingSDK({
signer,
rpcUrl: 'https://bsc-dataseed.binance.org'
});
// Use SDK normally
const result = await sdk.buyToken('0x...', '0.1');Deprecated: Private Key Mode (Not Recommended)
⚠️ WARNING: Using privateKey directly is deprecated and less secure. Use wallet or signer instead.
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
// Deprecated: Direct private key (will show warning)
const sdk = new BNBTradingSDK({
privateKey: 'your-private-key-here', // ⚠️ Not recommended
rpcUrl: 'https://bsc-dataseed.binance.org'
});Configuration
Constructor Options
interface BNBTradingSDKConfig {
wallet?: ethers.Wallet; // Recommended: Wallet instance (secure)
signer?: ethers.Signer; // Recommended: Signer instance (secure)
privateKey?: string; // Deprecated: Use wallet/signer instead
provider?: ethers.Provider; // Optional: Custom provider
rpcUrl?: string; // Optional: BSC RPC URL (default: https://bsc-dataseed.binance.org)
tokenManager2?: string; // Optional: TokenManager2 address (has default)
helper3Address?: string; // Optional: Helper3 address (has default)
pancakeRouterAddress?: string; // Optional: PancakeRouter address (has default)
wbnbAddress?: string; // Optional: WBNB address (has default)
}Security Best Practices:
- ✅ Always use
walletorsigneroption - ✅ Create wallet/signer outside the SDK
- ✅ Never commit private keys to version control
- ✅ Never use
process.env.PRIVATE_KEYin shared code or examples - ✅ Use secure key management services (AWS Secrets Manager, HashiCorp Vault, etc.)
- ✅ Store private keys in encrypted storage, never in plain text
- ❌ Avoid passing
privateKeydirectly (deprecated) - ❌ Never hardcode private keys in code
API Reference
Migration Status
getMigrationStatus(tokenAddress: string): Promise<boolean>
Check if a token has migrated to PancakeSwap.
const isMigrated = await sdk.getMigrationStatus('0x...');
console.log(isMigrated ? 'On PancakeSwap' : 'On four.meme');Token Information
getTokenInfo(tokenAddress: string): Promise<TokenInfo>
Get comprehensive token information from Helper3 contract.
const info = await sdk.getTokenInfo('0x...');
console.log('Token info:', info);
// Returns: version, tokenManager, quote, lastPrice, tradingFeeRate,
// minTradingFee, launchTime, offers, maxOffers, funds,
// maxFunds, liquidityAddedgetTokenMetadata(tokenAddress: string): Promise<TokenMetadata>
Get basic token metadata (name, symbol, decimals, totalSupply).
const metadata = await sdk.getTokenMetadata('0x...');
console.log(`${metadata.name} (${metadata.symbol})`);Estimates
estimateBuy(tokenAddress: string, bnbAmount: string | number): Promise<BuyEstimate>
Estimate how many tokens you'll receive for a given BNB amount (four.meme).
const estimate = await sdk.estimateBuy('0x...', '0.1');
console.log(`Estimated tokens: ${estimate.estimatedAmount}`);
console.log(`Estimated cost: ${estimate.estimatedCost} BNB`);
console.log(`Estimated fee: ${estimate.estimatedFee} BNB`);estimateSell(tokenAddress: string, tokenAmount: string | number): Promise<SellEstimate>
Estimate how much BNB you'll receive for selling tokens (four.meme).
const estimate = await sdk.estimateSell('0x...', '1000');
console.log(`Estimated BNB: ${estimate.funds}`);
console.log(`Fee: ${estimate.fee} BNB`);Buying Tokens
buyToken(tokenAddress: string, bnbAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Smart buy - Automatically detects migration status and uses the appropriate method (four.meme or PancakeSwap).
// Simple buy with 0.1 BNB
const result = await sdk.buyToken('0x...', '0.1');
console.log('Transaction:', result.txHash);
// With custom options
const result = await sdk.buyToken('0x...', '0.1', {
gasLimit: 400000,
gasPrice: 5, // gwei
minAmount: '1000' // minimum tokens (for four.meme)
});buyFourMemeToken(tokenAddress: string, bnbAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Buy token on four.meme (before migration).
const result = await sdk.buyFourMemeToken('0x...', '0.1');buyPancakeToken(tokenAddress: string, bnbAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Buy token on PancakeSwap (after migration).
const result = await sdk.buyPancakeToken('0x...', '0.1');Selling Tokens
sellToken(tokenAddress: string, tokenAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Smart sell - Automatically detects migration status and uses the appropriate method.
// Simple sell
const result = await sdk.sellToken('0x...', '1000');
console.log('Transaction:', result.txHash);
// With custom options
const result = await sdk.sellToken('0x...', '1000', {
gasLimit: 250000,
gasPrice: 5, // gwei
amountOutMin: '0.09' // minimum BNB (for PancakeSwap)
});sellFourMemeToken(tokenAddress: string, tokenAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Sell token on four.meme (before migration).
const result = await sdk.sellFourMemeToken('0x...', '1000');sellPancakeToken(tokenAddress: string, tokenAmount: string | number, options?: TransactionOptions): Promise<TransactionResult>
Sell token on PancakeSwap (after migration).
const result = await sdk.sellPancakeToken('0x...', '1000');Approvals
approveToken(tokenAddress: string, amount?: string | number): Promise<string | null>
Approve TokenManager to spend tokens (for four.meme trading). Returns null if already approved.
const txHash = await sdk.approveToken('0x...');
if (txHash) {
console.log('Approval transaction:', txHash);
} else {
console.log('Already approved');
}approvePancakeRouter(tokenAddress: string, amount?: string | number): Promise<string | null>
Approve PancakeRouter to spend tokens (for PancakeSwap trading).
const txHash = await sdk.approvePancakeRouter('0x...');Utilities
getBalance(tokenAddress?: string | null): Promise<string>
Get balance of BNB or a specific token.
// BNB balance
const bnbBalance = await sdk.getBalance();
console.log(`BNB: ${bnbBalance}`);
// Token balance
const tokenBalance = await sdk.getBalance('0x...');
console.log(`Tokens: ${tokenBalance}`);getWalletAddress(): string
Get the wallet address associated with the SDK.
const address = sdk.getWalletAddress();
console.log('Wallet:', address);Gas & Transaction Management
getGasPrice(): Promise<Object>
Get current network gas prices.
const gasPrice = await sdk.getGasPrice();
console.log(`Gas price: ${gasPrice.gasPriceGwei} gwei`);
console.log(`Max fee per gas: ${gasPrice.maxFeePerGas}`);estimateGasBuy(tokenAddress: string, bnbAmount: string | number): Promise<Object>
Estimate gas needed for a buy transaction.
const gasEstimate = await sdk.estimateGasBuy('0x...', '0.1');
console.log(`Estimated gas: ${gasEstimate.gasLimit}`);estimateGasSell(tokenAddress: string, tokenAmount: string | number): Promise<Object>
Estimate gas needed for a sell transaction.
const gasEstimate = await sdk.estimateGasSell('0x...', '1000');
console.log(`Estimated gas: ${gasEstimate.gasLimit}`);waitForTransaction(txHash: string, confirmations?: number, timeout?: number): Promise<Object>
Wait for transaction confirmation.
const receipt = await sdk.waitForTransaction(txHash, 1, 60000);
console.log(`Confirmed in block: ${receipt.blockNumber}`);getTransactionStatus(txHash: string): Promise<Object>
Get detailed transaction status.
const status = await sdk.getTransactionStatus(txHash);
console.log(`Status: ${status.status}`);
console.log(`Confirmations: ${status.confirmations}`);Price & Quote Functions
getPancakeSwapQuote(tokenAddress: string, amount: string | number, isBuy?: boolean): Promise<Object>
Get price quote from PancakeSwap.
const quote = await sdk.getPancakeSwapQuote('0x...', '0.1', true);
console.log(`Will receive: ${quote.outputAmount} tokens`);
console.log(`Price: ${quote.price}`);getTokenPrice(tokenAddress: string): Promise<Object>
Get current token price in BNB (works for both four.meme and PancakeSwap).
const price = await sdk.getTokenPrice('0x...');
console.log(`Price: ${price.price} BNB per token`);
console.log(`Source: ${price.source}`);calculatePriceImpact(tokenAddress: string, amount: string | number, isBuy?: boolean): Promise<Object>
Calculate price impact for a trade.
const impact = await sdk.calculatePriceImpact('0x...', '0.1', true);
console.log(`Price impact: ${impact.priceImpact}%`);
console.log(`Expected output: ${impact.expectedOutput}`);calculateOptimalSlippage(tokenAddress: string, amount: string | number, isBuy?: boolean): Promise<Object>
Calculate recommended slippage tolerance.
const slippage = await sdk.calculateOptimalSlippage('0x...', '0.1', true);
console.log(`Recommended: ${slippage.recommended}%`);
console.log(`Safe: ${slippage.safe}%`);
console.log(`Aggressive: ${slippage.aggressive}%`);Advanced Trading Functions
getOptimalBuyAmount(tokenAddress: string, maxPriceImpact?: number, maxBNB?: string | number): Promise<Object>
Find optimal buy amount within price impact tolerance.
const optimal = await sdk.getOptimalBuyAmount('0x...', 5); // Max 5% impact
console.log(`Optimal amount: ${optimal.optimalAmount} BNB`);
console.log(`Price impact: ${optimal.optimalPriceImpact}%`);calculateProfitLoss(tokenAddress: string, buyAmount: string | number, sellTokenAmount: string | number): Promise<Object>
Calculate profit/loss for a potential trade.
const pnl = await sdk.calculateProfitLoss('0x...', '0.1', '1000');
console.log(`Profit: ${pnl.profit} BNB (${pnl.profitPercent}%)`);
console.log(`Is profit: ${pnl.isProfit}`);Utility Functions
isValidToken(tokenAddress: string): Promise<boolean>
Check if an address is a valid ERC20 token contract.
const isValid = await sdk.isValidToken('0x...');
console.log(`Is valid token: ${isValid}`);batchApproveTokens(tokenAddresses: string[], amount?: string | number): Promise<Array<Object>>
Approve multiple tokens at once.
const results = await sdk.batchApproveTokens([
'0x...',
'0x...',
'0x...'
]);
results.forEach(result => {
console.log(`${result.tokenAddress}: ${result.success ? 'Approved' : 'Failed'}`);
});formatTokenAmount(amount: string | number, decimals?: number): string
Format token amount with proper decimals.
const formatted = sdk.formatTokenAmount('1000000000000000000', 18);
console.log(formatted); // "1.0"parseTokenAmount(amount: string | number, decimals?: number): bigint
Parse token amount to wei (BigInt).
const parsed = sdk.parseTokenAmount('1.0', 18);
console.log(parsed); // 1000000000000000000nWallet Generation
BNBTradingSDK.generateWallet(options?: Object): Object
Generate a new random wallet. This is a static method that creates a secure wallet.
const { ethers } = require('ethers');
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
// Generate a new wallet
const walletInfo = BNBTradingSDK.generateWallet({
rpcUrl: 'https://bsc-dataseed.binance.org'
});
console.log('New wallet address:', walletInfo.address);
console.log('Private key:', walletInfo.privateKey); // ⚠️ Store securely!
console.log('Mnemonic:', walletInfo.mnemonic); // ⚠️ Store securely!
// Use the wallet to create an SDK instance
const sdk = walletInfo.getSDK({
rpcUrl: 'https://bsc-dataseed.binance.org'
});
// Or use the wallet directly
const provider = new ethers.JsonRpcProvider('https://bsc-dataseed.binance.org');
const sdk2 = new BNBTradingSDK({
wallet: walletInfo.wallet,
rpcUrl: 'https://bsc-dataseed.binance.org'
});Important Security Notes:
- ⚠️ NEVER commit the private key or mnemonic to version control
- ⚠️ Store private keys in secure, encrypted storage
- ⚠️ Use secure key management services for production
- ✅ The generated wallet is cryptographically secure
- ✅ Private key is generated using secure random number generation
Returns:
{
address: string; // Wallet address
privateKey: string; // Private key (keep secure!)
mnemonic: string | null; // Mnemonic phrase (if available)
wallet: ethers.Wallet; // Wallet instance
getSDK: (config?) => BNBTradingSDK; // Helper to create SDK with this wallet
}Transaction Options
All buy/sell methods accept an optional options parameter:
interface TransactionOptions {
gasLimit?: number; // Gas limit (defaults provided)
gasPrice?: number; // Gas price in gwei
minAmount?: string | number; // Minimum tokens for four.meme buy
amountOutMin?: string | number; // Minimum output for PancakeSwap
deadline?: number; // Transaction deadline in seconds (default: now + 3600)
}Complete Examples
Example 1: Complete Trading Flow
const { ethers } = require('ethers');
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
async function tradeToken() {
// Secure initialization
// Get private key from secure storage, NOT from environment variables
const provider = new ethers.JsonRpcProvider('https://bsc-dataseed.binance.org');
const wallet = new ethers.Wallet(yourPrivateKey, provider); // From secure key management
const sdk = new BNBTradingSDK({
wallet,
rpcUrl: 'https://bsc-dataseed.binance.org'
});
const tokenAddress = '0x...';
// Check migration status
const isMigrated = await sdk.getMigrationStatus(tokenAddress);
console.log(`Token migrated: ${isMigrated}`);
// Get token info
const info = await sdk.getTokenInfo(tokenAddress);
console.log('Token info:', info);
// Estimate buy
const buyEstimate = await sdk.estimateBuy(tokenAddress, '0.1');
console.log(`Buy estimate: ${buyEstimate.estimatedAmount} tokens`);
// Buy token (auto-detects migration)
const buyResult = await sdk.buyToken(tokenAddress, '0.1');
console.log(`Buy tx: ${buyResult.txHash}`);
// Wait a bit
await new Promise(resolve => setTimeout(resolve, 5000));
// Get token balance
const balance = await sdk.getBalance(tokenAddress);
console.log(`Token balance: ${balance}`);
// Estimate sell
const sellEstimate = await sdk.estimateSell(tokenAddress, balance);
console.log(`Sell estimate: ${sellEstimate.funds} BNB`);
// Sell half
const halfBalance = (parseFloat(balance) / 2).toString();
const sellResult = await sdk.sellToken(tokenAddress, halfBalance);
console.log(`Sell tx: ${sellResult.txHash}`);
}
tradeToken().catch(console.error);Example 2: Trading Bot with Error Handling
const { ethers } = require('ethers');
const BNBTradingSDK = require('@bnb-trading-sdk/trading');
class TradingBot {
constructor(privateKey, rpcUrl = 'https://bsc-dataseed.binance.org') {
// Secure initialization
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(privateKey, provider);
this.sdk = new BNBTradingSDK({ wallet, rpcUrl });
}
async buy(tokenAddress, bnbAmount) {
try {
// Check if we have enough BNB
const bnbBalance = await this.sdk.getBalance();
if (parseFloat(bnbBalance) < parseFloat(bnbAmount)) {
throw new Error('Insufficient BNB balance');
}
// Estimate first
const estimate = await this.sdk.estimateBuy(tokenAddress, bnbAmount);
console.log(`Will receive ~${estimate.estimatedAmount} tokens`);
// Execute buy
const result = await this.sdk.buyToken(tokenAddress, bnbAmount, {
gasLimit: 400000,
gasPrice: 5
});
return {
success: true,
txHash: result.txHash,
estimatedTokens: estimate.estimatedAmount
};
} catch (error) {
console.error('Buy error:', error.message);
return { success: false, error: error.message };
}
}
async sell(tokenAddress, percentage = 100) {
try {
const balance = await this.sdk.getBalance(tokenAddress);
const amountToSell = (parseFloat(balance) * percentage / 100).toString();
if (parseFloat(amountToSell) === 0) {
throw new Error('No tokens to sell');
}
const estimate = await this.sdk.estimateSell(tokenAddress, amountToSell);
console.log(`Will receive ~${estimate.funds} BNB`);
const result = await this.sdk.sellToken(tokenAddress, amountToSell);
return {
success: true,
txHash: result.txHash,
estimatedBnb: estimate.funds
};
} catch (error) {
console.error('Sell error:', error.message);
return { success: false, error: error.message };
}
}
}
// Usage
// Pass private key from secure storage, NOT from environment variables
const bot = new TradingBot(yourPrivateKey); // From secure key management
bot.buy('0x...', '0.1').then(console.log);Example 3: TypeScript Usage
import { ethers } from 'ethers';
import BNBTradingSDK from '@bnb-trading-sdk/trading';
// Secure initialization
// Get private key from secure storage, NOT from environment variables
const provider = new ethers.JsonRpcProvider('https://bsc-dataseed.binance.org');
const wallet = new ethers.Wallet(yourPrivateKey, provider); // From secure key management
const sdk = new BNBTradingSDK({
wallet,
rpcUrl: 'https://bsc-dataseed.binance.org'
});
async function main() {
const tokenAddress = '0x...';
const isMigrated = await sdk.getMigrationStatus(tokenAddress);
const tokenInfo = await sdk.getTokenInfo(tokenAddress);
const metadata = await sdk.getTokenMetadata(tokenAddress);
console.log(`${metadata.name} (${metadata.symbol})`);
console.log(`Migrated: ${isMigrated}`);
console.log(`Last price: ${tokenInfo.lastPrice}`);
const result = await sdk.buyToken(tokenAddress, '0.1');
console.log(`Buy transaction: ${result.txHash}`);
}
main().catch(console.error);Default Contract Addresses
The SDK includes default addresses for BSC mainnet:
- TOKEN_MANAGER2:
0x5c952063c7fc8610FFDB798152D69F0B9550762b - HELPER3_ADDRESS:
0xF251F83e40a78868FcfA3FA4599Dad6494E46034 - PANCAKE_ROUTER_ADDRESS:
0x10ED43C718714eb63d5aA57B78B54704E256024E - WBNB_ADDRESS:
0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c - RPC_URL:
https://bsc-dataseed.binance.org
You can override these in the constructor if needed.
Error Handling
All methods throw errors that should be caught:
try {
const result = await sdk.buyToken('0x...', '0.1');
console.log('Success:', result.txHash);
} catch (error) {
console.error('Transaction failed:', error.message);
// Handle error (insufficient funds, revert, etc.)
}Common errors:
Failed to buy token: insufficient funds for gas- Need more BNBFailed to buy token: execution reverted- Transaction reverted (check token address, amounts, etc.)Failed to approve token: user rejected- User rejected transaction
Security Notes
🔒 Best Practices:
- ✅ Always use
walletorsigneroption - Never passprivateKeydirectly - ✅ Create wallet outside SDK - Keep private key management separate
- ✅ Never commit private keys to version control
- ✅ Use environment variables or secure key management services
- ✅ Test on testnet first before mainnet
- ✅ Start with small amounts when testing
- ✅ Review transaction details before signing
- ❌ Avoid using
privateKeyoption - It's deprecated and less secure
Requirements
- Node.js >= 18.0.0
- ethers.js ^6.9.0 (included as dependency)
License
MIT
Support
- Issues: https://github.com/solEchoForge/bnb-trading-sdk/issues
- Sponsors: https://github.com/sponsors/solEchoForge
Author
James Alien - https://github.com/solEchoForge