In the following part, we will override the flash callback with our custom logic to execute the desired swaps and pay the profit to the original msg.sender.
Declare the algebraFlashCallback function and override it.
functionalgebraFlashCallback(uint256 fee0,uint256 fee1,bytescalldata data ) externaloverride {
Declare a variable decoded in memory and assign it to the
Each callback must be checked and verified to make sure that the callback comes from a real pool. Without this, the pool contract will be vulnerable to an attack through an EOA manipulating the callback function.
This time, we are using the previously declared amount0In as the minimum amount out, and assigning the returned balance of the swap to amountOut0.
Most of the arguments of these functions have already been touched upon and explained, except for two new introductions:
sqrtPriceLimitX96: This value limits the price by which the swap can change the pool. Remember that the price is always shown and expressed in the pool contract as token1 in terms of token0. This is useful when the user wants to swap to a certain price – up until a specific price. For this case, we will set the value to 0, which will make the argument inactive.
deadline: this is the timestamp after which the transaction will revert, to protect the transaction from sudden changes in the pricing environment that can occur if the transaction is pending for too long. In this example, to make it simpler and more comfortable to further change, we will set it far in the future.
The first swap takes the amount1 that we have withdrawn from the original pool, and passes that amount as the input amount for a single swap that trades a fixed input for the max amount of possible output. It calls this function on the pool determined by our previous pair of tokens.
To pay the original pool back for the flash transaction, calculate the balance due to it in the first place, and then approve the router to transfer the tokens in our contract back to the pool.
Send the profits to the payer: the original msg.sender of the initFlash function, which executed the flash transaction and in turn triggered the callback.