Skip to content

Instantly share code, notes, and snippets.

@sarvagnakadiya
Created April 10, 2025 20:16
Show Gist options
  • Save sarvagnakadiya/1f213d0b61abee0f9024c8132a90d96b to your computer and use it in GitHub Desktop.
Save sarvagnakadiya/1f213d0b61abee0f9024c8132a90d96b to your computer and use it in GitHub Desktop.
getting swap data next api
import {
AlphaRouter,
SwapOptionsSwapRouter02,
SwapType,
} from '@uniswap/smart-order-router';
import {
TradeType,
CurrencyAmount,
Percent,
Token,
ChainId,
Ether,
} from '@uniswap/sdk-core';
import * as ethers from 'ethers';
import { NextResponse } from 'next/server';
import JSBI from 'jsbi';
import { BaseProvider } from '@ethersproject/providers';
// Types
interface SwapRequest {
userAddress: string;
tokenInAddress: string;
tokenOutAddress: string;
amount: string | number;
decimalsIn: number;
}
interface SwapResponse {
quote: string;
methodParameters?: {
calldata: string;
value: string;
};
gasEstimate: string;
gasPriceWei: string;
feeTier: string;
}
// Constants
const SLIPPAGE_TOLERANCE = new Percent(50, 10_000); // 0.5%
const SWAP_DEADLINE_MINUTES = 30;
// Utility functions
function countDecimals(amount: number): number {
if (Math.floor(amount) === amount) return 0;
return amount.toString().split('.')[1]?.length || 0;
}
function fromReadableAmount(amount: number | string, decimals: number): JSBI {
const amountNum = typeof amount === 'string' ? parseFloat(amount) : amount;
const extraDigits = Math.pow(10, countDecimals(amountNum));
const adjustedAmount = amountNum * extraDigits;
return JSBI.divide(
JSBI.multiply(
JSBI.BigInt(Math.floor(adjustedAmount)),
JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(decimals)),
),
JSBI.BigInt(extraDigits),
);
}
function getMainnetProvider(): BaseProvider {
const ALCHEMY_URL =
process.env.ALCHEMY_URL ||
'https://base-mainnet.g.alchemy.com/v2/9-2O3J1H0d0Z-xDdDwZHHCBM2mwzVMwT';
return new ethers.providers.JsonRpcProvider(
{
url: ALCHEMY_URL,
skipFetchSetup: true,
},
{
name: 'base',
chainId: 8453,
},
);
}
function getSwapOptions(recipient: string): SwapOptionsSwapRouter02 {
return {
recipient,
slippageTolerance: SLIPPAGE_TOLERANCE,
deadline: Math.floor(Date.now() / 1000 + SWAP_DEADLINE_MINUTES * 60),
type: SwapType.SWAP_ROUTER_02,
};
}
// Main API handler
export async function POST(request: Request) {
try {
const {
userAddress,
tokenInAddress,
tokenOutAddress,
amount,
decimalsIn,
}: SwapRequest = await request.json();
// Validate input parameters
if (
!userAddress ||
!tokenInAddress ||
!tokenOutAddress ||
!amount ||
!decimalsIn
) {
return NextResponse.json(
{ error: 'Missing required parameters' },
{ status: 400 },
);
}
// Initialize provider and router
const provider = getMainnetProvider();
await provider.ready;
const router = new AlphaRouter({
chainId: ChainId.BASE,
provider: provider,
});
// Create token objects
const tokenIn = new Token(ChainId.BASE, tokenInAddress, decimalsIn, '', '');
const tokenOut = new Token(ChainId.BASE, tokenOutAddress, 18, '', '');
// Prepare swap parameters
const amountIn = CurrencyAmount.fromRawAmount(
tokenIn,
fromReadableAmount(amount, decimalsIn).toString(),
);
const options = getSwapOptions(userAddress);
// Get route
const route = await router.route(
amountIn,
Ether.onChain(ChainId.BASE),
TradeType.EXACT_INPUT,
options,
);
if (!route) {
return NextResponse.json({ error: 'No route found' }, { status: 404 });
}
// Extract fee tier from the route
// const feeTier = route.route[0].fee.toString();
const feeTier = '10000';
// Prepare response
const response: SwapResponse = {
quote: route.quote.toFixed(6),
methodParameters: route.methodParameters,
gasEstimate: route.estimatedGasUsed.toString(),
gasPriceWei: route.gasPriceWei.toString(),
feeTier: `${parseInt(feeTier) / 10000}%`, // Convert fee tier to percentage
};
return NextResponse.json(response);
} catch (error) {
console.error('API error:', error);
return NextResponse.json(
{
error: 'Error processing swap request',
details: error instanceof Error ? error.message : String(error),
},
{ status: 500 },
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment