In this guide, we will write a smart contract that calls
flash on a V3 pool and swaps the full amount withdrawn of
token1 in the corresponding pools with the same token pair - but different fee tiers. After the swap, the contract will pay back the first pool and transfer profits to the original calling address.
Flash transactions are an approach to transferring tokens on Ethereum that transfer token balances before the necessary conditions are met for those balances to be transferred. In the context of a swap, this would mean the output is sent from the swap before the input is received.
Uniswap V3 introduces a new function,
flash, within the Pool contract.
Flash withdraws a specified amount of both
token1 to the
recipient address. The withdrawn amount, plus the swap fees, will be due to the pool at the end of the transaction.
flash includes a fourth parameter,
data, which allows the caller to abi.encode any necessary data to be passed through the function and decoded later.
flash will withdraw the tokens, but how are they paid back? To understand this, we must look inside the flash function code. midway through the flash function, we see this:
This step calls the
FlashCallback function on
msg.sender - which passes the fee data needed to calculate the balances due to the pool, as well as any data encoded into the
In V3 there are three separate callback functions,
uniswapV3FlashCallback, each available to be overridden with custom logic. To write our arbitrage contract, we'll be calling
flash and overriding the
uniswapV3FlashCallback with the steps needed to finish executing our transaction.
Our first step is to inherit
PeripheryPayments, as we will use each in our logic. Note these two inherited contracts already extend many other contracts that we will be using, such as LowGasSafeMath which we attach, to types
Next, we declare an immutable public variable
swapRouter of type
We'll declare the constructor here, which is executed once when the contract is deployed. Our constructor hard codes the address of the V3 router, factory, and the address of weth9, the ERC-20 wrapper for ether.
the full import section and contract declaration: