Skip to content

kostandinang/eth-swap-api

Repository files navigation

NestJS UniswapV2 & Gas Price API

Tests

A high-performance NestJS application providing Ethereum gas prices and UniswapV2 swap calculations.

Features

  • Ethereum Gas Price API
    • Fast, production-ready endpoint for current gas prices
  • UniswapV2 Swap Calculations
    • Get swap rates and output amounts for any token pair
  • Redis Caching
    • Fetch the gas price with low latency

Prerequisites

  • Node.js 20+
  • Redis
  • Alchemy API Key

Installation

  1. Clone the repository
  2. Copy .env.example into .env
  3. Provide ALCHEMY_API_KEY
  4. Install dependencies:
pnpm install

Run

pnpm start:dev

Running Tests

Run all tests locally:

pnpm test

Or view the latest test results in GitHub Actions.

Testing Endpoints

Gas price

curl -X GET "http://localhost:3000/api/v1/gasPrice" | jq

Uniswap

curl -X GET "http://localhost:3000/api/v1/return/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/100" | jq

Performance Optimization Proposal: 5ms Gas Price API

Goal

Transform gas price endpoint to achieve <5ms response times for production-ready, high-frequency applications.

Current vs Proposed Performance

Scenario Current Proposed Improvement
Cache Hit 10-30ms 0.1-2ms 15x faster
Cache Miss 200-500ms 0.1-2ms* 200x faster
P95 Response 50ms <5ms 10x faster

*After initial warmup

Key Technical Improvements

1. Multi-Layer Caching

Memory Cache (0.1ms) → Redis Cache (2-5ms) → Blockchain RPC (200ms+)

2. Stale-While-Revalidate

  • Return cached data instantly
  • Refresh in background
  • Zero user-facing cache misses

3. Cache Warming

  • Background refresh every 10s
  • Cache always ready on startup
  • Eliminates cold start delays

4. Performance Monitoring

  • Track response times per request
  • Monitor cache hit ratios
  • Alert on performance degradation

Implementation Plan

Phase 1: Enhanced Cache Layer

  • Add in-memory caching to existing CacheService
  • Implement LRU eviction and stale-while-revalidate

Phase 2: Background Refresh Service

  • Create GasPriceCacheService with active warming

Phase 3: Monitoring & Optimization

  • Performance middleware and metrics
  • Production configuration tuning

Current Architecture Analysis

Strengths

  • Clean modular architecture with SoC
  • Redis integration for gas price caching with TTL management
  • Global exception filter and logging interceptor
  • Class-validator integration with transformation
  • Containerized with non-root user security
  • Unit tests for core services

Architectural Decisions

1. Caching

Current Decision: Simple Redis caching with 30s TTL for gas prices

Why: Reduces blockchain RPC calls and improves response times

Limitation: Basic caching without cache warming or invalidation strategies

2. Blockchain

Current Decision: Single provider (Alchemy) with simple connection

Why: Simple setup and reliable service

Limitation: No failover, rate limiting, or connection pooling

3. Configuration

Current Decision: Environment variables with basic defaults

Why: Standard 12-factor app approach

Limitation: No validation, secrets management, or environment-specific configs

4. Error Handling

Current Decision: Global exception filter with basic logging

Why: Centralized error handling and consistent API responses

Limitation: No structured logging, error tracking, or alerting

Production-Ready Improvements

1. Better configuration

  • Environment-specific configuration files
  • Secrets management
  • Configuration validation on startup
  • Rate limiting configuration per environment

2. Resilient Blockchain

  • Multiple RPC provider endpoints
  • Circuit breaker pattern for failed providers
  • Connection pooling/retry mechanisms
  • Provider health monitoring

3. Caching Strategy

  • Cache warming to prevent cold cache hits
  • Multi-level caching (memory + Redis)
  • Cache metrics and monitoring

4. Monitoring

  • Structured logging with request IDs
  • Health checks with dependency status
  • APM integration for request tracing
  • Error tracking (Sentry)

5. API Security/Rate Limiting

  • API rate limiting per endpoint/user
  • Request/response validation with validation library
  • API key authentication
  • Request size limits

6. Data Persistence

  • Database for analytics and historical data

7. Testing

  • Integration tests
  • Load testing with realistic traffic
  • End-to-end testing pipeline

8. Infrastructure

  • Kubernetes deployment with HPA
  • Multi-environment deployment pipeline

About

Fast Ethereum gas price and UniswapV2 swap calculation API built with Nest.js

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors