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

merchant-sdk

v0.1.1

Published

Multi-exchange price comparison tool for ERC20 tokens across CEX and DEX

Readme

Price Comparison Tool

A comprehensive tool for comparing ERC20 token prices across multiple exchanges (CEX and DEX) on various blockchain networks. Built using the Strategy + Factory + Aggregator design patterns for maximum extensibility and maintainability.

🏗️ Architecture

This tool implements three core design patterns:

1. Strategy Pattern

  • Purpose: Encapsulates different price fetching algorithms for each exchange
  • Implementation: Each exchange (CEX/DEX) has its own strategy class
  • Benefits: Easy to add new exchanges, maintainable code, testable components

2. Factory Pattern

  • Purpose: Creates appropriate strategy instances based on exchange configuration
  • Implementation: PriceStrategyFactory manages strategy creation and registration
  • Benefits: Centralized strategy management, dynamic strategy loading

3. Aggregator Pattern

  • Purpose: Collects and compares prices from multiple exchanges
  • Implementation: PriceAggregator orchestrates price fetching and result aggregation
  • Benefits: Parallel processing, comprehensive price comparison, error handling

🚀 Features

  • Multi-Exchange Support: Compare prices across CEX and DEX exchanges
  • Multi-Network Support: Ethereum, Polygon, BSC, Base, Arbitrum, Optimism
  • Real-time Pricing: Get current market prices with intelligent caching
  • Price Impact Analysis: Calculate price impact for large trades
  • Gas Estimation: Estimate transaction costs for DEX trades
  • Error Handling: Robust error handling and fallback mechanisms
  • Extensible: Easy to add new exchanges and networks
  • Configurable Caching: Enable/disable caching with customizable TTL

📦 Installation

npm install
npm run build

🛠️ Usage

Basic Usage

import { PriceComparisonTool } from './src/index';
import { ethers } from 'ethers';

// Initialize the tool
const tool = new PriceComparisonTool();

// Define tokens
const usdc = {
  address: "0xA0b86a33E6441b8c4C8C8C8C8C8C8C8C8C8C8C8C",
  symbol: "USDC",
  name: "USD Coin",
  decimals: 6,
  chainId: 1
};

const weth = {
  address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
  symbol: "WETH",
  name: "Wrapped Ether",
  decimals: 18,
  chainId: 1
};

// Compare prices
const amountIn = ethers.parseUnits("1000", 6); // 1000 USDC
const result = await tool.comparePrices(usdc, weth, amountIn, "ethereum");

console.log("Best price:", result.summary.bestPrice);
console.log("Price spread:", result.summary.priceSpread);

Advanced Usage

// Get price from specific exchange
const binanceResult = await tool.getPriceFromExchange(
  usdc, weth, amountIn, "binance", "ethereum"
);

// Get price from MEXC exchange
const mexcResult = await tool.getPriceFromExchange(
  usdc, weth, amountIn, "mexc", "ethereum"
);

// Get prices from specific network
const polygonResult = await tool.getPricesFromNetwork(
  usdc, weth, amountIn, "polygon"
);

// Check exchange status
const status = await tool.getExchangeStatus();
console.log("Exchange status:", status);

// Cache management
console.log("Cache enabled:", tool.isCacheEnabled());
const cacheStats = tool.getCacheStats();
console.log("Cache hit rate:", cacheStats.hitRate);

// Disable cache for real-time data
tool.setCacheEnabled(false);

// Clear cache
tool.clearCache();

## 🏛️ Project Structure

src/ ├── types/ # TypeScript type definitions │ └── index.ts ├── strategies/ # Strategy pattern implementations │ ├── BasePriceStrategy.ts # Base abstract class │ ├── cex/ # CEX strategies │ │ └── BinanceStrategy.ts │ └── dex/ # DEX strategies │ └── UniswapV2Strategy.ts ├── factories/ # Factory pattern implementation │ └── PriceStrategyFactory.ts ├── aggregators/ # Aggregator pattern implementation │ └── PriceAggregator.ts ├── config/ # Configuration files │ └── defaultConfig.ts └── index.ts # Main entry point


## 🔧 Configuration

### Cache Settings

The tool includes configurable caching to improve performance:

```typescript
const tool = new PriceComparisonTool({
  useCache: true,           // Enable/disable caching
  cacheTimeout: 30000,      // Cache TTL in milliseconds (30 seconds)
  maxRetries: 3,           // Number of retries for failed requests
  retryDelay: 1000,        // Delay between retries in milliseconds
  timeout: 10000,          // Request timeout in milliseconds
});

Networks

The tool supports multiple blockchain networks:

  • Ethereum (Chain ID: 1)
  • Polygon (Chain ID: 137)
  • BSC (Chain ID: 56)
  • Base (Chain ID: 8453)
  • Arbitrum (Chain ID: 42161)
  • Optimism (Chain ID: 10)

Exchanges

CEX Exchanges

  • Binance: High liquidity, multiple pairs
  • MEXC: Global exchange with wide token selection
  • Coinbase: Institutional-grade pricing
  • Kraken: Advanced trading features
  • KuCoin: Wide token selection
  • OKX: Global exchange support

DEX Exchanges

  • Uniswap V2: Classic AMM on Ethereum
  • Uniswap V3: Concentrated liquidity
  • Sushiswap: Community-driven DEX
  • PancakeSwap: BSC's leading DEX
  • Aerodrome: Base network DEX
  • Curve: Stablecoin-focused DEX
  • Balancer: Multi-token pools
  • QuickSwap: Polygon's leading DEX

🧪 Testing

npm test

💾 Cache Management

The tool provides comprehensive cache management:

Cache Statistics

const stats = tool.getCacheStats();
console.log(`Hit Rate: ${(stats.hitRate * 100).toFixed(2)}%`);
console.log(`Cache Size: ${stats.size}/${stats.maxSize}`);

Cache Control

// Enable/disable cache
tool.setCacheEnabled(true);

// Clear all cache
tool.clearCache();

// Clean up expired entries
tool.cleanupCache();

// Get cache keys
const keys = tool.getCacheKeys();

Performance Benefits

  • Faster Response Times: Cached results return instantly
  • Reduced API Calls: Minimizes external requests
  • Cost Savings: Lower bandwidth and API usage
  • Better User Experience: Consistent response times

📈 Adding New Exchanges

1. Create Strategy Class

import { BasePriceStrategy } from '../BasePriceStrategy';
import { PriceRequest, PriceResult } from '../../types';

export class NewExchangeStrategy extends BasePriceStrategy {
  async getPrice(request: PriceRequest): Promise<PriceResult> {
    // Implement price fetching logic
    // Use this.createPriceResult() for consistent output
  }
}

2. Register in Factory

// In PriceStrategyFactory.ts
this.registerStrategy('new_exchange', NewExchangeStrategy);

3. Add Configuration

// In defaultConfig.ts
{
  name: "new_exchange",
  type: "DEX", // or "CEX"
  network: "ethereum",
  chainId: 1,
  // ... other config
}

🔮 TODO

See TODO.md for a comprehensive list of planned features and exchange implementations.

High Priority

  • [ ] Uniswap V3 Strategy
  • [ ] Sushiswap Strategy
  • [ ] PancakeSwap Strategy
  • [ ] Curve Strategy

Medium Priority

  • [ ] Balancer Strategy
  • [ ] Aerodrome Strategy
  • [ ] QuickSwap Strategy
  • [ ] 1inch Strategy

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes
  4. Add tests
  5. Submit a pull request

📄 License

ISC License

⚠️ Disclaimer

This tool is for educational and informational purposes only. Always verify prices independently before making trading decisions. The authors are not responsible for any financial losses incurred through the use of this tool.