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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@stochain/dex-swap

v1.0.0

Published

DEX swap utilities for PancakeSwap and other DEXs

Readme

@stochain/dex-swap

DEX swap utilities for PancakeSwap and other decentralized exchanges.

Installation

npm install @stochain/dex-swap ethers simple-pancakeswap-sdk

Features

  • 🥞 PancakeSwap integration
  • 💱 Token swap utilities
  • 📊 Exchange rate calculation
  • ✅ Swap validation
  • 🎣 React hooks for swap management
  • 💰 Token balance queries

Usage

Basic Swap with PancakeSwap

import { trade, swap } from '@stochain/dex-swap';
import { Wallet } from 'ethers';

// Create trade
const tradeContext = await trade({
  ethAddress: '0x...',
  fromTokenAddress: '0x...',
  toTokenAddress: '0x...',
  amount: '1.0',
  slippage: 0.005, // 0.5%
  deadlineMinutes: 20
});

// Execute swap
const wallet = new Wallet('private-key');
const result = await swap(wallet, tradeContext);

React Hook for Swap Management

import { useSwap } from '@stochain/dex-swap';

function SwapScreen() {
  const {
    fromToken,
    toToken,
    setFromToken,
    setToToken,
    fromAmount,
    toAmount,
    handleFromAmountChange,
    handleMaxAmount,
    swapTokens,
    executeSwap,
    isSwapEnabled,
    exchangeRate
  } = useSwap({
    onSwapComplete: () => console.log('Swap completed'),
    onSwapError: (error) => console.error('Swap failed:', error)
  });

  return (
    <View>
      <TextInput
        value={fromAmount}
        onChangeText={handleFromAmountChange}
        placeholder="0.00"
      />
      <Text>Exchange Rate: {exchangeRate}</Text>
      <Text>You will receive: {toAmount}</Text>
      <Button
        title="Swap"
        onPress={executeSwap}
        disabled={!isSwapEnabled()}
      />
    </View>
  );
}

Swap Validation

import { validateSwap } from '@stochain/dex-swap';

const validation = validateSwap(fromToken, toToken, '1.0');

if (!validation.isValid) {
  console.error('Validation errors:', validation.errors);
}

Exchange Rate Calculation

import { calculateExchangeRate } from '@stochain/dex-swap';

const result = calculateExchangeRate(
  fromToken,
  toToken,
  '1.0'
);

console.log('Rate:', result.rate);
console.log('To Amount:', result.toAmount);

Token Balance

import { getTokenBalance, getBNBToken } from '@stochain/dex-swap';
import { Wallet } from 'ethers';

const wallet = new Wallet('private-key');

// Get BNB balance
const bnbToken = await getBNBToken(wallet);
console.log('BNB balance:', bnbToken.balance.val);

// Get ERC20 token balance
const balance = await getTokenBalance(wallet, {
  address: '0x...'
});
console.log('Token balance:', balance.val);

API Reference

PancakeSwap Functions

  • trade(params): Create a trade on PancakeSwap
  • swap(wallet, tradeContext): Execute swap transaction
  • getTokenBalance(wallet, token, providerUrl?): Get token balance
  • getBNBToken(wallet): Get BNB token info
  • getToken(tokenAddress, chainId): Get token information

Swap Service Functions

  • calculateExchangeRate(fromToken, toToken, fromAmount): Calculate exchange rate
  • validateSwap(fromToken, toToken, fromAmount): Validate swap parameters
  • executeSwap(fromToken, toToken, fromAmount, toAmount): Execute swap
  • updateBalancesAfterSwap(...): Update balances after swap

React Hooks

  • useSwap(options?): Hook for swap state management

Types

interface Token {
  symbol: string;
  name: string;
  address?: string;
  network: string;
  balance?: string;
  price?: number;
}

interface TradeParams {
  ethAddress: string;
  fromTokenAddress: string;
  toTokenAddress: string;
  amount: string;
  providerUrl?: string;
  slippage?: number;
  deadlineMinutes?: number;
}

interface ValidationResult {
  isValid: boolean;
  errors: string[];
}

License

MIT