@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
Maintainers
Readme
KyberSwap Node SDK
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-sdkQuick 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') // 137getChainName(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') // falseisChainIdSupported(chainId: number): boolean
Check if a chain ID is supported.
Example:
KyberswapSDK.isChainIdSupported(137) // true
KyberswapSDK.isChainIdSupported(999999) // falseComplete 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:uiBuilding
# Build the package
yarn build
# Development mode with watch
yarn devDocumentation
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
- GitHub Issues: https://github.com/unifi-io/kyberswap-node-sdk/issues
- KyberSwap Discord: https://discord.com/invite/NB3vc8J9uv
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
