npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@0xfnzero/pancakeswap-sdk

v1.0.0

Published

TypeScript SDK for PancakeSwap V2 on BSC - Trading, Liquidity Management, and Event Monitoring

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-sdk

Quick 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 tokens
  • swapTokensForExactTokens(params) - Swap for exact output tokens
  • swapExactETHForTokens(params, ethAmount) - Swap BNB for tokens
  • swapETHForExactTokens(params, maxETH) - Swap BNB for exact tokens
  • swapExactTokensForETH(params) - Swap tokens for BNB
  • swapTokensForExactETH(params) - Swap for exact BNB
  • addLiquidity(params) - Add liquidity for token pair
  • addLiquidityETH(params, ethAmount) - Add liquidity with BNB
  • removeLiquidity(params) - Remove liquidity
  • removeLiquidityETH(params) - Remove liquidity with BNB
  • approveToken(tokenAddress, amount?) - Approve token spending
  • getAmountsOut(amountIn, path) - Get expected output amounts
  • getAmountsIn(amountOut, path) - Get required input amounts

PancakeFactory

  • getPair(tokenA, tokenB) - Get pair address
  • pairExists(tokenA, tokenB) - Check if pair exists
  • allPairsLength() - Get total pairs count
  • allPairs(index) - Get pair by index
  • getAllPairs() - Get all pair addresses
  • findPairsWithToken(tokenAddress) - Find pairs containing token
  • onPairCreated(listener) - Subscribe to pair creation events
  • getPairCreatedEvents(token0?, token1?, fromBlock?, toBlock?) - Query historical events

PancakePair

  • getReserves() - Get current reserves
  • token0() - Get token0 address
  • token1() - Get token1 address
  • getPrice() - Get current token prices
  • getPairInfo() - Get comprehensive pair information
  • getTokensInfo() - Get detailed token information
  • totalSupply() - Get LP token supply
  • balanceOf(address) - Get LP token balance
  • onMint(listener) - Subscribe to liquidity additions
  • onBurn(listener) - Subscribe to liquidity removals
  • onSwap(listener) - Subscribe to swap events
  • onSync(listener) - Subscribe to reserve updates
  • getSwapEvents(fromBlock?, toBlock?) - Query historical swaps
  • getMintEvents(fromBlock?, toBlock?) - Query historical mints
  • getBurnEvents(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.