Skip to navigation

DEX Aggregator API

The HyperFlow DEX Aggregator API gives you the same routing engine that powers hyperflow.fun: quote the best route across the liquidity sources of each supported chain, then execute through the HyperFlow router contract. Wallets and apps can also charge their own fee on top of each swap — see Integrator fee.

Supported chains

Each chain has its own base URL. The endpoints, parameters and responses are identical; only the base URL changes.

ChainChain IDBase URL
HyperEVM999https://ag-api.hyperflow.fun/v1/hyperevm
Elysium99901https://ag-api.hyperflow.fun/v1/elysium

All endpoints serve mainnet only; there is no public testnet environment.

Elysium is an L2 on HyperEVM with HYPE as its gas token. Public RPC: https://rpc.elysium.kinetiq.xyz. Explorer: elysium.kinetiq.xyz.

List liquidity sources

GET /exchanges

Returns the DEX ids available on that chain, for use in exchanges and excludedExchanges:

["hyperswapv2", "hyperswapv3", "kittenswapv3", "prjxv3", "curvestableng", "..."]

Authentication & rate limits

Requests can be authenticated with an API key passed in the x-api-key header:

AccessRate limit
Without API key10 requests/second
With API key25 requests/second

The limit applies to /quote and /swap. To obtain an API key, or if your bot, solver or vault needs more than 25 requests/second, reach out to the HyperFlow team on Discord.

Keep your API key on your backend. A key shipped in a web or mobile app can be read by anyone and used against your rate limit.

When you hit the limit

Requests over the limit return HTTP 429 with:

{"error": "rate limit exceeded"}

The response does not say when to retry. Back off and retry with an increasing delay plus random jitter (for example 250 ms, 500 ms, 1 s, …), and avoid retrying in a tight loop.

Get a quote

GET /quote

Retrieves the optimal trading route and price quote between two tokens.

Parameters

ParameterRequiredDescription
tokenInYesInput token address
tokenOutYesOutput token address
amountInYesInput amount, in wei
exchangesNoComma-separated DEX ids to restrict routing; blank routes across all available sources
excludedExchangesNoComma-separated DEX ids to leave out of routing
excludedPoolsNoComma-separated pool addresses to leave out of routing
slippageNoMaximum acceptable slippage as a fraction, above 0 and at most 0.5 (e.g. 0.005 = 0.5%), used for minAmountOut. Defaults to 0.01; a value outside that range is ignored and the default applies
gasPriceNoCustom gas price, in wei
feeBpsNoIntegrator fee in basis points (1 bps = 0.01%), integer, maximum 100 (1%)
feeReceiverNoAddress that receives the integrator fee. Required on /swap when feeBps > 0
feeByNoToken the integrator fee is taken in. Only out (the output token, default) is supported today

Response

FieldDescription
tokenIn / tokenOutToken addresses of the quoted pair
amountIn / amountInUsdInput amount in wei / USD
amountOut / amountOutUsdOutput amount the receiver gets, in wei / USD — net of any integrator fee
minAmountOutOutput floor after slippage, in wei — net of any integrator fee
priceImpactPercentEstimated price impact of the route
totalGas / totalGasUsdEstimated gas for the route
gasPriceGas price used for the estimate, in wei
splits[]Route splits — each with amountIn, amountOut, and the detailed swaps path (pool, exchange, type per hop)
integratorFeePresent only when feeBps is set: bps, by, token, amount (wei), amountUsd, and receiver when feeReceiver was passed
requestIdIdentifier of this quote

priceImpactPercent is in percent, excludes any integrator fee, and is negative when the route loses value.

Example: 1 WHYPE to USDC on HyperEVM, routed in two hops:

{
"tokenIn": "0x5555555555555555555555555555555555555555",
"tokenOut": "0xb88339CB7199b77E23DB6E890353E22632Ba630f",
"amountIn": "1000000000000000000",
"amountInUsd": 59.3139,
"amountOut": "59305455",
"amountOutUsd": 59.3055,
"priceImpactPercent": -0.0143,
"minAmountOut": "58712401",
"totalGas": 356000,
"totalGasUsd": 0.0021,
"gasPrice": "100000000",
"splits": [
{
"amountIn": "1000000000000000000",
"amountOut": "59305455",
"swaps": [
{
"tokenIn": "0x5555555555555555555555555555555555555555",
"tokenOut": "0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb",
"amountIn": "1000000000000000000",
"amountOut": "59379602",
"pool": "0xB9fA3BdfA88dA2dC78C20ca03472E043992C6671",
"exchange": "uscore",
"type": "uscore",
"timestamp": 1795587543
},
{
"tokenIn": "0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb",
"tokenOut": "0xb88339CB7199b77E23DB6E890353E22632Ba630f",
"amountIn": "59379602",
"amountOut": "59305455",
"pool": "0x7319aC5bB90164191bD236c16000fa3f1c29E456",
"exchange": "hybrafinancev4",
"type": "uniswapv3",
"timestamp": 1795587540
}
]
}
],
"requestId": "c6f7c6e5b5d2bdbbf0debae6f2d63e21"
}

Get swap data

GET /swap

Generates the transaction data needed to execute the swap through the router contract.

Parameters

All Quote parameters, plus:

ParameterRequiredDescription
receiverYesRecipient address for the output token
minAmountOutNoCustom minimum output, in wei, written into the transaction. Must not exceed the quoted output less slippage, otherwise 400
deadlineNoTransaction deadline in Unix seconds (default: now + 20 minutes; a time in the past is replaced by the default)
sourceNoYour partner code, for partner bonus points

Response

/swap wraps the quote:

{
"quote": { "...": "all /quote fields except requestId" },
"tx": {
"router": "0x…",
"data": "0xf970cf64…"
},
"requestId": "2b493058b2cf36f39de8d4c41589b9cc"
}

Approve tx.router for tokenIn (ERC-20 inputs), then send tx.data to tx.router — attaching value = amountIn for native-token input.

Always use the tx.router returned with each response; never hardcode it. Swaps with an integrator fee go through the integrator-fee router, swaps without one through the standard router (see Smart Contracts).

Integrator fee

Wallets, apps and bots can charge their own fee on swaps they route through HyperFlow. The fee is paid to your address in the same transaction as the swap — there is nothing to claim.

  • Set feeBps (maximum 100, i.e. 1%) and feeReceiver on /swap. On /quote, feeBps alone is enough to preview the fee.
  • The fee is taken from the output token, as a share of the routed output.
  • amountOut and minAmountOut are already net of the fee, so what your user sees and signs matches what they receive.
  • Without feeBps, swaps work exactly as before.

Example: feeBps=50 on a swap routing 5,869.81 USDC out:

{
"amountOut": "5840464572",
"minAmountOut": "5782059927",
"integratorFee": {
"bps": 50,
"by": "out",
"token": "0xb88339CB7199b77E23DB6E890353E22632Ba630f",
"amount": "29349068",
"amountUsd": 29.35,
"receiver": "0xYourFeeAddress"
}
}

Your user receives 5,840.46 USDC and 0xYourFeeAddress receives 29.35 USDC (0.5% of 5,869.81).

Code example

import {ethers} from 'ethers'; // ^6.13.4
import type {TransactionRequest} from 'ethers';
const routerApiUrl = 'https://ag-api.hyperflow.fun/v1/hyperevm'; // or https://ag-api.hyperflow.fun/v1/elysium
const rpcUrl = 'network-RPC'; // RPC of the same chain, e.g. https://rpc.elysium.kinetiq.xyz
const privateKey = 'your-private-key-here'; // Replace with your private key
const apiKey = process.env.HYPERFLOW_API_KEY; // Optional: raises the rate limit
const apiHeaders = apiKey ? {'x-api-key': apiKey} : undefined;
const wallet = new ethers.Wallet(privateKey);
const provider = new ethers.JsonRpcProvider(rpcUrl);
async function signAndSendTransaction(tx: TransactionRequest) {
const signer = wallet.connect(provider);
if (!tx.gasLimit) {
const estimatedGas = await signer.estimateGas(tx);
tx.gasLimit = estimatedGas * BigInt(120) / BigInt(100);
}
const txResponse = await signer.sendTransaction(tx);
console.log('Transaction Hash:', txResponse.hash);
const receipt = await txResponse.wait();
console.log('Transaction Mined:', receipt);
return receipt;
}
type Address = `0x${string}`;
export const EtherAddress = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
const erc20Abi = [
{
"constant": true,
"inputs": [{"name": "_owner", "type": "address"}, {"name": "_spender", "type": "address"}],
"name": "allowance",
"outputs": [{"name": "remaining", "type": "uint256"}],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}],
"name": "approve",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
];
async function approve(token: Address, spender: Address, amount: string | bigint) {
const contract = new ethers.Contract(token, erc20Abi, provider);
const allowance = await contract.allowance(wallet.address, spender);
if (allowance < BigInt(amount)) {
const data = contract.interface.encodeFunctionData('approve', [spender, amount]);
return signAndSendTransaction({to: token, data});
}
return Promise.resolve(true);
}
function serializeParameters(params: Record<string, any>) {
const searchParams = new URLSearchParams(
Object.fromEntries(Object.entries(params).filter(([_, v]) => v !== undefined && v !== null && v !== ''))
);
return searchParams.toString();
}
interface QuoteParameters {
tokenIn: Address;
tokenOut: Address;
amountIn: string | bigint;
exchanges?: string[];
slippage?: number;
feeBps?: number; // Optional integrator fee, max 100
}
// Retrieves the optimal trading route and price quote between two tokens
export async function quote(args: QuoteParameters) {
const params = {
...args,
amountIn: args.amountIn.toString(),
exchanges: args.exchanges?.join(','),
slippage: args.slippage?.toString(),
feeBps: args.feeBps?.toString(),
};
const quoteResponse = await fetch(`${routerApiUrl}/quote?${serializeParameters(params)}`, {headers: apiHeaders});
const quoteResult = await quoteResponse.json();
if (!quoteResponse.ok) throw new Error(quoteResult.error ?? JSON.stringify(quoteResult.errors));
return quoteResult;
}
interface SwapParameters extends QuoteParameters {
receiver?: Address;
feeReceiver?: Address; // Required when feeBps > 0
}
// Routers on the Smart Contracts page; check tx.router against this list before sending
const knownRouters = [
'0x980B9271A33c4B31214301fAE584B18dBB9731eC',
'0x0FbE14a7Cd24aDB08575d67bd39d2290A12126b0', // HyperEVM, integrator fee
'0x995E574059e1dD9528C22627773A397Bbb073A22', // Elysium, integrator fee
].map((a) => a.toLowerCase());
// Generates the transaction data needed to execute the swap through the router
async function buildSwap(args: SwapParameters) {
const params = {
...args,
amountIn: args.amountIn.toString(),
exchanges: args.exchanges?.join(','),
slippage: args.slippage?.toString(),
feeBps: args.feeBps?.toString(),
receiver: args.receiver || wallet.address,
};
const encodingResponse = await fetch(`${routerApiUrl}/swap?${serializeParameters(params)}`, {headers: apiHeaders});
const encodingResult = await encodingResponse.json();
if (!encodingResponse.ok) throw new Error(encodingResult.error ?? JSON.stringify(encodingResult.errors));
if (!knownRouters.includes(encodingResult.tx.router.toLowerCase())) {
throw new Error(`Unexpected router ${encodingResult.tx.router}`);
}
return encodingResult;
}
export async function swap(args: SwapParameters) {
const tokenInIsNative = args.tokenIn.toLowerCase() === EtherAddress.toLowerCase();
let encodingResult = await buildSwap(args);
if (!tokenInIsNative) {
await approve(args.tokenIn, encodingResult.tx.router, args.amountIn);
encodingResult = await buildSwap(args); // fresh route after the approval is mined
}
return await signAndSendTransaction({
to: encodingResult.tx.router,
value: tokenInIsNative ? args.amountIn : undefined,
data: encodingResult.tx.data,
});
}

Errors

Client errors return a 4xx status with the reason in the body; only faults on our side return 5xx. Most errors are {"error": "<message>"}; a malformed value returns {"errors": [{"field": "...", "message": "..."}]}.

ResponseMeaning
400 Bad request. Reason: …A parameter is invalid, e.g. feeReceiver is required, feeBps exceeds the maximum of 100, feeBy=in is not available on this chain yet, tokenIn and tokenOut are the same token
400 field-validation messageA required parameter is missing or malformed (e.g. receiver on /swap, non-numeric amountIn)
404 token not foundA token is not supported on this chain
404 no path foundNo route exists for the pair and amount
429 rate limit exceededOver the rate limit

Resources