const { MoroBestRate } = require('@moromoro/moro-sdk')
const { ethers } = require('ethers')
async function productionSwap(
srcToken,
destToken,
amountIn,
slippagePercent = 1
) {
// 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')
const gasPrice = ethers.BigNumber.from('5000000000')
try {
// 1. Validate inputs
if (!ethers.utils.isAddress(srcToken)) {
throw new Error('Invalid source token address')
}
if (!ethers.utils.isAddress(destToken)) {
throw new Error('Invalid destination token address')
}
if (amountIn.lte(0)) {
throw new Error('Amount must be greater than 0')
}
// 2. Check balance
const isNative = srcToken === '0x5555555555555555555555555555555555555555'
let balance
if (isNative) {
balance = await signer.getBalance()
} else {
const token = new ethers.Contract(
srcToken,
['function balanceOf(address) view returns (uint256)'],
provider
)
balance = await token.balanceOf(signer.address)
}
if (balance.lt(amountIn)) {
throw new Error(
`Insufficient balance. Have ${balance.toString()}, need ${amountIn.toString()}`
)
}
// 3. Approve if ERC20
if (!isNative) {
console.log('Approving token...')
const approveTx = await moroClient.approve(signer, srcToken, amountIn)
if (approveTx) {
await approveTx.wait()
console.log('✓ Token approved')
}
}
// 4. Get quote
console.log('Getting best rate...')
const quote = await moroClient.getQuote(
srcToken,
destToken,
amountIn,
gasPrice,
{ enableSplit: true }
)
console.log('Quote:')
console.log('- Amount Out:', quote.amountOut)
console.log('- Type:', quote.type)
console.log('- Block:', quote.blockNumber)
// 5. Calculate slippage
const minOut = ethers.BigNumber.from(quote.amountOut)
.mul(100 - slippagePercent)
.div(100)
console.log(`- Min Out (${slippagePercent}% slippage):`, minOut.toString())
// 6. Execute swap
console.log('Executing swap...')
const tx = await moroClient.swap(
signer,
srcToken,
destToken,
amountIn,
minOut,
quote
)
console.log('Transaction hash:', tx.hash)
// 7. Wait for confirmation
const receipt = await tx.wait()
console.log('✓ Swap confirmed!')
console.log(' Block:', receipt.blockNumber)
console.log(' Gas used:', receipt.gasUsed.toString())
return {
success: true,
txHash: tx.hash,
blockNumber: receipt.blockNumber,
gasUsed: receipt.gasUsed.toString()
}
} catch (error) {
console.error('Swap failed:', error.message)
return {
success: false,
error: error.message
}
}
}
// Usage
const HYPE = '0x5555555555555555555555555555555555555555'
const USDT = '0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb'
const amount = ethers.utils.parseUnits('10', 18)
productionSwap(HYPE, USDT, amount, 1)
.then(result => console.log('Result:', result))