0

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?
1
  • The contract calling uniswapV2Call is Uniswap Pair for DAI-WETH, so msg.sender is a UniswapV2Pair contract.
    – Ismael
    Commented May 18, 2022 at 5:01

1 Answer 1

1

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.

4
  • Thanks @Bruce Darcy I'm a bit confused here - isn't msg.sender the address of my wallet which would be calling the function? In that case I don't have token0 and token1 defined...
    – bzak
    Commented May 17, 2022 at 21:41
  • Or should I replace msg.sender with the address of an existing pair defined on uniswap in which case why did the docs use msg.sender?
    – bzak
    Commented May 17, 2022 at 21:48
  • Msg.sender if whatever entity called that contract function. The control flow of a flashloan is as follows: You call uniswap pair contract asking for a flashloan Uniswap pair contract calls your contract (address of contract provided by you) executing the uniswapV2Call function. Inside that function, the msg.sender the the uniswap contract, because that contract is what called your contract
    – Bruce
    Commented May 18, 2022 at 19:06
  • In flashloans, the loaning contract calls your contract. You can then execute any code inside the uniswapV2Call function which it calls. Then execution passes back to the flash loan provider, where they check to make sure the funds are paid back. If not, they revert the transaction undoing everything your contract did (since they are one call level up on the stack, and a revert anywhere in a transaction undoes everything.) Thus, since the flash loan provider (uniswap pair in this case) is calling your contract, the msg.sender inside your contract will be the address of the flashloan provider.
    – Bruce
    Commented May 18, 2022 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.