@0xfnzero/pancakeswap-sdk
v1.0.0
Published
TypeScript SDK for PancakeSwap V2 on BSC - Trading, Liquidity Management, and Event Monitoring
Maintainers
Readme
Complete TypeScript SDK for interacting with PancakeSwap V2 on Binance Smart Chain (BSC). Trade tokens, manage liquidity, and monitor on-chain events with ease.
Features
- 🔄 Token Swaps - All swap variants (token-to-token, ETH/BNB swaps)
- 💧 Liquidity Management - Add and remove liquidity
- 📊 Pair Monitoring - Real-time event subscriptions
- 🏭 Factory Operations - Query pairs and monitor creation
- 🔍 Query Functions - Get prices, reserves, and token info
- ⛽ Gas Management - Flexible gas price configuration
- 📡 Event Subscriptions - Listen to on-chain events in real-time
- 📜 Historical Events - Query past events with block range filters
Installation
npm install @0xfnzero/pancakeswap-sdk
# or
yarn add @0xfnzero/pancakeswap-sdkQuick Start
import { PancakeRouter } from '@0xfnzero/pancakeswap-sdk';
const router = new PancakeRouter({
rpcUrl: 'https://bsc-dataseed.binance.org/',
privateKey: 'YOUR_PRIVATE_KEY',
});
// Swap BNB for tokens
await router.swapExactETHForTokens(
{
amountOutMin: '0', // Set slippage tolerance
path: [PancakeRouter.WBNB, TOKEN_ADDRESS],
to: router.getWalletAddress(),
},
'0.1' // 0.1 BNB
);Usage Examples
1. Token Swaps
Swap Exact Tokens for Tokens
import { PancakeRouter } from '@0xfnzero/pancakeswap-sdk';
const router = new PancakeRouter({
rpcUrl: 'https://bsc-dataseed.binance.org/',
privateKey: 'YOUR_PRIVATE_KEY',
});
// First approve the router to spend your tokens
await router.approveToken(TOKEN_A_ADDRESS);
// Swap 100 TOKEN_A for TOKEN_B
const result = await router.swapExactTokensForTokens({
amountIn: '100',
amountOutMin: '95', // 5% slippage tolerance
path: [TOKEN_A_ADDRESS, TOKEN_B_ADDRESS],
to: router.getWalletAddress(),
deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes
});
console.log(`Transaction hash: ${result.txHash}`);Swap BNB for Tokens
// Swap 0.1 BNB for tokens
await router.swapExactETHForTokens(
{
amountOutMin: '0',
path: [PancakeRouter.WBNB, TOKEN_ADDRESS],
to: router.getWalletAddress(),
},
'0.1' // 0.1 BNB
);Swap Tokens for BNB
// Approve first
await router.approveToken(TOKEN_ADDRESS);
// Swap tokens for BNB
await router.swapExactTokensForETH({
amountIn: '100',
amountOutMin: '0.05', // Minimum BNB to receive
path: [TOKEN_ADDRESS, PancakeRouter.WBNB],
to: router.getWalletAddress(),
});2. Liquidity Management
Add Liquidity
// Approve both tokens first
await router.approveToken(TOKEN_A_ADDRESS);
await router.approveToken(TOKEN_B_ADDRESS);
// Add liquidity
await router.addLiquidity({
tokenA: TOKEN_A_ADDRESS,
tokenB: TOKEN_B_ADDRESS,
amountADesired: '100',
amountBDesired: '100',
amountAMin: '95', // 5% slippage
amountBMin: '95',
to: router.getWalletAddress(),
});Add Liquidity with BNB
await router.approveToken(TOKEN_ADDRESS);
await router.addLiquidityETH(
{
token: TOKEN_ADDRESS,
amountTokenDesired: '100',
amountTokenMin: '95',
amountETHMin: '0.095',
to: router.getWalletAddress(),
},
'0.1' // 0.1 BNB
);Remove Liquidity
import { PancakeFactory } from '@0xfnzero/pancakeswap-sdk';
// Get pair address
const factory = new PancakeFactory({ rpcUrl: 'YOUR_RPC_URL' });
const pairAddress = await factory.getPair(TOKEN_A_ADDRESS, TOKEN_B_ADDRESS);
// Approve LP tokens
await router.approveToken(pairAddress, '10'); // Approve 10 LP tokens
// Remove liquidity
await router.removeLiquidity({
tokenA: TOKEN_A_ADDRESS,
tokenB: TOKEN_B_ADDRESS,
liquidity: '10',
amountAMin: '0',
amountBMin: '0',
to: router.getWalletAddress(),
});3. Query Functions
Get Expected Output Amount
// Get expected output for 1 TOKEN_A
const amounts = await router.getAmountsOut('1', [TOKEN_A_ADDRESS, TOKEN_B_ADDRESS]);
console.log(`Expected output: ${amounts[1]} wei`);Get Required Input Amount
// Get required input to receive 100 TOKEN_B
const amounts = await router.getAmountsIn('100', [TOKEN_A_ADDRESS, TOKEN_B_ADDRESS]);
console.log(`Required input: ${amounts[0]} wei`);Check Balances
// Get BNB balance
const bnbBalance = await router.getBNBBalance();
console.log(`BNB Balance: ${bnbBalance}`);
// Get token balance
const tokenBalance = await router.getTokenBalance(TOKEN_ADDRESS);
console.log(`Token Balance: ${tokenBalance}`);4. Factory Operations
import { PancakeFactory } from '@0xfnzero/pancakeswap-sdk';
const factory = new PancakeFactory({
rpcUrl: 'https://bsc-dataseed.binance.org/',
});
// Get pair address
const pairAddress = await factory.getPair(TOKEN_A_ADDRESS, TOKEN_B_ADDRESS);
console.log(`Pair address: ${pairAddress}`);
// Check if pair exists
const exists = await factory.pairExists(TOKEN_A_ADDRESS, TOKEN_B_ADDRESS);
console.log(`Pair exists: ${exists}`);
// Get all pairs count
const pairsCount = await factory.allPairsLength();
console.log(`Total pairs: ${pairsCount}`);
// Find all pairs for a token
const pairs = await factory.findPairsWithToken(TOKEN_ADDRESS);
console.log(`Found ${pairs.length} pairs`);5. Pair Operations
import { PancakePair } from '@0xfnzero/pancakeswap-sdk';
const pair = new PancakePair({
rpcUrl: 'https://bsc-dataseed.binance.org/',
pairAddress: 'PAIR_ADDRESS',
});
// Get comprehensive pair info
const pairInfo = await pair.getPairInfo();
console.log(`Pair: ${pairInfo.token0.symbol}/${pairInfo.token1.symbol}`);
console.log(`Price: ${pairInfo.price0}`);
console.log(`Reserves: ${pairInfo.reserves.reserve0} / ${pairInfo.reserves.reserve1}`);
// Get reserves
const reserves = await pair.getReserves();
console.log(`Reserve0: ${reserves.reserve0}`);
console.log(`Reserve1: ${reserves.reserve1}`);
// Get token addresses
const token0 = await pair.token0();
const token1 = await pair.token1();
// Get current price
const price = await pair.getPrice();
console.log(`Token0 price in Token1: ${price.price0}`);
console.log(`Token1 price in Token0: ${price.price1}`);6. Event Subscriptions
Subscribe to Pair Creation Events
const factory = new PancakeFactory({ rpcUrl: 'YOUR_RPC_URL' });
// Listen for all pair creations
const listenerId = factory.onPairCreated((event) => {
console.log('New pair created!');
console.log(`Token0: ${event.token0}`);
console.log(`Token1: ${event.token1}`);
console.log(`Pair address: ${event.pair}`);
});
// Unsubscribe later
factory.off(listenerId);Subscribe to Swap Events
const pair = new PancakePair({ rpcUrl: 'YOUR_RPC_URL', pairAddress: 'PAIR_ADDRESS' });
// Listen for swaps
const swapListenerId = pair.onSwap((event) => {
console.log('Swap detected!');
console.log(`Amount0In: ${event.amount0In}`);
console.log(`Amount1Out: ${event.amount1Out}`);
console.log(`To: ${event.to}`);
});
// Unsubscribe
pair.off(swapListenerId);Subscribe to Liquidity Events
// Listen for liquidity additions
const mintListenerId = pair.onMint((event) => {
console.log('Liquidity added!');
console.log(`Amount0: ${event.amount0}`);
console.log(`Amount1: ${event.amount1}`);
});
// Listen for liquidity removals
const burnListenerId = pair.onBurn((event) => {
console.log('Liquidity removed!');
console.log(`Amount0: ${event.amount0}`);
console.log(`Amount1: ${event.amount1}`);
});
// Listen for reserve syncs
const syncListenerId = pair.onSync((event) => {
console.log('Reserves synced!');
console.log(`Reserve0: ${event.reserve0}`);
console.log(`Reserve1: ${event.reserve1}`);
});7. Query Historical Events
// Get historical swap events
const swaps = await pair.getSwapEvents(0, 'latest');
console.log(`Found ${swaps.length} swaps`);
// Get historical pair creations
const creations = await factory.getPairCreatedEvents(undefined, undefined, 0, 'latest');
console.log(`Found ${creations.length} pair creations`);
// Get mints for specific block range
const mints = await pair.getMintEvents(30000000, 30100000);
console.log(`Found ${mints.length} liquidity additions`);8. Gas Management
// Custom gas settings
await router.swapExactETHForTokens(
{
amountOutMin: '0',
path: [PancakeRouter.WBNB, TOKEN_ADDRESS],
to: router.getWalletAddress(),
gas: {
gasLimit: 300000,
gasPrice: '5', // 5 gwei
},
},
'0.1'
);
// EIP-1559 style gas (BSC supports this now)
await router.swapExactTokensForTokens({
amountIn: '100',
amountOutMin: '95',
path: [TOKEN_A_ADDRESS, TOKEN_B_ADDRESS],
to: router.getWalletAddress(),
gas: {
maxFeePerGas: '10',
maxPriorityFeePerGas: '2',
},
});Contract Addresses (BSC Mainnet)
// Router
PancakeRouter.DEFAULT_ROUTER = '0x10ED43C718714eb63d5aA57B78B54704E256024E';
// Factory
PancakeFactory.DEFAULT_FACTORY = '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73';
// WBNB
PancakeRouter.WBNB = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';Common Token Addresses (BSC)
const BUSD = '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56';
const USDT = '0x55d398326f99059fF775485246999027B3197955';
const CAKE = '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82';
const ETH = '0x2170Ed0880ac9A755fd29B2688956BD959F933F8';
const BTCB = '0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c';API Reference
PancakeRouter
swapExactTokensForTokens(params)- Swap exact input tokensswapTokensForExactTokens(params)- Swap for exact output tokensswapExactETHForTokens(params, ethAmount)- Swap BNB for tokensswapETHForExactTokens(params, maxETH)- Swap BNB for exact tokensswapExactTokensForETH(params)- Swap tokens for BNBswapTokensForExactETH(params)- Swap for exact BNBaddLiquidity(params)- Add liquidity for token pairaddLiquidityETH(params, ethAmount)- Add liquidity with BNBremoveLiquidity(params)- Remove liquidityremoveLiquidityETH(params)- Remove liquidity with BNBapproveToken(tokenAddress, amount?)- Approve token spendinggetAmountsOut(amountIn, path)- Get expected output amountsgetAmountsIn(amountOut, path)- Get required input amounts
PancakeFactory
getPair(tokenA, tokenB)- Get pair addresspairExists(tokenA, tokenB)- Check if pair existsallPairsLength()- Get total pairs countallPairs(index)- Get pair by indexgetAllPairs()- Get all pair addressesfindPairsWithToken(tokenAddress)- Find pairs containing tokenonPairCreated(listener)- Subscribe to pair creation eventsgetPairCreatedEvents(token0?, token1?, fromBlock?, toBlock?)- Query historical events
PancakePair
getReserves()- Get current reservestoken0()- Get token0 addresstoken1()- Get token1 addressgetPrice()- Get current token pricesgetPairInfo()- Get comprehensive pair informationgetTokensInfo()- Get detailed token informationtotalSupply()- Get LP token supplybalanceOf(address)- Get LP token balanceonMint(listener)- Subscribe to liquidity additionsonBurn(listener)- Subscribe to liquidity removalsonSwap(listener)- Subscribe to swap eventsonSync(listener)- Subscribe to reserve updatesgetSwapEvents(fromBlock?, toBlock?)- Query historical swapsgetMintEvents(fromBlock?, toBlock?)- Query historical mintsgetBurnEvents(fromBlock?, toBlock?)- Query historical burns
TypeScript Support
This SDK is written in TypeScript and includes full type definitions.
import {
PancakeRouter,
PancakeFactory,
PancakePair,
SwapExactTokensParams,
AddLiquidityParams,
TransactionResult,
} from '@0xfnzero/pancakeswap-sdk';Error Handling
try {
const result = await router.swapExactETHForTokens(
{
amountOutMin: '0',
path: [PancakeRouter.WBNB, TOKEN_ADDRESS],
to: router.getWalletAddress(),
},
'0.1'
);
console.log(`Success: ${result.txHash}`);
} catch (error) {
console.error('Swap failed:', error.message);
// Handle error appropriately
}Requirements
- Node.js >= 18.0.0
- ethers.js ^6.13.0
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Security
This SDK handles private keys. Always keep your private keys secure and never commit them to version control.
Disclaimer
This SDK is provided as-is. Use at your own risk. Always test on testnet before using with real funds.
