Swap
This page provides practical examples for executing token swaps using the Moromoro SDK.
Basic Swap: Native to ERC20
Swap native HYPE tokens to USDT on HyperEVM.
const { MoroBestRate } = require('@moromoro/moro-sdk')
const { ethers } = require('ethers')
async function swapHYPEtoUSDT() {
// Setup
const provider = new ethers.providers.JsonRpcProvider(
'https://rpc.hyperliquid.xyz/evm'
)
const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider)
const moroClient = new MoroBestRate(provider, 'hyperevm')
// Token addresses
const HYPE = '0x5555555555555555555555555555555555555555'
const USDT = '0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb'
// Swap parameters
const amountIn = ethers.utils.parseUnits('10', 18) // 10 HYPE
const gasPrice = ethers.BigNumber.from('5000000000') // 5 gwei
try {
// Get quote
console.log('Getting best rate...')
const quote = await moroClient.getQuote(
HYPE,
USDT,
amountIn,
gasPrice,
{ enableSplit: false }
)
console.log('Quote received:')
console.log('- Amount Out:', ethers.utils.formatUnits(quote.amountOut, 6), 'USDT')
console.log('- Type:', quote.type)
// Calculate minimum output with 1% slippage
const minAmountOut = ethers.BigNumber.from(quote.amountOut)
.mul(99)
.div(100)
console.log('- Min Amount Out:', ethers.utils.formatUnits(minAmountOut, 6), 'USDT')
// Execute swap
console.log('\nExecuting swap...')
const tx = await moroClient.swap(
signer,
HYPE,
USDT,
amountIn,
minAmountOut,
quote
)
console.log('Transaction submitted:', tx.hash)
// Wait for confirmation
const receipt = await tx.wait()
console.log('✓ Swap confirmed in block', receipt.blockNumber)
} catch (error) {
console.error('Swap failed:', error.message)
throw error
}
}
swapHYPEtoUSDT()ERC20 to ERC20 Swap
Swap USDT to another ERC20 token. Requires token approval.
ERC20 to Native Swap
Swap ERC20 tokens back to native HYPE.
Swap with Custom Receiver
Send output tokens to a different address.
Swap with Gas Limit Override
Set a custom gas limit for the transaction.
Checking Balance Before Swap
Always verify sufficient balance before executing a swap.
Error Handling
Comprehensive error handling for swaps.
Complete Example with All Checks
Production-ready swap example with all safety checks.
See Also
Split Trading Examples
Multi-Chain Examples