> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monei.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# Token Swaps

> Swap tokens seamlessly across decentralized exchanges on EVM networks

## 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

<CardGroup cols={3}>
  <Card title="Native → Token" icon="right-long">
    Swap ETH/BNB/MATIC to any ERC-20 token
  </Card>

  <Card title="Token → Token" icon="arrow-right-arrow-left">
    Swap between any two ERC-20 tokens
  </Card>

  <Card title="Token → Native" icon="left-long">
    Swap ERC-20 tokens back to native currency
  </Card>
</CardGroup>

***

## Get Swap Quote

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

### Native to Token Quote

<CodeGroup>
  ```javascript Node.js theme={null}
  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.getNativeToTokenPrice({
    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));
  ```

  ```python Python theme={null}
  from monei import MoneiClient

  monei = MoneiClient(
      api_key=os.getenv('MONEI_API_KEY')
  )

  # Get quote
  quote = monei.evm_exchange.get_native_to_token_price(
      output_mint='0x55d398326f99059fF775485246999027B3197955',
      amount='0.1',
      chain_id=56
  )

  print(f'Quote ID: {quote.quote_id}')
  print(f'From: {quote.from_token.symbol} (Native)')
  print(f'To: {quote.to_token.symbol}')
  print(f'Input: {quote.from_amount}')
  print(f'Output: {quote.to_amount}')
  print(f'Rate: {quote.rate}')
  print(f'Min Output: {quote.min_to_amount}')
  print(f'Price Impact: {quote.price_impact}%')
  print(f'Gas Cost: ${quote.estimated_gas_usd}')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/price/native-to-token \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "outputMint": "0x55d398326f99059fF775485246999027B3197955",
      "amount": "0.1",
      "chainId": 56
    }'
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "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

<CodeGroup>
  ```javascript Node.js theme={null}
  // Get quote for USDT → USDC swap on BSC
  const quote = await monei.evmExchange.getTokenToTokenPrice({
    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 + '%');
  ```

  ```python Python theme={null}
  # Get token-to-token quote
  quote = monei.evm_exchange.get_token_to_token_price(
      input_mint='0x55d398326f99059fF775485246999027B3197955',
      output_mint='0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',
      amount='100',
      chain_id=56
  )

  print(f'Swap 100 USDT → USDC')
  print(f'Rate: {quote.rate}')
  print(f'Output: {quote.to_amount} USDC')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/price/token-to-token \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "inputMint": "0x55d398326f99059fF775485246999027B3197955",
      "outputMint": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
      "amount": "100",
      "chainId": 56
    }'
  ```
</CodeGroup>

### Token to Native Quote

<CodeGroup>
  ```javascript Node.js theme={null}
  // Get quote for USDT → BNB swap
  const quote = await monei.evmExchange.getTokenToNativePrice({
    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');
  ```

  ```python Python theme={null}
  # Get token-to-native quote
  quote = monei.evm_exchange.get_token_to_native_price(
      input_mint='0x55d398326f99059fF775485246999027B3197955',
      amount='100',
      chain_id=56
  )

  print(f'Swap 100 USDT → BNB')
  print(f'Rate: {quote.rate}')
  print(f'Output: {quote.to_amount} BNB')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/price/token-to-native \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "inputMint": "0x55d398326f99059fF775485246999027B3197955",
      "amount": "100",
      "chainId": 56
    }'
  ```
</CodeGroup>

***

## Execute Swap

### Swap Native to Token

<CodeGroup>
  ```javascript Node.js theme={null}
  // 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!');
  ```

  ```python Python theme={null}
  # Execute swap
  swap = monei.evm_exchange.swap_native_to_token(
      output_mint='0x55d398326f99059fF775485246999027B3197955',
      amount='0.1',
      amount_out='28',
      chain_id=56
  )

  print(f'Transaction Hash: {swap.tx_hash}')
  print(f'Explorer: https://bscscan.com/tx/{swap.tx_hash}')

  # Wait for confirmation
  monei.evm.wait_for_transaction(swap.tx_hash, 56)
  print('Swap completed!')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/native-to-token \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "outputMint": "0x55d398326f99059fF775485246999027B3197955",
      "amount": "0.1",
      "amountOut": "28",
      "chainId": 56
    }'
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "statusCode": 200,
  "message": "Swap executed successfully",
  "data": {
    "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
  }
}
```

### Swap Token to Token

<CodeGroup>
  ```javascript Node.js theme={null}
  // 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}`);
  ```

  ```python Python theme={null}
  # Execute token-to-token swap
  swap = monei.evm_exchange.swap_token_to_token(
      input_mint='0x55d398326f99059fF775485246999027B3197955',
      output_mint='0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d',
      amount='100',
      chain_id=56
  )

  print(f'Transaction Hash: {swap.tx_hash}')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/token-to-token \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "inputMint": "0x55d398326f99059fF775485246999027B3197955",
      "outputMint": "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",
      "amount": "100",
      "chainId": 56
    }'
  ```
</CodeGroup>

### Swap Token to Native

<CodeGroup>
  ```javascript Node.js theme={null}
  // 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}`);
  ```

  ```python Python theme={null}
  # Execute token-to-native swap
  swap = monei.evm_exchange.swap_token_to_native(
      input_mint='0x55d398326f99059fF775485246999027B3197955',
      amount='100',
      chain_id=56
  )

  print(f'Transaction Hash: {swap.tx_hash}')
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.monei.cc/api/v1/evm-exchange/token-to-native \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "inputMint": "0x55d398326f99059fF775485246999027B3197955",
      "amount": "100",
      "chainId": 56
    }'
  ```
</CodeGroup>

***

## Understanding Quote Details

### Key Quote Fields

| Field                | Description                                              |
| -------------------- | -------------------------------------------------------- |
| `quoteId`            | Unique identifier for this quote (valid for \~5 minutes) |
| `rate`               | Exchange rate (1 input token = X output tokens)          |
| `reverseRate`        | Reverse rate (1 output token = Y input tokens)           |
| `toAmount`           | Expected output amount                                   |
| `minToAmount`        | Minimum output after slippage (usually 0.5%)             |
| `priceImpact`        | How much this trade affects the market price             |
| `estimatedGas`       | Estimated gas cost in native token                       |
| `estimatedGasUsd`    | Estimated gas cost in USD                                |
| `liquidityAvailable` | Whether sufficient liquidity exists                      |
| `expiryTimestamp`    | When this quote expires (Unix timestamp)                 |

### Price Impact

Price impact shows how much your trade will move the market price:

| Price Impact | Interpretation   | Action                    |
| ------------ | ---------------- | ------------------------- |
| \< 1%        | Low impact       | Safe to proceed           |
| 1% - 3%      | Moderate impact  | Consider splitting trade  |
| 3% - 5%      | High impact      | Warning recommended       |
| > 5%         | Very high impact | Split into smaller trades |

<CodeGroup>
  ```javascript Node.js theme={null}
  // Check price impact before swapping
  const quote = await monei.evmExchange.getNativeToTokenPrice({
    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 + '%');
  }
  ```

  ```python Python theme={null}
  # Check price impact
  quote = monei.evm_exchange.get_native_to_token_price(
      output_mint=token_address,
      amount='1.0',
      chain_id=56
  )

  price_impact = float(quote.price_impact)

  if price_impact > 5:
      print('⚠️ WARNING: Very high price impact!')
      print('Consider splitting into smaller trades')
  elif price_impact > 3:
      print(f'⚠️ High price impact: {price_impact}%')
  elif price_impact > 1:
      print(f'ℹ️ Moderate price impact: {price_impact}%')
  else:
      print(f'✓ Low price impact: {price_impact}%')
  ```
</CodeGroup>

***

## Slippage Protection

Slippage is the difference between expected and actual output amounts.

**Default Slippage:** 0.5% (configurable)

<CodeGroup>
  ```javascript Node.js theme={null}
  // Calculate minimum output with custom slippage
  function calculateMinOutput(expectedOutput, slippagePercent = 0.5) {
    const slippage = 1 - (slippagePercent / 100);
    return (parseFloat(expectedOutput) * slippage).toFixed(6);
  }

  // Get price
  const quote = await monei.evmExchange.getNativeToTokenPrice({
    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
  });
  ```

  ```python Python theme={null}
  # Calculate min output with slippage
  def calculate_min_output(expected_output, slippage_percent=0.5):
      slippage = 1 - (slippage_percent / 100)
      return float(expected_output) * slippage

  # Get price
  quote = monei.evm_exchange.get_native_to_token_price(
      output_mint=token_address,
      amount='0.1',
      chain_id=56
  )

  # Calculate with 1% slippage
  min_output = calculate_min_output(quote.to_amount, 1.0)

  print(f'Expected: {quote.to_amount}')
  print(f'Min (1% slippage): {min_output}')
  print(f'Default Min (0.5%): {quote.min_to_amount}')
  ```
</CodeGroup>

**Recommended Slippage:**

| Market Condition   | Recommended Slippage |
| ------------------ | -------------------- |
| Stablecoin swaps   | 0.1% - 0.3%          |
| Normal volatility  | 0.5% - 1.0%          |
| High volatility    | 1.0% - 3.0%          |
| Very low liquidity | 3.0% - 5.0%          |

***

## Gas Optimization

### Network Comparison for Swaps

| Network      | Typical Swap Gas | USD Cost      | Best For             |
| ------------ | ---------------- | ------------- | -------------------- |
| **Polygon**  | \~200,000 gas    | $0.05 - $0.20 | Small/frequent swaps |
| **BSC**      | \~180,000 gas    | $0.50 - $2.00 | Medium swaps         |
| **Base**     | \~150,000 gas    | $1.00 - $3.00 | Fast execution       |
| **Arbitrum** | \~200,000 gas    | $1.00 - $5.00 | Balanced cost/speed  |
| **Optimism** | \~200,000 gas    | $0.50 - $3.00 | L2 efficiency        |
| **Ethereum** | \~150,000 gas    | $30 - $100    | Large swaps only     |

### Optimize Swap Costs

<CodeGroup>
  ```javascript Node.js theme={null}
  // 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.getTokenToTokenPrice({
          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}`);
  ```

  ```python Python theme={null}
  # Compare networks
  async def find_best_network(token_in, token_out, amount):
      networks = [
          {'chain_id': 56, 'name': 'BSC'},
          {'chain_id': 137, 'name': 'Polygon'},
          {'chain_id': 8453, 'name': 'Base'},
          {'chain_id': 42161, 'name': 'Arbitrum'}
      ]
      
      quotes = []
      
      for network in networks:
          try:
              quote = monei.evm_exchange.get_token_to_token_price(
                  input_mint=token_in,
                  output_mint=token_out,
                  amount=amount,
                  chain_id=network['chain_id']
              )
              
              quotes.append({
                  'network': network['name'],
                  'chain_id': network['chain_id'],
                  'output': float(quote.to_amount),
                  'gas_cost_usd': float(quote.estimated_gas_usd),
                  'net_output': float(quote.to_amount) - float(quote.estimated_gas_usd)
              })
          except Exception as e:
              print(f"{network['name']}: Not available")
      
      # Sort by net output
      quotes.sort(key=lambda x: x['net_output'], reverse=True)
      
      return quotes[0]
  ```
</CodeGroup>

***

## Common Token Pairs

### Stablecoin Swaps (BSC)

<Tabs>
  <Tab title="USDT ↔ USDC">
    ```javascript theme={null}
    // USDT to USDC
    const swap = await monei.evmExchange.swapTokenToToken({
      inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
      outputMint: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', // USDC
      amount: '1000',
      chainId: 56
    });
    ```
  </Tab>

  <Tab title="BNB ↔ USDT">
    ```javascript theme={null}
    // BNB to USDT
    const swap = await monei.evmExchange.swapNativeToToken({
      outputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
      amount: '1.0', // 1 BNB
      amountOut: '287', // Expected USDT
      chainId: 56
    });
    ```
  </Tab>

  <Tab title="USDT ↔ BNB">
    ```javascript theme={null}
    // USDT to BNB
    const swap = await monei.evmExchange.swapTokenToNative({
      inputMint: '0x55d398326f99059fF775485246999027B3197955', // USDT
      amount: '287', // 287 USDT
      chainId: 56
    });
    ```
  </Tab>
</Tabs>

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Always Get Quote" icon="quote-left">
    Get fresh quote before each swap (quotes expire in \~5 min)
  </Card>

  <Card title="Check Price Impact" icon="chart-line">
    Avoid swaps with high price impact (>5%)
  </Card>

  <Card title="Set Slippage" icon="shield">
    Use appropriate slippage for market conditions
  </Card>

  <Card title="Monitor Gas" icon="gas-pump">
    Factor gas costs into swap profitability
  </Card>

  <Card title="Use Cheap Networks" icon="dollar-sign">
    Polygon/BSC for small swaps, Ethereum for large
  </Card>

  <Card title="Test Small First" icon="vial">
    Test with small amount before large swaps
  </Card>
</CardGroup>

***

## Troubleshooting

<AccordionGroup>
  <Accordion icon="circle-xmark" title="Swap Failed - Slippage Exceeded">
    **Error:** Transaction reverted due to slippage

    **Cause:** Actual output fell below minimum due to price movement

    **Solution:**

    * Increase slippage tolerance
    * Get fresh quote
    * Split into smaller trades
    * Try during less volatile periods
  </Accordion>

  <Accordion icon="circle-xmark" title="Insufficient Liquidity">
    **Error:** Not enough liquidity for swap

    **Solutions:**

    * Reduce swap amount
    * Try different network
    * Use more liquid token pairs (USDT/USDC)
    * Check DEX liquidity on explorer
  </Accordion>

  <Accordion icon="clock" title="Quote Expired">
    **Error:** Quote ID expired or invalid

    **Cause:** Quotes are valid for \~5 minutes

    **Solution:**

    * Get fresh quote before swapping
    * Execute swap immediately after quote
    * Don't reuse old quotes
  </Accordion>

  <Accordion icon="exclamation-triangle" title="High Price Impact">
    **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)
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Wallet Operations" icon="wallet" href="/evm-blockchain/wallet-operations">
    Manage your EVM wallet
  </Card>

  <Card title="Transactions" icon="arrow-right-arrow-left" href="/evm-blockchain/transactions">
    Learn about EVM transactions
  </Card>

  <Card title="Solana Swaps" icon="coins" href="/solana/token-swaps">
    Swap tokens on Solana
  </Card>

  <Card title="Networks" icon="network-wired" href="/core-concepts/networks">
    Explore supported networks
  </Card>
</CardGroup>
