Integrating Hypertrade into Your dApp: A Guide for Developers
Integrating Hypertrade into Your dApp: A Guide for Developers
Meta Title: Hypertrade API for Developers | Integrating a DEX Aggregator into a Hyperliquid dApp
Meta Description: A complete guide to integrating Hypertrade into your app: API documentation, code samples, SDKs, best practices. Add the best swap courses for Hyperliquid to your dApp in 30 minutes.
URL: https://hyper-trade.org/developer-integration-guide
Canonical: https://hyper-trade.org/developer-integration-guide
Introduction: Why integrate Hypertrade into your dApp?
If you're developing a decentralized application (dApp) on Hyperliquid — a DeFi protocol, wallet, portfolio tracker, NFT marketplace, or any other project — your users need the ability to swap tokens.
Problem: creating your own swap functionality:
- ❌ Requires integration of each DEX separately (Hyperswap, Kittenswap, HyperCore Spot, Prjx)
- ❌ Requires the development of a routing algorithm to find the best price
- ❌ Requires constant updating of contracts and APIs
- ❌ Takes weeks/months of development and testing
Solution: Integrate Hypertrade in 30-60 minutes:
- ✅ Access to all Hyperliquid DEXs through one API
- ✅ Automatic route optimization (split-routing, price comparison)
- ✅ Invisium Simulations - accurate quotes (99.5-99.9%)
- ✅ 0% platform fee - all savings go to your users
- ✅ Constant updates - we support integrations with new DEXs
- ✅ Easy integration — REST API, TypeScript/JavaScript SDK, React hooks
What you will get after the integration:
For users:
- Best exchange rates (save 0.5-5% on each swap)
- Minimum price impact (split-routing)
- Transparency (route details, result simulation)
- User-friendly UX (one click to swap)
For your dApp:
- Added value for users (swap without leaving the application)
- Optional: referral fees (share commissions with Hypertrade)
- Increase retention (users stay in your app)
- Saving development time (focus on core functionality)
Examples of integrations:
- DeFi Dashboard → built-in swap for portfolio rebalancing
- Wallet → a native token swap feature
- NFT Marketplace → convert ETH ⇄ USDC to buy NFTs
- Yield Optimizer → Automatic Token Swap for Farming Login
- Trading Bot → API for automated strategies
Quick start: integration in 30 minutes
Step 1: Install the SDK
For TypeScript/JavaScript projects:
npm install @hypertrade/sdk # or yarn add @hypertrade/sdk
For React applications:
npm install @hypertrade/sdk @hypertrade/react-hooks
For other languages:
- Python SDK – In Development (ETA Q1 2025)
- REST API – works with all languages (see below)
Step 2: Get API key (optional)
Public API (without registration):
- ✅ Accessible to everyone
- ✅ Rate limit: 100 requests/minute
- ✅ Suitable for most dApps
API key (with registration):
- ✅ Rate limit: 1000 requests/minute
- ✅ Priority processing of requests
- ✅ Access to the referral program
- ✅ Detailed usage analytics
Getting an API key:
- Switch to https://docs.hypertrade.io/api-keys
- Connect wallet (MetaMask)
- Fill out the form (dApp name, contacts, expected volume)
- Get API key and secret
Step 3: Basic Integration (React Example)
The simplest example is the built-in swap widget:
import { HypertradeSwapWidget } from '@hypertrade/react-hooks';
function MyApp() {
return (
<div>
<h1>My DeFi Dashboard</h1>
{/* Built-in swap widget */}
<HypertradeSwapWidget
defaultTokenIn="USDC"
defaultTokenOut="ETH"
theme="dark" // or "light"
onSwapSuccess={(result) => {
console.log('Swap completed:', result);
Update the user's balance, show notification, etc.
}}
/>
</div>
);
}
The result: a fully functional swap interface in 5 lines of code.
Step 4: UI Customization
If you want more control over the UI:
import { useHypertrade, useQuote, useSwap } from '@hypertrade/react-hooks';
import { useState } from 'react';
function CustomSwapInterface() {
const [tokenIn, setTokenIn] = useState('USDC');
const [tokenOut, setTokenOut] = useState('ETH');
const [amountIn, setAmountIn] = useState('1000');
Get a quote
const { data: quote, isLoading } = useQuote({
tokenIn,
tokenOut,
amountIn,
slippage: 1.0, // 1%
});
Execute swap
const { swap, isSwapping } = useSwap();
const handleSwap = async () => {
try {
const result = await swap({
tokenIn,
tokenOut,
amountIn,
quote: quote.route, // use the found route
});
console.log('Swap success:', result);
alert(`Received ${result.amountOut} ${tokenOut}`);
} catch (error) {
console.error('Swap failed:', error);
alert('Swap failed: ' + error.message);
}
};
return (
<div className="custom-swap">
<h2>Swap Tokens</h2>
{/* Input */}
<div>
<label>From:</label>
<input
type="number"
value={amountIn}
onChange={(e) => setAmountIn(e.target.value)}
/>
<select value={tokenIn} onChange={(e) => setTokenIn(e.target.value)}>
<option value="USDC">USDC</option>
<option value="ETH">ETH</option>
<option value="HYPE">HYPE</option>
</select>
</div>
{/* Output */}
<div>
<label>To (estimated):</label>
{isLoading ? (
<p>Loading quote... </p>
) : (
<p>{quote?. amountOut} {tokenOut}</p>
)}
</div>
{/* Details */}
{quote && (
<div className="quote-details">
<p>Price Impact: {quote.priceImpact}%</p>
<p>Min. Received: {quote.minAmountOut} {tokenOut}</p>
<p>Route: {quote.route.map(r => r.dex).join(' → ')}</p>
<p>You save: ${quote.savings} vs. single DEX</p>
</div>
)}
{/* Swap button */}
<button
onClick={handleSwap}
disabled={isSwapping || !quote}
>
{isSwapping ? 'Swapping...' : 'Swap'}
</button>
</div>
);
}
The result: full control over the UI when using the Hypertrade logic.
API Reference: Core endpoints
Base URL:
https://api.hypertrade.io/v1
All queries support:
- Content-Type: application/json
- Authorization: Bearer YOUR_API_KEY (optional, for increased rate limit)
1. GET /quote — get a quote
Description: Get the best route and expected result for swap.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| tokenIn | string | Yes | Contract address or symbol (e.g., "USDC" or "0x...") |
| tokenOut | string | Yes | Contract address or symbol |
| amountIn | string | Yes | Amount in smallest units (e.g. "1000000000" for 1000 USDC with 6 decimals) |
| slippage | number | No | Slippage tolerance % (default: 1.0) |
| userAddress | string | No | User address (for personalized routes) |
Example Request:
curl -X GET "https://api.hypertrade.io/v1/quote?tokenIn=USDC&tokenOut=ETH&amountIn=10000000000&slippage=1.0" \ -H "Authorization: Bearer YOUR_API_KEY"
Example Response:
{
"success": true,
"data": {
"tokenIn": "USDC",
"tokenOut": "ETH",
"amountIn": "10000000000",
"amountOut": "3986234000000000000",
"amountOutHuman": "3.986234",
"minAmountOut": "3946451660000000000",
"minAmountOutHuman": "3.946452",
"priceImpact": 0.51,
"slippage": 1.0,
"route": [
{
"dex": "HyperCore Spot",
"percentage": 60,
"amountIn": "6000000000",
"amountOut": "2391740400000000000",
"priceImpact": 0.25
},
{
"dex": "Hyperswap",
"percentage": 40,
"amountIn": "4000000000",
"amountOut": "1594493600000000000",
"priceImpact": 0.90
}
],
"gasCostUSD": 7.5,
"savings": {
"amount": "0.042",
"amountUSD": 105.0,
"percentage": 1.06
},
"executionTime": "6-10 seconds",
"timestamp": 1702345678
}
}
Response Fields:
- amountOut is the expected number of output tokens (wei/smallest units)
- amountOutHuman is a human-readable format (taking decimals into account)
- minAmountOut - minimum including slippage (unexpected slippage protection)
- priceImpact — price impact in % (0.51% in the example)
- route[] — route details (which DEX, what % of the order, what impact on each)
- savings — how much you save vs. best single DEX
2. POST /swap — execute swap
Description: Build a transaction to execute swap.
Request Body:
{
"tokenIn": "USDC",
"tokenOut": "ETH",
"amountIn": "10000000000",
"slippage": 1.0,
"userAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"route": { /* route object from /quote */ }
}
Example Request:
curl -X POST "https://api.hypertrade.io/v1/swap" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"tokenIn": "USDC",
"tokenOut": "ETH",
"amountIn": "10000000000",
"slippage": 1.0,
"userAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"route": { ... }
}'
Example Response:
{
"success": true,
"data": {
"to": "0xHypertradeRouterContractAddress",
"data": "0x38ed1739000000000000000...",
"value": "0",
"gasLimit": "350000",
"gasPrice": "1500000000",
"chainId": 998
}
}
Response Fields:
- to is the address of the Hypertrade Router contract
- data — encoded transaction data
- value — ETH value (usually "0" if you don't buy a native token)
- gasLimit is the recommended gas limit
- gasPrice – recommended gas price (in wei)
Usage:
Pass this data to wallet.sendTransaction() (ethers.js, web3.js, etc.):
const tx = await wallet.sendTransaction({
to: swapData.to,
data: swapData.data,
value: swapData.value,
gasLimit: swapData.gasLimit,
gasPrice: swapData.gasPrice,
});
const receipt = await tx.wait();
console.log('Swap completed:', receipt);
3. GET /tokens – List of supported tokens
Description: Get a list of all tokens available for swap on Hyperliquid.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| chainId | number | No | Chain ID (default: 998 for Hyperliquid) |
Example Request:
curl -X GET "https://api.hypertrade.io/v1/tokens?chainId=998"
Example Response:
{
"success": true,
"data": [
{
"symbol": "USDC",
"name": "USD Coin",
"address": "0x...",
"decimals": 6,
"logoURI": "https://...",
"verified": true
},
{
"symbol": "ETH",
"name": "Wrapped Ether",
"address": "0x...",
"decimals": 18,
"logoURI": "https://...",
"verified": true
},
{
"symbol": "HYPE",
"name": "Hyperliquid",
"address": "0x...",
"decimals": 18,
"logoURI": "https://...",
"verified": true
}
]
}
4. GET /price — the current price of the token
Description: Get the current market price of the token in USDC.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| token | string | Yes | Symbol or contract address |
Example Request:
curl -X GET "https://api.hypertrade.io/v1/price?token=ETH"
Example Response:
{
"success": true,
"data": {
"token": "ETH",
"priceUSD": 2500.45,
"change24h": 3.2,
"volume24h": 125000000,
"timestamp": 1702345678
}
}
5. GET /liquidity — the liquidity of the pair
Description: Get liquidity information for a trading pair.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| tokenA | string | Yes | First token |
| tokenB | string | Yes | Second token |
Example Request:
curl -X GET "https://api.hypertrade.io/v1/liquidity?tokenA=USDC&tokenB=ETH"
Example Response:
{
"success": true,
"data": {
"pair": "USDC/ETH",
"totalLiquidityUSD": 5200000,
"sources": [
{
"dex": "HyperCore Spot",
"liquidityUSD": 2100000,
"percentage": 40.4
},
{
"dex": "Hyperswap",
"liquidityUSD": 1800000,
"percentage": 34.6
},
{
"dex": "Kittenswap",
"liquidityUSD": 1300000,
"percentage": 25.0
}
],
"timestamp": 1702345678
}
}
6. GET /status — API status
Description: Check the health of the API and the availability of services.
Example Request:
curl -X GET "https://api.hypertrade.io/v1/status"
Example Response:
{
"success": true,
"data": {
"status": "operational",
"version": "1.2.4",
"uptime": "99.98%",
"services": {
"router": "operational",
"invisium": "operational",
"hypercore": "operational",
"hyperswap": "operational",
"kittenswap": "operational"
},
"latency": {
"quote": "120ms",
"swap": "850ms"
}
}
}
SDK Reference: TypeScript/JavaScript
Installation:
npm install @hypertrade/sdk ethers
Initialization:
import { HypertradeSDK } from '@hypertrade/sdk';
import { ethers } from 'ethers';
Connecting to Hyperliquid
const provider = new ethers. JsonRpcProvider('https://api.hyperliquid.xyz/evm');
const signer = new ethers. Wallet(PRIVATE_KEY, provider);
Initializing the SDK
const hypertrade = new HypertradeSDK({
provider,
signer,
apiKey: 'YOUR_API_KEY', // optional
chainId: 998, // Hyperliquid
});
Main methods:
1. getQuote() — get a quote
const quote = await hypertrade.getQuote({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: ethers.parseUnits('1000', 6), // 1000 USDC (6 decimals)
slippage: 1.0, // 1%
});
console.log('You will receive:', ethers.formatUnits(quote.amountOut, 18), 'ETH');
console.log('Price impact:', quote.priceImpact, '%');
console.log('Route:', quote.route.map(r => `${r.percentage}% via ${r.dex}`));
2. executeSwap() — execute swap
try {
const tx = await hypertrade.executeSwap({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: ethers.parseUnits('1000', 6),
slippage: 1.0,
deadline: Math.floor(Date.now() / 1000) + 600, // 10 minutes
});
console.log('Transaction sent:', tx.hash);
const receipt = await tx.wait();
console.log('Swap completed!');
console.log('Gas used:', receipt.gasUsed.toString());
} catch (error) {
console.error('Swap failed:', error);
}
3. approveToken() — approve token
Before the first token swap, you need to give approval to the Hypertrade Router:
Check if approval is required
const allowance = await hypertrade.checkAllowance('USDC');
const amountIn = ethers.parseUnits('1000', 6);
if (allowance < amountIn) {
console.log('Approval needed...');
const approveTx = await hypertrade.approveToken('USDC', amountIn);
await approveTx.wait();
console.log('Approval successful!');
}
Now you can swap
const swapTx = await hypertrade.executeSwap({ ... });
Recommendation: Use limited approval (exact amount or amount + 10%) rather than unlimited.
4. getTokens() — list of tokens
const tokens = await hypertrade.getTokens();
console.log('Available tokens:');
tokens.forEach(token => {
console.log(`${token.symbol} (${token.name}): ${token.address}`);
});
5. getPrice() — current price
const ethPrice = await hypertrade.getPrice('ETH');
console.log('ETH price:', ethPrice.priceUSD, 'USD');
console.log('24h change:', ethPrice.change24h, '%');
6. simulateSwap() — no execution simulation
Useful for testing:
const simulation = await hypertrade.simulateSwap({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: ethers.parseUnits('10000', 6), // large order
slippage: 1.0,
});
console.log('Simulated result:');
console.log('Amount out:', ethers.formatUnits(simulation.amountOut, 18), 'ETH');
console.log('Price impact:', simulation.priceImpact, '%');
console.log('Gas cost:', simulation.gasCostUSD, 'USD');
Check if the swap will execute
if (simulation.success) {
console.log('✅ Swap will succeed');
} else {
console.error('❌ Swap will fail:', simulation.error);
}
React Hooks Reference
Installation:
npm install @hypertrade/react-hooks ethers wagmi
Setup Provider:
import { HypertradeProvider } from '@hypertrade/react-hooks';
import { WagmiConfig } from 'wagmi';
function App() {
return (
<WagmiConfig config={wagmiConfig}>
<HypertradeProvider apiKey="YOUR_API_KEY">
<YourApp />
</HypertradeProvider>
</WagmiConfig>
);
}
1. useQuote() — getting a quote
import { useQuote } from '@hypertrade/react-hooks';
function SwapInterface() {
const [amountIn, setAmountIn] = useState('1000');
const {
data: quote,
isLoading,
error
} = useQuote({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn,
slippage: 1.0,
enabled: amountIn !== '', // fetch only when amount is entered
});
if (isLoading) return <p>Loading quote... </p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<p>You will receive: {quote.amountOutHuman} ETH</p>
<p>Price impact: {quote.priceImpact}%</p>
</div>
);
}
Features:
- Automatic refetch every 10 seconds
- Debounce for amountIn (does not spam API when typing)
- Caching results
2. useSwap() — swap execution
import { useSwap } from '@hypertrade/react-hooks';
function SwapButton({ quote }) {
const {
swap,
isSwapping,
isSuccess,
error
} = useSwap();
const handleSwap = async () => {
try {
const result = await swap({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: '1000',
quote: quote.route,
});
console.log('Swap completed:', result);
alert(`Received ${result.amountOut} ETH`);
} catch (err) {
console.error('Swap failed:', err);
}
};
return (
<button onClick={handleSwap} disabled={isSwapping}>
{isSwapping ? 'Swapping...' : 'Swap'}
</button>
);
}
3. useApproval() — management approvals
import { useApproval } from '@hypertrade/react-hooks';
function ApprovalButton({ token, amount }) {
const {
needsApproval,
approve,
isApproving
} = useApproval(token, amount);
if (!needsApproval) {
return <p>✅ Token approved</p>;
}
return (
<button onClick={approve} disabled={isApproving}>
{isApproving ? 'Approving...' : 'Approve USDC'}
</button>
);
}
4. useTokens() — list of tokens
import { useTokens } from '@hypertrade/react-hooks';
function TokenSelector({ onSelect }) {
const { data: tokens, isLoading } = useTokens();
if (isLoading) return <p>Loading tokens... </p>;
return (
<select onChange={(e) => onSelect(e.target.value)}>
{tokens.map(token => (
<option key={token.address} value={token.symbol}>
{token.symbol} - {token.name}
</option>
))}
</select>
);
}
5. useBalance() — token balance
import { useBalance } from '@hypertrade/react-hooks';
function BalanceDisplay({ token }) {
const { balance, isLoading } = useBalance(token);
if (isLoading) return <p>Loading balance... </p>;
return (
<p>Balance: {balance} {token}</p>
);
}
Best Practices for Integration
1. Error handling
Always handle possible errors:
try {
const quote = await hypertrade.getQuote({ ... });
} catch (error) {
if (error.code === 'INSUFFICIENT_LIQUIDITY') {
alert('Not enough liquidity for this swap');
} else if (error.code === 'HIGH_PRICE_IMPACT') {
alert(`Price impact ${error.impact}% is too high. Consider splitting the order.`);
} else if (error.code === 'USER_REJECTED') {
console.log('User cancelled transaction');
} else {
console.error('Unexpected error:', error);
alert('Swap failed. Please try again.');
}
}
Typical error codes:
- INSUFFICIENT_LIQUIDITY — insufficient liquidity
- HIGH_PRICE_IMPACT — price impact >10%
- SLIPPAGE_EXCEEDED – the actual price is worse than minAmountOut
- INSUFFICIENT_BALANCE — the user does not have enough tokens
- INSUFFICIENT_GAS – not enough HYPE for gas
- USER_REJECTED — the user rejected the transaction in the wallet
- NETWORK_ERROR - RPC or API issue
- RATE_LIMIT_EXCEEDED - Rate limit exceeded
2. UX Recommendations
✅ Show loading states:
{isLoading && <Spinner />}
{quote && <QuoteDetails quote={quote} />}
✅ Show the details of the route:
<div className="route-details">
<h4>Route:</h4>
{quote.route.map((hop, index) => (
<div key={index}>
{hop.percentage}% via {hop.dex} (impact: {hop.priceImpact}%)
</div>
))}
</div>
✅ Show your savings:
{quote.savings && (
<p className="savings">
💰 You save ${quote.savings.amountUSD} vs. single DEX
</p>
)}
✅ Warn about high price impact:
{quote.priceImpact > 3 && (
<Warning>
⚠️ High price impact ({quote.priceImpact}%).
Consider splitting your order.
</Warning>
)}
✅ Show the progress of the transaction:
{isSwapping && (
<div className="tx-progress">
<Spinner />
<p>Swap in progress... </p>
<p>Transaction hash: {tx.hash}</p>
<a href={`https://explorer.hyperliquid.xyz/tx/${tx.hash}`} target="_blank">
View on Explorer
</a>
</div>
)}
3. Gas optimization
✅ Estimate gas before execution:
const gasEstimate = await hypertrade.estimateGas({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: amount,
});
console.log('Estimated gas cost:', gasEstimate.gasCostUSD, 'USD');
Warn the user if the gas is high
if (gasEstimate.gasCostUSD > 10) {
const confirm = window.confirm(
`Gas cost is high ($${gasEstimate.gasCostUSD}). Continue?`
);
if (!confirm) return;
}
✅ Batch approvals for multiple tokens:
Instead of separate approvals for each token
const tokensToApprove = ['USDC', 'ETH', 'HYPE'];
const approvals = await Promise.all(
tokensToApprove.map(token => hypertrade.approveToken(token, amount))
);
await Promise.all(approvals.map(tx => tx.wait()));
console.log('All tokens approved');
4. Security best practices
✅ User input validation:
function validateAmount(amount: string, decimals: number): boolean {
Format check
if (!/^\d+\.? \d*$/.test(amount)) {
throw new Error('Invalid amount format');
}
Range check
const parsed = parseFloat(amount);
if (parsed <= 0) {
throw new Error('Amount must be positive');
}
if (parsed > 1e18) {
throw new Error('Amount too large');
}
return true;
}
✅ Checking the contract address:
Check that tokenIn/tokenOut are legitimate tokens
const verifiedTokens = await hypertrade.getTokens();
const isTokenInVerified = verifiedTokens.some(t => t.symbol === tokenIn);
const isTokenOutVerified = verifiedTokens.some(t => t.symbol === tokenOut);
if (!isTokenInVerified || !isTokenOutVerified) {
throw new Error('Token not verified');
}
✅ Rate limiting:
Limit the number of requests per user
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 60*1000, // 1 minute
max: 20, // maximum 20 requests
message: 'Too many requests, please try again later.',
});
app.use('/api/swap', limiter);
5. Analytics and monitoring
✅ Swap event logging:
const result = await hypertrade.executeSwap({ ... });
Send an event to your analytics
analytics.track('Swap Completed', {
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: '1000',
amountOut: result.amountOut,
priceImpact: result.priceImpact,
gasCostUSD: result.gasCostUSD,
savings: result.savings,
userAddress: user.address,
timestamp: Date.now(),
});
✅ Bug Monitoring:
try {
await hypertrade.executeSwap({ ... });
} catch (error) {
Send to Sentry / error tracking
Sentry.captureException(error, {
tags: {
component: 'swap',
tokenIn: 'USDC',
tokenOut: 'ETH',
},
user: { address: user.address },
});
throw error;
}
Referral Program: Monetization of Integration
How it works:
- You integrate Hypertrade into your dApp
- Register for the referral program: https://docs.hypertrade.io/referral
- Get referral code
- Pass the referral code in each swap request
- Get % of the volume of swaps made through your dApp
Example of integration:
const hypertrade = new HypertradeSDK({
provider,
signer,
apiKey: 'YOUR_API_KEY',
referralCode: 'YOUR_REFERRAL_CODE', // your unique code
});
All swaps are automatically counted as your referrals
const tx = await hypertrade.executeSwap({ ... });
Terms of the program:
- Minimum Volume: $100,000/month
- Commission: 0.05-0.15% of the volume (depends on the volume)
- Payout: Monthly in USDC or HYPE
- Tracking: real-time dashboard with analytics
Calculation example:
Your dApp generates $5M of swap volume/month
Commission: 0.1%
Your Earnings: $5,000/month ($60,000/year)
Read more: https://docs.hypertrade.io/referral
Integration examples
Example 1: DeFi Dashboard
Use case: the user wants to rebalance the portfolio (sell 30% ETH, buy USDC).
function PortfolioRebalance() {
const [portfolio, setPortfolio] = useState({
ETH: 10.5,
USDC: 5000,
HYPE: 2000,
});
const handleRebalance = async () => {
Sell 30% ETH
const ethToSell = portfolio. ETH * 0.3; // 3.15 ETH
const quote = await hypertrade.getQuote({
tokenIn: 'ETH',
tokenOut: 'USDC',
amountIn: ethers.parseUnits(ethToSell.toString(), 18),
slippage: 1.0,
});
console.log('Will receive:', quote.amountOutHuman, 'USDC');
const tx = await hypertrade.executeSwap({
tokenIn: 'ETH',
tokenOut: 'USDC',
amountIn: ethers.parseUnits(ethToSell.toString(), 18),
slippage: 1.0,
});
await tx.wait();
Update portfolio
setPortfolio({
ETH: portfolio. ETH - ethToSell,
USDC: portfolio. USDC + parseFloat(quote.amountOutHuman),
HYPE: portfolio. HYPE,
});
alert('Rebalance complete!');
};
return (
<div>
<h2>Portfolio Rebalance</h2>
<p>ETH: {portfolio. ETH}</p>
<p>USDC: {portfolio. USDC}</p>
<button onClick={handleRebalance}>Rebalance (Sell 30% ETH)</button>
</div>
);
}
Example 2: NFT Marketplace
Use case: A user wants to buy NFTs with ETH, but they only have USDC.
function NFTPurchase({ nftPrice }) {
const [userBalance, setUserBalance] = useState({ USDC: 5000, ETH: 0.5 });
const handleBuyNFT = async () => {
const ethNeeded = nftPrice; e.g. 2.5 ETH
if (userBalance.ETH >= ethNeeded) {
Enough ETH, you can buy it right away
await purchaseNFT(ethNeeded);
} else {
Not enough ETH → swap USDC → ETH
const ethShortage = ethNeeded - userBalance.ETH; 2.0 ETH needs to be purchased
const quote = await hypertrade.getQuote({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountOut: ethers.parseUnits(ethShortage.toString(), 18), // reversed quote
slippage: 1.0,
});
console.log('Need to swap:', quote.amountInHuman, 'USDC');
User Confirmation
const confirm = window.confirm(
`You need ${ethShortage} ETH. Swap ${quote.amountInHuman} USDC?`
);
if (!confirm) return;
Execute swap
const tx = await hypertrade.executeSwap({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: quote.amountIn,
slippage: 1.0,
});
await tx.wait();
Update Balance
setUserBalance({
USDC: userBalance.USDC - parseFloat(quote.amountInHuman),
ETH: userBalance.ETH + ethShortage,
});
Buy NFTs Now
await purchaseNFT(ethNeeded);
}
};
return (
<div>
<h2>Buy NFT</h2>
<p>Price: {nftPrice} ETH</p>
<p>Your balance: {userBalance.ETH} ETH, {userBalance.USDC} USDC</p>
<button onClick={handleBuyNFT}>Buy NFT</button>
</div>
);
}
Integration examples
Example 3: Trading Bot
Use case: Automatic DCA (Dollar Cost Averaging) — buying $1000 worth of ETH every Monday.
import cron from 'node-cron';
Every Monday at 10:00 UTC
cron.schedule('0 10 * * 1', async () => {
console.log('Running weekly DCA...');
try {
const amountUSDC = 1000;
const quote = await hypertrade.getQuote({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: ethers.parseUnits(amountUSDC.toString(), 6),
slippage: 1.0,
});
console.log('Will buy:', quote.amountOutHuman, 'ETH for', amountUSDC, 'USDC');
console.log('Price:', amountUSDC / parseFloat(quote.amountOutHuman), 'USDC/ETH');
const tx = await hypertrade.executeSwap({
tokenIn: 'USDC',
tokenOut: 'ETH',
amountIn: ethers.parseUnits(amountUSDC.toString(), 6),
slippage: 1.0,
});
await tx.wait();
console.log('DCA successful! Tx:', tx.hash);
Send a notification
await sendNotification(`DCA executed: Bought ${quote.amountOutHuman} ETH`);
} catch (error) {
console.error('DCA failed:', error);
await sendErrorAlert('DCA failed', error);
}
});
Troubleshooting: Common Problems
Issue 1: "Insufficient liquidity"
Reason: insufficient liquidity for the order.
Solution:
- Reduce Order Size
- Divide into several parts
- Try a different pair (e.g., USDC → HYPE → ETH instead of direct USDC → ETH)
if (error.code === 'INSUFFICIENT_LIQUIDITY') {
Try to reduce the order by 20%
const newAmount = originalAmount * 0.8;
const quote = await hypertrade.getQuote({ ... params, amountIn: newAmount });
}
Problem 2: "High price impact"
The reason: your order is too large relative to liquidity.
Solution:
- Use split-routing (Hypertrade does it automatically)
- Split the order into multiple transactions with an interval of
- Use limit order on HyperCore Spot
if (quote.priceImpact > 5) {
console.warn('High price impact! Consider splitting order.');
Automatic division into 3 parts
const partSize = originalAmount / 3;
for (let i = 0; i < 3; i++) {
const tx = await hypertrade.executeSwap({ ... params, amountIn: partSize });
await tx.wait();
Wait 30 seconds before the next part
if (i < 2) await sleep(30000);
}
}
Problem 3: "Slippage exceeded"
Reason: the price changed between receiving the quote and executing swap.
Solution:
- Increase slippage tolerance
- Get a new quote before swap
- Use Invisium Simulations for more accurate prediction
try {
const tx = await hypertrade.executeSwap({ ... params, slippage: 1.0 });
} catch (error) {
if (error.code === 'SLIPPAGE_EXCEEDED') {
Try with enlarged slippage
console.log('Retrying with higher slippage...');
const tx = await hypertrade.executeSwap({ ... params, slippage: 2.0 });
}
}
Problem 4: "Insufficient gas"
Reason: Not enough HYPE for gas.
Solution:
- Check your HYPE balance before swapping
- Warn the user
const hypeBalance = await provider.getBalance(userAddress);
const minHypeNeeded = ethers.parseUnits('5', 18); Minimum 5 HYPE
if (hypeBalance < minHypeNeeded) {
alert('Insufficient HYPE for gas. Please add at least 5 HYPE to your wallet.');
return;
}
Problem 5: Rate limit exceeded
Cause: Too many API requests.
Solution:
- Get an API key for an increased limit
- Use debounce for user input
- Cache quotes for 5-10 seconds
import debounce from 'lodash.debounce';
Debounce to avoid API spam
const debouncedGetQuote = debounce(async (params) => {
const quote = await hypertrade.getQuote(params);
setQuote(quote);
}, 500); 500ms Latency
On user input
const handleAmountChange = (newAmount) => {
setAmount(newAmount);
debouncedGetQuote({ ... params, amountIn: newAmount });
};
Conclusion: Start Integrating Today
Advantages of Hypertrade integration:
- ✅ 30-60 minutes before the first working swap
- ✅ 0% platform fee — all the savings for users
- ✅ Best courses on Hyperliquid (split-routing, Invisium)
- ✅ Simple API — REST + TypeScript SDK + React hooks
- ✅ Full documentation and code
- ✅ examples Referral program — integration
- ✅ monetization Support — Discord, email, Telegram
Next steps:
- 📚 Study the documentation: https://docs.hypertrade.io
- 🔑 Get API key: https://docs.hypertrade.io/api-keys
- 💻 Install the SDK: npm install @hypertrade/sdk
- 🚀 Integrate into your dApp (use the examples above)
- 🧪 Test on the Hyperliquid testnet
- 🎉 Run on mainnet
Resources for developers:
📚 Documentation:
- API Reference: https://docs.hypertrade.io/api
- SDK Docs: https://docs.hypertrade.io/sdk
- React Hooks: https://docs.hypertrade.io/react-hooks
- Examples: https://github.com/hypertrade/examples
💬 Support:
- Discord (dev channel): https://discord.gg/hypertrade
- Twitter: @Hypertrade_xyz
- Email: developers@hypertrade.io
- Telegram: @HypertradeDev
🎁 Referral Program:
- Registration: https://docs.hypertrade.io/referral
- Dashboard: https://app.hypertrade.io/referrals
FAQ for Developers
1. Is it free to use the API?
Yes, the public API is free with a limit of 100 requests/minute. For an increased limit (1000 req/min), get a free API key.
2. Do I need a backend for integration?
No, the SDK works entirely on the frontend (in the browser). Backend is only needed for automated bots or server-side integrations.
3. Which blockchains are supported?
Only Hyperliquid (HyperEVM, chainId 998). Support for other chains is not planned.
4. Can I customize the UI?
Yes, the SDK gives you full control. You can use a ready-made widget or create your own UI from scratch.
5. How does the referral program work?
You get 0.05-0.15% of the volume of swaps made through your dApp. Minimum volume: $100k/month. Payments monthly.
6. Is there a testnet?
Yes, use the Hyperliquid testnet for testing. API endpoint: https://api.hypertrade.io/v1/testnet
7. Can I use the API without the SDK?
Yes, the REST API works with any language (Python, Go, Rust, etc.). The SDK is just a handy wrapper.
8. How often is the quote updated?
The API updates quotes in real time (every 1-2 seconds). The SDK has built-in polling.
9. What should I do if I have a problem?
Write to Discord (#dev-support) or developers@hypertrade.io. Average response time: 2-6 hours.
10. Are there any code examples?
Yes, see https://github.com/hypertrade/examples — there are 10+ examples for different use cases.