kirapay-axelar-sdk
Version:
TypeScript SDK for cross-chain swaps with CCIP and Axelar bridges
504 lines (399 loc) • 12.3 kB
Markdown
# KiraPay Axelar SDK
A comprehensive TypeScript SDK for cross-chain token swaps and bridging using Axelar Network and Chainlink CCIP protocols.
## Installation
```bash
npm install kirapay-axelar-sdk
```
## Features
- 🌉 **Multi-Protocol Bridge Support**: Axelar Network and Chainlink CCIP
- 🔄 **Cross-Chain Token Swaps**: Seamless token swaps across 15+ supported chains
- ⛽ **Gas Estimation**: Accurate gas cost calculations for cross-chain transactions
- 📊 **Transaction Tracking**: Real-time status tracking for cross-chain messages
- 🎯 **Route Optimization**: Smart routing for optimal swap paths
- 💰 **Fee Calculation**: Transparent bridge fee estimation
- 🔒 **Type Safety**: Full TypeScript support with comprehensive type definitions
## Supported Chains
The SDK supports the following blockchain networks:
- **Ethereum** (Chain ID: 1)
- **Optimism** (Chain ID: 10)
- **Polygon** (Chain ID: 137)
- **Arbitrum** (Chain ID: 42161)
- **Base** (Chain ID: 8453)
- **Avalanche** (Chain ID: 43114)
- **BNB Smart Chain** (Chain ID: 56)
- **Linea** (Chain ID: 59144)
- **Celo** (Chain ID: 42220)
- **zkSync Era** (Chain ID: 324)
- **Zora** (Chain ID: 7777777)
- **Blast** (Chain ID: 81457)
- **Scroll** (Chain ID: 534352)
- **Polygon zkEVM** (Chain ID: 1101)
- **Mantle** (Chain ID: 5000)
## Quick Start
```typescript
import { KiraSdk } from 'kirapay-axelar-sdk';
// Initialize the SDK
const sdk = new KiraSdk({
// Optional: Custom RPC endpoints
rpcs: {
1: 'https://your-ethereum-rpc.com',
137: 'https://your-polygon-rpc.com'
}
});
// Get a route quote for cross-chain swap
const route = await sdk.getRoute({
srcChainId: 1, // Ethereum
dstChainId: 137, // Polygon
tokenIn: {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
symbol: 'USDC',
decimals: 6,
chainId: 1
},
tokenOut: {
address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',
symbol: 'USDC',
decimals: 6,
chainId: 137
},
amountIn: BigInt('1000000'), // 1 USDC
recipient: '0x742d35Cc6634C0532925a3b8D0C9e3e0C8b0e9e1',
maxSlippageBps: 50, // 0.5% slippage
preferredBridge: 'AXELAR'
});
// Build the transaction
const preparedTx = await sdk.build(route);
// Execute the transaction
const txHash = await wallet.sendTransaction({
to: preparedTx.to,
data: preparedTx.data,
value: preparedTx.value
});
// Track transaction status
const tracker = sdk.trackTransaction(txHash, 1, 137, {
onUpdate: (status) => {
console.log('Transaction status:', status.status);
console.log('Confirmations:', status.confirmations);
}
});
```
## API Reference
### KiraSdk
The main SDK class providing all cross-chain functionality.
#### Constructor
```typescript
const sdk = new KiraSdk(config?: KiraSdkConfig)
```
**Config Options:**
- `rpcs`: Custom RPC endpoints for each chain
- `ccip`: Custom CCIP router configurations
- `axelar`: Custom Axelar gateway configurations
- `defaultTtlSeconds`: Default time-to-live for quotes (default: 1800)
- `defaultSwapDeadlineSeconds`: Default swap deadline (default: 1800)
#### Core Methods
##### `getRoute(params: QuoteInput): Promise<RouteQuote>`
Get an optimal route for cross-chain token swap.
**Parameters:**
- `srcChainId`: Source chain ID
- `dstChainId`: Destination chain ID
- `tokenIn`: Input token details
- `tokenOut`: Output token details
- `amountIn`: Input amount (in token's smallest unit)
- `recipient`: Recipient address
- `maxSlippageBps`: Maximum slippage in basis points
- `preferredBridge`: Preferred bridge protocol ('AXELAR' or 'CCIP')
- `ttlSeconds`: Quote validity period (optional)
##### `build(route: RouteQuote): Promise<PreparedTx>`
Build a transaction from a route quote.
**Returns:**
- `to`: Contract address to send transaction to
- `data`: Encoded transaction data
- `value`: ETH value to send
- `metadata`: Additional transaction metadata
##### `estimateGas(route: RouteQuote): Promise<GasEstimationResult>`
Estimate gas costs for a cross-chain transaction.
**Returns:**
- `sourceChain`: Gas estimation for source chain operations
- `bridge`: Bridge fee information
- `total`: Total cost breakdown in USD
#### Bridge Contract Methods
##### `getBridgeContract(chainId: number, bridge: Bridge): Address`
Get the bridge contract address for a specific chain and protocol.
#### Transaction Tracking
##### `trackTransaction(txHash, srcChainId, dstChainId?, options?)`
Track the status of a cross-chain transaction.
**Options:**
- `pollInterval`: Polling interval in milliseconds (default: 5000)
- `confirmations`: Required confirmations (default: 1)
- `timeout`: Tracking timeout in milliseconds
- `onUpdate`: Callback for status updates
**Returns:**
- `stopTracking()`: Stop tracking the transaction
- `getStatus()`: Get current transaction status
##### `trackCrossChainMessage(messageId, srcChainId, dstChainId, bridge, options?)`
Track a specific cross-chain message by ID.
## Types
### Core Types
```typescript
type Token = {
address: Address;
chainId: ChainId;
decimals: number;
symbol: string;
};
type Bridge = "CCIP" | "AXELAR";
type TransactionStatus =
| 'pending'
| 'confirmed'
| 'delivering'
| 'delivered'
| 'failed'
| 'rejected';
```
### Route and Quote Types
```typescript
type RouteQuote = {
srcDex: DexLeg;
dstDexGasEstimate?: bigint;
dstDex?: DexLeg;
bridgeAsset: Token;
bridgeContract: { srcContract: Address; dstContract: Address };
};
type DexLeg = {
gasEstimate: bigint;
kind: "V4" | "V3" | "V2";
path: Address[];
feeTiers?: number[];
amountIn: bigint;
minAmountOut: bigint;
poolParams: PoolParams[];
};
```
## Error Handling
The SDK includes custom error types for better error handling:
```typescript
try {
const route = await sdk.getRoute(params);
} catch (error) {
if (error instanceof RouteNotFoundError) {
console.log('No route found for', error.leg, 'leg');
console.log('Context:', error.context);
}
}
```
## Examples
### Cross-Chain USDC Transfer
```typescript
const route = await sdk.getRoute({
srcChainId: 1, // Ethereum
dstChainId: 42161, // Arbitrum
tokenIn: {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
symbol: 'USDC',
decimals: 6,
chainId: 1
},
tokenOut: {
address: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',
symbol: 'USDC',
decimals: 6,
chainId: 42161
},
amountIn: BigInt('100000000'), // 100 USDC
recipient: '0x742d35Cc6634C0532925a3b8D0C9e3e0C8b0e9e1',
maxSlippageBps: 30,
preferredBridge: 'CCIP'
});
```
### ETH to USDC Cross-Chain Swap
```typescript
const route = await sdk.getRoute({
srcChainId: 1, // Ethereum
dstChainId: 137, // Polygon
tokenIn: {
address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH
symbol: 'WETH',
decimals: 18,
chainId: 1
},
tokenOut: {
address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', // USDC
symbol: 'USDC',
decimals: 6,
chainId: 137
},
amountIn: BigInt('1000000000000000000'), // 1 ETH
recipient: '0x742d35Cc6634C0532925a3b8D0C9e3e0C8b0e9e1',
maxSlippageBps: 100, // 1% slippage
preferredBridge: 'AXELAR'
});
```
## Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
## Supported Chains
The SDK includes built-in support for the following chains:
- Ethereum (Mainnet)
- Optimism
- Polygon
- Arbitrum
- Base
- Avalanche
- BSC (BNB Chain)
- Linea
- Celo
- zkSync Era
- Zora
- Blast
- Scroll
- Polygon zkEVM
- Mantle
## Basic Usage
```typescript
import { KiraSdk } from "kirapay-axelar-sdk";
// Create SDK instance with minimal config (built-in RPCs)
const sdk = new KiraSdk();
// Or with custom RPC providers
const sdkWithCustomRpcs = new KiraSdk({
rpcs: {
42161: "https://arbitrum-one.publicnode.com",
8453: "https://base.publicnode.com",
},
// other optional config
});
// Get a cross-chain swap quote
const quote = await sdk.getRoute({
srcChainId: 42161, // Arbitrum
dstChainId: 8453, // Base
tokenIn: {
address: "0x912CE59144191C1204E64559FE8253a0e49E6548", // ARB on Arbitrum
symbol: "ARB",
decimals: 18,
chainId: 42161,
},
tokenOut: {
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
symbol: "USDC",
decimals: 6,
chainId: 8453,
},
sender: "0xUserWalletAddress",
recipient: "0xUserWalletAddress", // or a destination contract
amountIn: 1000000000000000000n, // 1 ARB
maxSlippageBps: 50, // 0.5%
ttlSeconds: 1800, // 30 min
});
// Build full transaction details
const txDetails = await sdk.build({
/* same params as getRoute */
});
// Execute approvals if needed
for (const approval of txDetails.approvals) {
const tx = await wallet.sendTransaction(approval);
await tx.wait();
}
// Submit cross-chain swap
const tx = await wallet.sendTransaction(txDetails.submit);
```
## Advanced Features
### Gas Estimation
```typescript
// Estimate gas fees
const gasFees = await sdk.estimateTotalGasFees({
// Same parameters as getRoute
});
console.log(`Total estimated cost in USD: $${gasFees.total.totalUsd}`);
```
### Optimal Bridge Route Calculation
```typescript
// Calculate optimal bridging route
const optimalRoute = await sdk.calculateOptimalBridgingRoute({
srcChainId: 1,
dstChainId: 42161,
tokenIn: {
/* token details */
},
tokenOut: {
/* token details */
},
amountIn: 1000000000000000000n,
});
console.log(`Best bridge to use: ${optimalRoute.optimalBridge}`);
console.log(`Estimated cost: $${optimalRoute.totalCostUsd}`);
```
### Transaction Tracking
```typescript
// Track a transaction
const tracker = sdk.trackTransaction(
"0x...", // txHash
1, // srcChainId
42161, // dstChainId
{
onUpdate: (status) => {
console.log(`Transaction status: ${status.status}`);
},
}
);
// Later, when you're done tracking
tracker.stopTracking();
```
## Advanced Usage with Services
The SDK provides access to individual services for more granular control:
```typescript
import {
ConfigManager,
BridgeService,
DexService,
GasService,
} from "kirapay-axelar-sdk";
// Create a config manager
const configManager = new ConfigManager({
// Configuration options
});
// Create services directly
const bridgeService = new BridgeService(configManager);
const dexService = new DexService(configManager);
const gasService = new GasService(configManager);
// Use services directly
const fee = await bridgeService.estimateFee(
{
// Fee parameters
},
"CCIP"
);
```
## SDK Requirements
The SDK provides the following core capabilities:
### Core Functions
- Calculate optimal bridging route
- Estimate total gas fees across chains
- Build transaction data for contracts
- Provide transaction status tracking
### Gas Estimation
- Estimate source chain transaction gas
- Estimate destination chain transaction gas
- Estimate swap gas fees if required
- Calculate total fees in USD equivalent
## Dependencies
- `viem` for RPC interactions
- `@uniswap/sdk-core` and `@uniswap/v3-sdk` for Uniswap V3 integration
## Development
```bash
# Install dependencies
pnpm install
# Run tests
pnpm test
```
## Future Improvements
The SDK has been recently refactored with a cleaner architecture, removing backward compatibility constraints. Future improvements include:
1. **Build System Refinement**: The current build system needs refinement to ensure proper ES module compatibility and smooth development experience.
2. **Comprehensive Tests**: Adding comprehensive tests for each module to ensure reliability.
3. **API Documentation**: Generate detailed API documentation using TypeDoc or similar tool.
4. **Performance Optimizations**: Further optimize gas estimation and routing algorithms.
## Key Benefits of the Refactored Architecture
1. **Better Separation of Concerns**: Each service is responsible for a specific domain.
2. **Enhanced Maintainability**: Modular architecture makes it easier to maintain and extend.
3. **Improved Testability**: Services can be tested independently.
4. **Clearer Interfaces**: Well-defined interfaces make it easier to understand the API.
5. **Future-Proof**: The architecture can easily accommodate new features and integrations.
## License
MIT