The main component of Uniswap V4 is swap; it manages precise input/output swaps, optimizes gas through flash accounting, and moves price through liquidity ticks. Three main points:

Compared to their predecessors, V4 swaps are therefore both gas-optimized and capital-efficient. lets discuss further about swap and Flash Accounting & Locking.

How swap works on Uniswap v4

Uniswap v4 design flow

image.png

  1. User uses a periphery contract (SwapRouter, for example) to initiate a swap
  2. Periphery contract unlocks the PoolManager, triggering the manager to call unlockCallback on the periphery
  3. Inside the callback function, the periphery executes swap on the manager
  4. The manager makes sure the pool is valid and has been initialized
  5. The manager checks the hook address attached to the pool (if one does) and checks if it needs to run beforeSwap
  6. If yes, beforeSwap is called on the hook contract. If no, skip to next step.
  7. After beforeSwap is run, the actual swap is conducted inside the manager contract
  8. The manager then charges protocol fees, if any, and emits the Swap event.
  9. It again checks the hook address to see if afterSwap needs to run
  10. If yes, call afterSwap, else skip to next step
  11. Finally, the manager has an overall delta change of balances from the swap. This delta represents which token (and how much) is owed to the user, and which token (and how much) is owed to the manager