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

@unifi-io/kyberswap-sdk

v0.0.2

Published

TypeScript SDK for KyberSwap Aggregator API - Find optimal swap routes across 100+ DEXs on 16+ EVM chains

Downloads

25

Readme

KyberSwap Node SDK

npm version License: MIT

A TypeScript/JavaScript SDK for interacting with KyberSwap Aggregator API to find optimal swap routes across multiple DEXs and liquidity sources.

Features

  • 🔍 Route Finding - Find optimal swap routes across 100+ DEXs and liquidity sources
  • 🔨 Transaction Building - Generate ready-to-send transaction data
  • 🌐 Multi-Chain Support - Support for 16+ EVM-compatible chains
  • 📝 Full TypeScript Support - Complete type definitions included
  • Native Fetch API - Zero dependencies on external HTTP clients
  • 🛡️ Built-in Error Handling - Descriptive error messages

Supported Chains

| Chain | Chain ID | Network Name | |-------|----------|--------------| | Ethereum | 1 | ethereum | | BSC | 56 | bsc | | Polygon | 137 | polygon | | Arbitrum | 42161 | arbitrum | | Optimism | 10 | optimism | | Avalanche | 43114 | avalanche | | Base | 8453 | base | | Linea | 59144 | linea | | Mantle | 5000 | mantle | | Sonic | 146 | sonic | | Berachain | 80094 | berachain | | Ronin | 2020 | ronin | | Unichain | 130 | unichain | | HyperEVM | 999 | hyperevm | | Plasma | 9745 | plasma | | Etherlink | 42793 | etherlink |

Installation

npm install @unifi-io/kyberswap-sdk
# or
yarn add @unifi-io/kyberswap-sdk

Quick Start

import { KyberswapSDK } from '@unifi-io/kyberswap-sdk'

// Initialize SDK with your app name
const sdk = new KyberswapSDK('my-awesome-dapp')

// Get optimal swap route
const route = await sdk.getRoute({
  chain: 'polygon',
  tokenIn: '0x7ceb23fd6bc0add59e62ac25578270cff1b9f619',  // WETH
  tokenOut: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174', // USDC
  amountIn: '1000000000000000000', // 1 WETH
  gasInclude: true,
})

// Build transaction
const txData = await sdk.buildRoute({
  chain: 'polygon',
  routeSummary: route.data.routeSummary,
  sender: '0xYourAddress',
  recipient: '0xYourAddress',
  slippageTolerance: 50, // 0.5%
})

// Send transaction with ethers.js
const tx = await wallet.sendTransaction({
  to: txData.data.routerAddress,
  data: txData.data.data,
  value: txData.data.amountIn,
})

API Reference

Constructor

new KyberswapSDK(clientId?: string, apiBaseUrl?: string)

Parameters:

  • clientId (optional) - Your application identifier (recommended to use app name)
  • apiBaseUrl (optional) - Custom API base URL (default: https://aggregator-api.kyberswap.com)

Example:

const sdk = new KyberswapSDK('my-dapp')

Instance Methods

getRoute(params: GetRouteParams): Promise<GetRouteResponse>

Find the best swap route supporting all liquidity sources including RFQ.

Parameters:

interface GetRouteParams {
  chain: ChainName                          // Target chain
  tokenIn: string                           // Input token address
  tokenOut: string                          // Output token address
  amountIn: string                          // Input amount (in token's smallest unit)
  saveGas?: boolean                         // Optimize for gas savings
  gasInclude?: boolean                      // Include gas in route calculation
  gasPrice?: string                         // Custom gas price
  isInBps?: boolean                         // Fee amount in basis points
  chargeFeeBy?: 'currency_in' | 'currency_out'  // Fee charging method
  feeAmount?: string                        // Fee amount
  feeReceiver?: string                      // Fee receiver address
  source?: string                           // Referral source
}

Returns:

interface GetRouteResponse {
  code: number
  message: string
  data: {
    routeSummary: RouteSummary
    routerAddress: string
    tokens: Record<string, TokenInfo>
  }
  requestId: string
}

Example:

const route = await sdk.getRoute({
  chain: 'polygon',
  tokenIn: '0x7ceb23fd6bc0add59e62ac25578270cff1b9f619',
  tokenOut: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',
  amountIn: '1000000000000000000',
  gasInclude: true,
})

console.log('Expected output:', route.data.routeSummary.amountOut)

buildRoute(params: BuildRouteParams): Promise<BuildRouteResponse>

Build swap transaction data for submission to the KyberSwap router contract.

Parameters:

interface BuildRouteParams {
  chain: ChainName              // Target chain
  routeSummary: RouteSummary    // Route summary from getRoute
  sender: string                // Sender address
  recipient: string             // Recipient address
  slippageTolerance?: number    // Slippage tolerance in basis points (50 = 0.5%)
  deadline?: number             // Transaction deadline timestamp
  permit?: string               // Permit signature for gasless approval
  source?: string               // Referral source
  skipSimulateTx?: boolean      // Skip transaction simulation
}

Returns:

interface BuildRouteResponse {
  code: number
  message: string
  data: {
    amountIn: string      // Input amount
    amountOut: string     // Output amount
    gas: string           // Estimated gas
    gasPrice: string      // Gas price
    data: string          // Encoded transaction data
    routerAddress: string // Router contract address
  }
  requestId: string
}

Example:

const txData = await sdk.buildRoute({
  chain: 'polygon',
  routeSummary: route.data.routeSummary,
  sender: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  slippageTolerance: 50,
  deadline: Math.floor(Date.now() / 1000) + 1200, // 20 minutes
})

Static Methods

getSupportedChains(): ChainInfo[]

Get all supported chains information.

Returns:

interface ChainInfo {
  name: ChainName
  chainId: number
}

Example:

const chains = KyberswapSDK.getSupportedChains()
console.log(chains)
// [
//   { name: 'ethereum', chainId: 1 },
//   { name: 'polygon', chainId: 137 },
//   ...
// ]

getChainId(chainName: ChainName): number

Get chain ID by chain name.

Example:

const chainId = KyberswapSDK.getChainId('polygon') // 137

getChainName(chainId: number): ChainName | undefined

Get chain name by chain ID.

Example:

const chainName = KyberswapSDK.getChainName(137) // 'polygon'

getChainInfo(chainName: ChainName): ChainInfo | undefined

Get chain information by chain name.

Example:

const info = KyberswapSDK.getChainInfo('polygon')
// { name: 'polygon', chainId: 137 }

getChainInfoById(chainId: number): ChainInfo | undefined

Get chain information by chain ID.

Example:

const info = KyberswapSDK.getChainInfoById(137)
// { name: 'polygon', chainId: 137 }

isChainSupported(chainName: string): boolean

Check if a chain is supported.

Example:

KyberswapSDK.isChainSupported('polygon') // true
KyberswapSDK.isChainSupported('bitcoin') // false

isChainIdSupported(chainId: number): boolean

Check if a chain ID is supported.

Example:

KyberswapSDK.isChainIdSupported(137) // true
KyberswapSDK.isChainIdSupported(999999) // false

Complete Example

import { KyberswapSDK } from '@unifi-io/kyberswap-sdk'
import { ethers } from 'ethers'

async function executeSwap() {
  // Initialize SDK
  const sdk = new KyberswapSDK('my-dapp')
  
  // Setup wallet
  const provider = new ethers.JsonRpcProvider('https://polygon-rpc.com')
  const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider)
  
  try {
    // Step 1: Get optimal route
    console.log('Finding optimal route...')
    const routeResponse = await sdk.getRoute({
      chain: 'polygon',
      tokenIn: '0x7ceb23fd6bc0add59e62ac25578270cff1b9f619',  // WETH
      tokenOut: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174', // USDC
      amountIn: '1000000000000000000', // 1 WETH
      gasInclude: true,
    })
    
    console.log('Expected output:', routeResponse.data.routeSummary.amountOut)
    
    // Step 2: Build transaction
    console.log('Building transaction...')
    const buildResponse = await sdk.buildRoute({
      chain: 'polygon',
      routeSummary: routeResponse.data.routeSummary,
      sender: wallet.address,
      recipient: wallet.address,
      slippageTolerance: 50, // 0.5%
      deadline: Math.floor(Date.now() / 1000) + 1200, // 20 minutes
    })
    
    // Step 3: Send transaction
    console.log('Sending transaction...')
    const tx = await wallet.sendTransaction({
      to: buildResponse.data.routerAddress,
      data: buildResponse.data.data,
      value: buildResponse.data.amountIn,
    })
    
    console.log('Transaction hash:', tx.hash)
    
    // Wait for confirmation
    const receipt = await tx.wait()
    console.log('Transaction confirmed in block:', receipt.blockNumber)
    
  } catch (error) {
    console.error('Swap failed:', error.message)
  }
}

executeSwap()

Constants

The SDK exports useful constants:

import { CHAIN_ID_MAP, CHAIN_NAME_MAP, SUPPORTED_CHAINS } from '@unifi-io/kyberswap-sdk'

// Map chain names to IDs
console.log(CHAIN_ID_MAP.polygon) // 137

// Map IDs to chain names
console.log(CHAIN_NAME_MAP[137]) // 'polygon'

// All supported chains
console.log(SUPPORTED_CHAINS)

Important Notes

Rate Limiting

KyberSwap API applies stricter rate limits if no clientId is provided. Always initialize the SDK with your application name:

const sdk = new KyberswapSDK('my-awesome-dapp')

Route Freshness

Routes are real-time and market conditions change constantly. Best practices:

  • Don't cache routes for more than 5-10 seconds
  • Refetch a new route before swapping if too much time has passed
  • Always use appropriate slippage tolerance

Slippage Tolerance

The slippageTolerance parameter is in basis points:

  • 10 = 0.1%
  • 50 = 0.5%
  • 100 = 1%
  • 500 = 5%

Token Approval

For ERC20 token swaps, you must approve the router contract before swapping:

import { ethers } from 'ethers'

const ERC20_ABI = ['function approve(address spender, uint256 amount) returns (bool)']
const tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, wallet)

// Approve router to spend tokens
await tokenContract.approve(buildResponse.data.routerAddress, amountIn)

Address Format

All addresses must be valid Ethereum addresses with proper checksum formatting. Use ethers.getAddress() to ensure proper formatting:

import { ethers } from 'ethers'

const sender = ethers.getAddress(userAddress)

Error Handling

The SDK throws descriptive errors:

try {
  const route = await sdk.getRoute({...})
} catch (error) {
  if (error.message.includes('insufficient liquidity')) {
    console.error('Not enough liquidity for this trade')
  } else if (error.message.includes('invalid token')) {
    console.error('Token address is invalid')
  } else {
    console.error('Swap failed:', error.message)
  }
}

TypeScript Support

This package includes full TypeScript type definitions. All types are exported:

import type {
  ChainName,
  ChainInfo,
  GetRouteParams,
  GetRouteResponse,
  BuildRouteParams,
  BuildRouteResponse,
  RouteSummary,
  TokenInfo,
} from '@unifi-io/kyberswap-sdk'

Testing

# Run tests
yarn test

# Run tests in watch mode
yarn test:watch

# Run tests with UI
yarn test:ui

Building

# Build the package
yarn build

# Development mode with watch
yarn dev

Documentation

For more details about the KyberSwap Aggregator API, visit:

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see the LICENSE file for details.

Support

Changelog

v0.0.1

  • Initial release
  • Support for KyberSwap Aggregator API v1
  • Multi-chain support (16+ chains)
  • Complete TypeScript support
  • Static helper methods for chain information