Gas optimization

Learn how to optimize gas costs when using the Moromoro SDK.

Understanding Gas Costs

Gas costs for swaps consist of:

  • Base transaction cost (~21,000 gas)

  • Router contract execution (~50,000–150,000 gas)

  • DEX interaction costs (varies by DEX type)

  • Token transfers (~50,000 gas per transfer)

  • Split trade overhead (if using multiple paths)

Gas-Aware Quote Selection

The SDK automatically considers gas costs when calculating the best rate.

const { MoroBestRate } = require('@moromoro/moro-sdk')
const { ethers } = require('ethers')

async function gasAwareSwap() {
  const provider = new ethers.providers.JsonRpcProvider(
    'https://rpc.hyperliquid.xyz/evm'
  )
  const moroClient = new MoroBestRate(provider, 'hyperevm')

  const HYPE = '0x5555555555555555555555555555555555555555'
  const USDT = '0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb'
  const amountIn = ethers.utils.parseUnits('10', 18)

  // Provide accurate gas price for better rate calculation
  const gasPrice = await provider.getGasPrice()
  console.log('Current gas price:', ethers.utils.formatUnits(gasPrice, 'gwei'), 'gwei')

  // SDK considers gas costs in the amountOut calculation
  const quote = await moroClient.getQuote(
    HYPE,
    USDT,
    amountIn,
    gasPrice,
    { enableSplit: true }
  )

  console.log('Gas fees:', quote.gasFees)
  console.log('Net amount out (after gas):', quote.amountOut)
}

gasAwareSwap()

Optimizing for L2 Chains

L2 chains like Optimism and Arbitrum have different gas models.

Batch Approvals

Approve once for unlimited use to save gas on future swaps.

Minimizing Split Paths

Control the number of paths to balance rate improvement vs gas cost.

Dynamic Gas Pricing

Adjust gas price based on network conditions.

Estimating Gas Costs

Estimate total gas cost before executing.

Comparing Gas Costs

Compare gas costs between single and split trades.

Zero Gas Options Helper

Use the built-in helper for testing without gas considerations.

Gas Optimization Checklist

  • ✅ Use unlimited approvals for frequently traded tokens

  • ✅ Provide accurate gas prices to SDK for better routing

  • ✅ Consider L2 chains for high-frequency trading

  • ✅ Limit split paths for small trades

  • ✅ Batch multiple swaps when possible

  • ✅ Monitor gas prices and swap during low-cost periods

  • ✅ Use native tokens when possible (no approval needed)

Advanced: Custom Gas Limit

Set custom gas limits for specific scenarios.

See Also