merchant-sdk
v0.1.1
Published
Multi-exchange price comparison tool for ERC20 tokens across CEX and DEX
Maintainers
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:
PriceStrategyFactorymanages strategy creation and registration - Benefits: Centralized strategy management, dynamic strategy loading
3. Aggregator Pattern
- Purpose: Collects and compares prices from multiple exchanges
- Implementation:
PriceAggregatororchestrates 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
- Fork the repository
- Create a feature branch
- Implement your changes
- Add tests
- 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.
