Uniswap – Initializing IUniswapV2Pair from msg.sender in Solidity

tokensuniswap

The Uniswap V2 docs provide an example flashswap contract here. The doc says:

For the sake of example, let's assume that we're dealing with a DAI/WETH pair, where DAI is token0 and WETH is token1.

On lines 33 & 34 the contract gets the token address using:

        address token0 = IUniswapV2Pair(msg.sender).token0();
        address token1 = IUniswapV2Pair(msg.sender).token1();
  1. What is happening when it calls IUniswapV2Pair(msg.sender)?
  2. How does it know which tokens we are interested in swapping? In other words what is returned when we call .token0() and .token1()? Is DAI and WETH token address always returned here?

Best Answer

So IUniswapV2Pair is a cast, that casts an address into an interface, in this case the IUniswapV2Pair interface. Doing this essentially makes all the functions inside of the interface easily callable with solidity syntax.

token0() and token1() are functions of all Uniswap Pairs. They will return different addresses of underlying tokens depending on what address you call it on, ie in this case your msg.sender.

Related Topic