Skip to main content

Overview

Monei integrates with leading DEX aggregators to provide the best swap rates across multiple decentralized exchanges. This guide covers token swaps on EVM networks. What you’ll learn:
  • Get swap quotes and rates
  • Swap native tokens to ERC-20 tokens
  • Swap ERC-20 to ERC-20 tokens
  • Swap ERC-20 tokens back to native
  • Price impact and slippage
  • Gas optimization for swaps

Swap Types

Native → Token

Swap ETH/BNB/MATIC to any ERC-20 token

Token → Token

Swap between any two ERC-20 tokens

Token → Native

Swap ERC-20 tokens back to native currency

Get Swap Quote

Always get a quote before executing a swap to see the exchange rate and estimated output.

Native to Token Quote

import MoneiSDK from 'monei-sdk';

const monei = new MoneiSDK({
  apiKey: process.env.MONEI_API_KEY,
});

// Get quote for swapping 0.1 BNB to USDT on BSC
const quote = await monei.evmExchange.getQuoteNativeToToken({
  outputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT on BSC
  amount: '0.1', // 0.1 BNB
  chainId: 56
});

console.log('Quote ID:', quote.quoteId);
console.log('From:', quote.fromToken.symbol, '(Native)');
console.log('To:', quote.toToken.symbol);
console.log('Input Amount:', quote.fromAmount);
console.log('Output Amount:', quote.toAmount);
console.log('Exchange Rate:', quote.rate);
console.log('Minimum Output:', quote.minToAmount, '(with slippage)');
console.log('Price Impact:', quote.priceImpact + '%');
console.log('Gas Cost:', quote.estimatedGasUsd, 'USD');
console.log('Expires At:', new Date(quote.expiryTimestamp * 1000));
Response:
{
  "statusCode": 200,
  "message": "Quote retrieved successfully",
  "data": {
    "quoteId": "0x592dbadfad19da6808b637c2",
    "fromToken": {
      "address": null,
      "symbol": "BNB",
      "decimals": 18
    },
    "toToken": {
      "address": "0x55d398326f99059fF775485246999027B3197955",
      "symbol": "USDT",
      "decimals": 18
    },
    "fromAmount": "100000000000000000",
    "toAmount": "28700000000000000000",
    "rate": "287.0",
    "reverseRate": "0.003484",
    "minToAmount": "28413000000000000000",
    "protocolFee": "100000000000000",
    "protocolFeeToken": {
      "address": null,
      "symbol": "BNB",
      "decimals": 18
    },
    "estimatedGas": "150000",
    "estimatedGasUsd": "1.25",
    "priceImpact": "0.15",
    "liquidityAvailable": true,
    "totalValueUsd": "28.70",
    "expiryTimestamp": 1698765432,
    "blockNumber": "24161093",
    "chainId": 56
  }
}

Token to Token Quote

// Get quote for USDT → USDC swap on BSC
const quote = await monei.evmExchange.getQuoteTokenToToken({
  inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  outputMint: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', // USDC
  amount: '100', // 100 USDT
  chainId: 56
});

console.log('Swap 100 USDT → USDC');
console.log('Rate:', quote.rate);
console.log('Output:', quote.toAmount, 'USDC');
console.log('Min Output:', quote.minToAmount, 'USDC');
console.log('Price Impact:', quote.priceImpact + '%');

Token to Native Quote

// Get quote for USDT → BNB swap
const quote = await monei.evmExchange.getQuoteTokenToNative({
  inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  amount: '100', // 100 USDT
  chainId: 56
});

console.log('Swap 100 USDT → BNB');
console.log('Rate:', quote.rate);
console.log('Output:', quote.toAmount, 'BNB');
console.log('Min Output:', quote.minToAmount, 'BNB');

Execute Swap

Swap Native to Token

// Swap 0.1 BNB to USDT on BSC
const swap = await monei.evmExchange.swapNativeToToken({
  outputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  amount: '0.1', // 0.1 BNB
  amountOut: '28', // Expected minimum USDT output
  chainId: 56
});

console.log('Transaction Hash:', swap.txHash);
console.log('View on BscScan:', `https://bscscan.com/tx/${swap.txHash}`);

// Wait for confirmation
await monei.evm.waitForTransaction(swap.txHash, 56);
console.log('Swap completed!');
Response:
{
  "statusCode": 200,
  "message": "Swap executed successfully",
  "data": {
    "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
  }
}

Swap Token to Token

// Swap 100 USDT to USDC on BSC
const swap = await monei.evmExchange.swapTokenToToken({
  inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  outputMint: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', // USDC
  amount: '100',
  chainId: 56
});

console.log('Transaction Hash:', swap.txHash);
console.log('View on BscScan:', `https://bscscan.com/tx/${swap.txHash}`);

Swap Token to Native

// Swap 100 USDT to BNB on BSC
const swap = await monei.evmExchange.swapTokenToNative({
  inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  amount: '100',
  chainId: 56
});

console.log('Transaction Hash:', swap.txHash);
console.log('View on BscScan:', `https://bscscan.com/tx/${swap.txHash}`);

Understanding Quote Details

Key Quote Fields

FieldDescription
quoteIdUnique identifier for this quote (valid for ~5 minutes)
rateExchange rate (1 input token = X output tokens)
reverseRateReverse rate (1 output token = Y input tokens)
toAmountExpected output amount
minToAmountMinimum output after slippage (usually 0.5%)
priceImpactHow much this trade affects the market price
estimatedGasEstimated gas cost in native token
estimatedGasUsdEstimated gas cost in USD
liquidityAvailableWhether sufficient liquidity exists
expiryTimestampWhen this quote expires (Unix timestamp)

Price Impact

Price impact shows how much your trade will move the market price:
Price ImpactInterpretationAction
< 1%Low impactSafe to proceed
1% - 3%Moderate impactConsider splitting trade
3% - 5%High impactWarning recommended
> 5%Very high impactSplit into smaller trades
// Check price impact before swapping
const quote = await monei.evmExchange.getQuoteNativeToToken({
  outputMint: tokenAddress,
  amount: '1.0',
  chainId: 56
});

const priceImpact = parseFloat(quote.priceImpact);

if (priceImpact > 5) {
  console.log('⚠️ WARNING: Very high price impact!');
  console.log('Consider splitting into smaller trades');
} else if (priceImpact > 3) {
  console.log('⚠️ High price impact:', priceImpact + '%');
} else if (priceImpact > 1) {
  console.log('ℹ️ Moderate price impact:', priceImpact + '%');
} else {
  console.log('✓ Low price impact:', priceImpact + '%');
}

Slippage Protection

Slippage is the difference between expected and actual output amounts. Default Slippage: 0.5% (configurable)
// Calculate minimum output with custom slippage
function calculateMinOutput(expectedOutput, slippagePercent = 0.5) {
  const slippage = 1 - (slippagePercent / 100);
  return (parseFloat(expectedOutput) * slippage).toFixed(6);
}

// Get quote
const quote = await monei.evmExchange.getQuoteNativeToToken({
  outputMint: tokenAddress,
  amount: '0.1',
  chainId: 56
});

// Calculate min output with 1% slippage
const minOutput = calculateMinOutput(quote.toAmount, 1.0);

console.log('Expected Output:', quote.toAmount);
console.log('Min Output (1% slippage):', minOutput);
console.log('Default Min Output (0.5%):', quote.minToAmount);

// Execute with custom slippage
const swap = await monei.evmExchange.swapNativeToToken({
  outputMint: tokenAddress,
  amount: '0.1',
  amountOut: minOutput, // Custom min output
  chainId: 56
});
Recommended Slippage:
Market ConditionRecommended Slippage
Stablecoin swaps0.1% - 0.3%
Normal volatility0.5% - 1.0%
High volatility1.0% - 3.0%
Very low liquidity3.0% - 5.0%

Gas Optimization

Network Comparison for Swaps

NetworkTypical Swap GasUSD CostBest For
Polygon~200,000 gas0.050.05 - 0.20Small/frequent swaps
BSC~180,000 gas0.500.50 - 2.00Medium swaps
Base~150,000 gas1.001.00 - 3.00Fast execution
Arbitrum~200,000 gas1.001.00 - 5.00Balanced cost/speed
Optimism~200,000 gas0.500.50 - 3.00L2 efficiency
Ethereum~150,000 gas3030 - 100Large swaps only

Optimize Swap Costs

// Compare costs across networks
async function findBestNetwork(tokenInAddress, tokenOutAddress, amount) {
  const networks = [
    { chainId: 56, name: 'BSC' },
    { chainId: 137, name: 'Polygon' },
    { chainId: 8453, name: 'Base' },
    { chainId: 42161, name: 'Arbitrum' }
  ];
  
  const quotes = [];
  
  for (const network of networks) {
    try {
      const quote = await monei.evmExchange.getQuoteTokenToToken({
        inputMint: tokenInAddress,
        outputMint: tokenOutAddress,
        amount: amount,
        chainId: network.chainId
      });
      
      quotes.push({
        network: network.name,
        chainId: network.chainId,
        output: quote.toAmount,
        gasCostUsd: parseFloat(quote.estimatedGasUsd),
        netOutput: parseFloat(quote.toAmount) - parseFloat(quote.estimatedGasUsd)
      });
    } catch (error) {
      console.log(`${network.name}: Token not available`);
    }
  }
  
  // Sort by net output (after gas)
  quotes.sort((a, b) => b.netOutput - a.netOutput);
  
  console.log('\nNetwork Comparison:');
  quotes.forEach(q => {
    console.log(`${q.network}:`);
    console.log(`  Output: ${q.output}`);
    console.log(`  Gas Cost: $${q.gasCostUsd}`);
    console.log(`  Net: ${q.netOutput}`);
  });
  
  return quotes[0]; // Best network
}

// Find best network for swap
const best = await findBestNetwork(usdtAddress, usdcAddress, '100');
console.log(`\nBest Network: ${best.network}`);

Common Token Pairs

Stablecoin Swaps (BSC)

// USDT to USDC
const swap = await monei.evmExchange.swapTokenToToken({
  inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
  outputMint: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', // USDC
  amount: '1000',
  chainId: 56
});

Best Practices

Always Get Quote

Get fresh quote before each swap (quotes expire in ~5 min)

Check Price Impact

Avoid swaps with high price impact (>5%)

Set Slippage

Use appropriate slippage for market conditions

Monitor Gas

Factor gas costs into swap profitability

Use Cheap Networks

Polygon/BSC for small swaps, Ethereum for large

Test Small First

Test with small amount before large swaps

Troubleshooting

Error: Transaction reverted due to slippageCause: Actual output fell below minimum due to price movementSolution:
  • Increase slippage tolerance
  • Get fresh quote
  • Split into smaller trades
  • Try during less volatile periods
Error: Not enough liquidity for swapSolutions:
  • Reduce swap amount
  • Try different network
  • Use more liquid token pairs (USDT/USDC)
  • Check DEX liquidity on explorer
Error: Quote ID expired or invalidCause: Quotes are valid for ~5 minutesSolution:
  • Get fresh quote before swapping
  • Execute swap immediately after quote
  • Don’t reuse old quotes
Warning: Price impact > 5%Recommendations:
  • Split into multiple smaller swaps
  • Use different network with more liquidity
  • Wait for better liquidity
  • Consider limit orders (if available)

Next Steps

Wallet Operations

Manage your EVM wallet

Transactions

Learn about EVM transactions

Solana Swaps

Swap tokens on Solana

Networks

Explore supported networks