Skip to content

DEX Balance

The Stablecoin DEX allows you to hold token balances directly using the DEX contract. This eliminates the need for token transfers on every trade, significantly reducing gas costs for active traders and liquidity providers.

Why DEX Balances?

When you trade or provide liquidity on the DEX, constantly transferring tokens between your wallet and the DEX contract wastes gas. By maintaining a balance via the DEX contract, you can:

  • Save on gas costs - Avoid ERC-20 transfer costs for each trade
  • Trade more efficiently - Execute multiple swaps without transfers between each trade
  • Receive maker proceeds automatically - When your limit orders are filled, proceeds are credited to your DEX balance instead of requiring a transfer for each fill

Checking Your Balance

Use the DEX contract to view your balance of any token held on the DEX:

function balanceOf(
    address user,
    address token
) external view returns (uint128)
Example:
uint128 balance = exchange.balanceOf(msg.sender, USDC_ADDRESS);

Using Your DEX Balance

Each transaction that you authorize will use your DEX balance before using funds you approve from your wallet. When you execute a swap or place an order, the DEX contract automatically:

  1. Checks if you have sufficient balance in the DEX
  2. If insufficient, transfers the needed amount from your wallet to your DEX balance
  3. Uses your DEX balance for the operation

Withdrawing from the DEX

Transfer tokens from your DEX balance back to your wallet:

function withdraw(
    address token,
    uint128 amount
) external
Parameters:
  • token - The token address to withdraw
  • amount - The amount to withdraw
Example:
// Withdraw 1000 USDC from exchange to your wallet
exchange.withdraw(USDC_ADDRESS, 1000e6);

How Balances Work

When Swapping

  • Before swap: Exchange checks your balance, transfers from wallet if needed
  • After swap: Output tokens are transferred directly to your wallet (not kept on exchange)

When Placing Orders

  • On placement: Required tokens are debited from your exchange balance (or transferred from wallet if insufficient)
  • When filled: Proceeds are credited to your exchange balance
  • On cancellation: Unfilled portion is refunded to your exchange balance