# [ガイド編] Uniswap V3 ~フラッシュスワップ~

> flashを呼び出すには、最初の呼び出しに必要なflashパラメータと、コールバック時に渡したいパラメータが必要になります。

- URL: https://cardene.dev/books/uniswap-v3/bc062b
- 本: Uniswap V3大全 (https://cardene.dev/books/uniswap-v3.md)
- 章: 14 / 33
- 前の章: https://cardene.dev/books/uniswap-v3/56fdd1.md
- 次の章: https://cardene.dev/books/uniswap-v3/6b9f6b.md
- 公開日: 2023-09-12
- 更新日: 2023-09-12
- トピック: Blockchain
- タグ: solidity, ethereum, smartcontract, defi

# フラッシュスワップ

## はじめに

このスマートコントラクトは、V3プールで「**フラッシュ**」と呼ばれる操作を実行し、トークン0とトークン1を全額引き出します。
そして、同じトークンペアである別の手数料ティア（手数料率）を持つプールで、取り出したトークン0とトークン1を交換します。
交換が完了したら、最初のプールに元のトークンを返し、利益を元の呼び出し元アドレスに送金します。

### フラッシュトランザクションの概要

フラッシュトランザクションは、トークンの送金条件が満たされる前にトークンの残高を移動させる方法です。
スワップの文脈では、これは入力が受け取られる前に出力がスワップから送信されることを意味します。

:::message
通常のトークン送信では、送信元アカウントが一定の条件を満たす必要があります（例：十分な残高があること、トランザクションのガスが支払われていることなど）。
しかし、フラッシュトランザクションでは、これらの条件を待たずにトークンを送信できます。
つまり、トークンの送信条件が通常よりも柔軟で、トランザクションが即座に実行されることを可能にします。

スワップの場合、入力（トークンの提供）が受け取られる前に、出力（スワップの結果として得られるトークン）が送信されることがあります。
このアプローチは、トランザクションのオーバーヘッドを最小限に抑え、効率的なトークン交換を実現します。
:::

**Uniswap V3**では、Poolコントラクト内で新しい関数である「`flash`」が導入されています。
`flash`は、指定された量のトークン0とトークン1を指定した受け取りアドレスに引き出します。
引き出した量には、スワップ手数料も含まれます。
トランザクションの終了時には、引き出した量とスワップ手数料がプールに支払われることになります。
また、`flash`には「`data`」という4つ目のパラメータが含まれており、このパラメータを使用して、後で必要なデータを関数に渡し、後でデコードすることができます。

```solidity
function flash(
	address recipient,
	uint256 amount0,
	uint256 amount1,
	bytes calldata data
) external override lock noDelegateCall {
```

### フラッシュコールバック

トークンが`flash`によって引き出された後、それらのトークンがどのように返済されるかを理解するには、`flash`関数のコードを見る必要があります。
`flash`関数の一部に以下のようなコードがあります。

```solidity
IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);
```

この部分の処理では、`msg.sender`によって`FlashCallback`関数が呼び出されます。
これにより、プールに支払う残高を計算するために必要な手数料データが渡され、`data`パラメータにエンコードされた任意のデータも渡されます。

**Uniswap V3**では、カスタムロジックでオーバーライド可能な以下の3つの異なるコールバック関数があります。

- `uniswapV3SwapCallback`
- `uniswapV3MintCallback`
- `uniswapV3FlashCallback`

アービトラージコントラクトを書くためには、`flash`を呼び出し、**uniswapV3FlashCallback**をオーバーライドして、トランザクションの実行を完了するために必要なステップを実行します。

### V3コントラクトの継承

**IUniswapV3FlashCallback**と**PeripheryPayments**を継承してそれぞれの機能を利用します。
注意点としては、これらの継承元のスマートコントラクトも多くの他のスマートコントラクトを拡張していることがあり、例として**LowGasSafeMath**を利用して`uint256`および`int256`の型を拡張しています。

```solidity
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';

import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol';
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

contract PairFlash is IUniswapV3FlashCallback, PeripheryPayments {
	using LowGasSafeMath for uint256;
	using LowGasSafeMath for int256;

	ISwapRouter public immutable swapRouter;

	constructor(
		ISwapRouter _swapRouter,
		address _factory,
		address _WETH9
	) PeripheryImmutableState(_factory, _WETH9) {
		swapRouter = _swapRouter;
	}
```

## フラッシュ呼び出し

### 構造体のパラメーター

`flash`を呼び出すには、最初の呼び出しに必要な`flash`パラメータと、コールバック時に渡したいパラメータが必要になります。

`FlashParams`構造体には、プールから引き出したいトークンのアドレスと量、どのプールから引き出し、どのプールとスワップするかを決定するための3つのデータが含まれます。

```solidity
struct FlashParams {
	address token0;
	address token1;
	uint24 fee1;
	uint256 amount0;
	uint256 amount1;
	uint24 fee2;
	uint24 fee3;
}
```

`FlashCallbackData`構造体には、コールバック時に送信するデータが格納されます。
これは、**PoolAddress**ライブラリによって返された、手数料ティアが一致するソートされたトークンを表す`poolKey`が含まれます。

```solidity
struct FlashCallbackData {
	uint256 amount0;
	uint256 amount1;
	address payer;
	PoolAddress.PoolKey poolKey;
	uint24 poolFee2;
	uint24 poolFee3;
}
```

### プールキー

`Flashparams`（`params`としてメモリ上に宣言してある）から関連するパラメータを`poolKey`に代入します。

```solidity
function initFlash(FlashParams memory params) external {
	PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
}
```

次に、`pool`を[`IUniswapV3Pool`]型として宣言し、目的のプールのコントラクトで`flash`を呼び出せるようにします。

```solidity
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
```

### フラッシュ呼び出し

最後に、宣言したプールで`flash`を呼び出します。
最後のパラメーターに対して、`FlashCallbackDataをabi.encode`を実行します。
この`FlashCallbackData`はコールバックでデコードされ、トランザクションの次のステップを通知するために使用されます。

```solidity
pool.flash(
	address(this),
	params.amount0,
	params.amount1,
	abi.encode(
		FlashCallbackData({
			amount0: params.amount0,
			amount1: params.amount1,
			payer: msg.sender,
			poolKey: poolKey,
			poolFee2: params.fee2,
			poolFee3: params.fee3
		})
	)
);
```

関数全体のコードは以下になります。

```solidity
//fee1 is the fee of the pool from the initial borrow
//fee2 is the fee of the first pool to arb from
//fee3 is the fee of the second pool to arb from
struct FlashParams {
	address token0;
	address token1;
	uint24 fee1;
	uint256 amount0;
	uint256 amount1;
	uint24 fee2;
	uint24 fee3;
}

// fee2 and fee3 are the two other fees associated with the two other pools of token0 and token1
struct FlashCallbackData {
	uint256 amount0;
	uint256 amount1;
	address payer;
	PoolAddress.PoolKey poolKey;
	uint24 poolFee2;
	uint24 poolFee3;
}

function initFlash(FlashParams memory params) external {
	PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
	IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
	pool.flash(
		address(this),
		params.amount0,
		params.amount1,
		abi.encode(
			FlashCallbackData({
				amount0: params.amount0,
				amount1: params.amount1,
				payer: msg.sender,
				poolKey: poolKey,
				poolFee2: params.fee2,
				poolFee3: params.fee3
			})
		)
	);
}
```

## フラッシュコールバック

フラッシュ・コールバックをカスタム・ロジックでオーバーライドして、必要なスワップを実行し、元の`msg.sender`に利益を支払います。

`uniswapV3FlashCallback`関数を宣言し、オーバーライドします。

```solidity
function uniswapV3FlashCallback(
	uint256 fee0,
	uint256 fee1,
	bytes calldata data
) external override {
	FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));
```

各コールバックは、呼び出し元が本物の**V3**プールであることを検証する必要があります。
そうでない場合、プールコントラクトは、コールバック関数を操作するEOAを介した攻撃を受けやすくなります。

```solidity
CallbackValidation.verifyCallback(factory, decoded.poolKey);
```

アドレス型のローカル変数をtoken0とtoken1に割り当てて、ルーターがフラッシュからトークンとやり取りできるようにします。

```solidity
address token0 = decoded.poolKey.token0;
address token1 = decoded.poolKey.token1;

TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);
```

2つのスワップトランザクションで得られる最小のトークン量を計算します。
これらのトランザクションは、利益がない場合には実行しないようにするために、最低限の条件を設定しています。

- `amount1Min`
	- トークン1の最小必要量。
- `amount0Min`
	- トークン0の最小必要量。

これらの値は、計算されたトークンの数量に手数料を追加しています。
手数料は`fee0`と`fee1`として表され、それぞれトークン0とトークン1の手数料を示します。
トークンの最小量を手数料を考慮に入れて計算することで、利益がないトランザクションが実行されないようになります。

```solidity
uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);
```

### スワップの開始

```solidity
uint256 amountOut0 =
	swapRouter.exactInputSingle(
	ISwapRouter.ExactInputSingleParams({
		tokenIn: token1,
		tokenOut: token0,
		fee: decoded.poolFee2,
		recipient: address(this),
		deadline: block.timestamp + 200,
		amountIn: decoded.amount1,
		amountOutMinimum: amount0Min,
		sqrtPriceLimitX96: 0
	})
);
```

上記のコードは最初のスワップトランザクションを呼び出す部分です。
この呼び出しでは、ルーターインターフェースコントラクトの`exactInputSingle`関数を使用しています。
この呼び出しでは、`amount0In`を最小の取引トークン量（最小アウトプット）として使用し、スワップの戻り値を`amountOut0`に格納しています。

以下の2つの新しい機能が導入されています。

- `sqrtPriceLimitX96`
	- スワップがプールの価格を変更できる範囲を制限します。
	- 価格は常にトークン0をトークン1との比率で表す形式でプールコントラクトに格納されます。
	- この引数は、ユーザーが特定の価格までスワップを行いたい場合に便利です。
	- この例では、この引数を無効にするために`0`に設定します。

- `deadline`
	- トランザクションがリバート（無効になる）するタイムスタンプです。
	- これにより、トランザクションが長時間保留された場合に価格環境が急激に変動することからトランザクションを保護します。
	- この例では、シンプルさのためにだいぶ先の将来のタイムスタンプに設定します。

このスワップトランザクションでは、最初に元のプールから引き出した`amount1`を、最大可能なアウトプット量に交換するための固定の入力として使用します。

:::message
元々持っていたトークン1を、最大限のトークン0に交換しようとしています。
:::

この関数呼び出しは、前回のトークンペアで決定されたプールに対して実行されます。
ただし、手数料ティアと呼ばれるトレードプールの種類があり、このスワップでは手数料ティアのリストで次にある手数料ティアで実行されます。

:::message
手数料ティアは手数料率が異なるトレードプールのことで、低い手数料ティアから高い手数料ティアまで複数の種類があります。

前回のトークンペアに基づいて、現在の手数料ティア（例：0.05%手数料、0.3%手数料、1%手数料など）が決定され、その手数料ティアのプールでトークンを交換することになります。手数料ティアごとに手数料率が異なり、トレードのコストや収益に影響します。
したがって、このスワップは現在の手数料ティアに従ってトークンを交換し、手数料の違いを考慮しています。
:::

```solidity
uint256 amountOut1 = swapRouter.exactInputSingle(
	ISwapRouter.ExactInputSingleParams({
		tokenIn: token0,
		tokenOut: token1,
		fee: decoded.poolFee3,
		recipient: address(this),
		deadline: block.timestamp + 200,
		amountIn: decoded.amount0,
		amountOutMinimum: amount1Min,
		sqrtPriceLimitX96: 0
	})
);
```

上記のコードは、2つ目のスワップトランザクションを設定する部分です。
このスワップでは、最後の手数料ティア（**fee tier**）を使用し、元のプールから引き出した`amount0`をトークンの取引に使います。

:::message
このスワップは以下のステップを実行します。

1. **最後の手数料ティア（fee tier）を選択します**
前回のスワップでは、異なる手数料率のプールでトークンを交換しましたが、今回は最後の手数料ティアを使用します。
これにより、最後の手数料率のプールでトークンを交換することになります。

2. **元のプールから引き出したamount0を使用**
以前に引き出したトークン0（`amount0`）を、このスワップトランザクションの入力として利用します。
つまり、元のプールから得たトークン0を、このスワップでトークン1に交換しようとしています。

このように、2つ目のスワップトランザクションは最後の手数料ティアのプールで行われ、元のプールから引き出したトークン0を交換対象としています。
これにより、最適なトークン交換を行い、利益を確保しようとしています。
:::

### プールからの返済

元のプールに対して`flash`トランザクションの返済を行うために、まずプールに支払う残高を計算し、ルーターがコントラクト内のトークンをプールに戻すために承認を行います。
以下のコードは、このプロセスを実行する部分です。

```solidity
uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

TransferHelper.safeApprove(token0, address(this), amount0Owed);
TransferHelper.safeApprove(token1, address(this), amount1Owed);
```

:::message
1. **`amount0Owed`および`amount1Owed`の計算**
元のプールに支払うべきトークンの残高を計算しています。
これには、以前のスワップトランザクションで計算した`amount0`および`amount1`に、それぞれの手数料（`fee0`と`fee1`）を加えます。つ

2. **承認の設定**
次に、計算した残高を元のプールに戻すために、ルーターに対してコントラクト内のトークンを転送する権限を与えるための承認を設定します。
これは、`TransferHelper.safeApprove`を使用して行われます。
トークン0およびトークン1に対して、それぞれの支払い残高（`amount0Owed`と`amount1Owed`）をコントラクト自体に承認することで、ルーターがこれらのトークンをプールに戻すことができるようになります。

このプロセスにより、元のプールへの支払い残高が計算され、ルーターがトークンを正確に返済できるようになります。
:::

トークンに支払う残高がある場合、シンプルなロジックを使用して`pay`関数を呼び出します。
この時に注意すべきなのは、コールバック関数は`internal`としてマークされていますが、プール自体によって呼び出されているため`pay`関数を呼び出すことができるということです。

```solidity
if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);
```

:::message
1. **`amount0Owed`および`amount1Owed`の確認**
まず、トークン0およびトークン1に支払うべき残高（`amount0Owed`と`amount1Owed`）が`0`でないか確認します。
もし残高が`0`でなければ、支払う必要があることを示します。

2. **`pay`関数の呼び出し**
残高が`0`でない場合、`pay`関数を呼び出します。
この関数はトークンの支払いを行うために使用されます。
トークン0またはトークン1（`token0`と`token1`）に対して、残高（`amount0Owed`と`amount1Owed`）を指定し、支払いを行います。
この呼び出しにより、トークンに対する支払いが実行されます。

このコードは、トークンに支払うべき残高がある場合に、`pay`関数を使用して支払いを行うシンプルなロジックを示しています。
:::

利益を支払うために、`initFlash`関数を実行し、`flash`トランザクションをトリガーし、その後コールバックの呼び出し元である`msg.sender`に対して利益を支払います。

```solidity
if (amountOut0 > amount0Owed) {
	uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

	TransferHelper.safeApprove(token0, address(this), profit0);
	pay(token0, address(this), decoded.payer, profit0);
}

if (amountOut1 > amount1Owed) {
	uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
	TransferHelper.safeApprove(token0, address(this), profit1);
	pay(token1, address(this), decoded.payer, profit1);
}
```

:::message
1. **`amountOut0`および`amountOut1`の確認**
まず、トークン0とトークン1の利益（`amountOut0`と`amountOut1`）が、それぞれトークン0とトークン1に支払うべき残高（`amount0Owed`と`amount1Owed`）よりも大きいか確認します。
これにより利益が発生しているかどうかを確認できます。

2. **利益の計算**
利益が発生している場合、利益を計算します。
具体的には、`amountOut0`から`amount0Owed`を引いて、トークン0の利益（`profit0`）を計算し、`amountOut1`から`amount1Owed`を引いて、トークン1の利益（`profit1`）を計算します。

3. **承認と支払い**
利益が発生している場合、トークン0とトークン1に対して利益を承認（`safeApprove`）し、それから`pay`関数を使用して元の`initFlash`関数の呼び出し元である`decoded.payer`に対して利益を支払います。
:::


### 関数全体のコード

:::details uniswapV3FlashCallback
```solidity
function uniswapV3FlashCallback(
	uint256 fee0,
	uint256 fee1,
	bytes calldata data
) external override {
	FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));
	CallbackValidation.verifyCallback(factory, decoded.poolKey);

	address token0 = decoded.poolKey.token0;
	address token1 = decoded.poolKey.token1;

	TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
	TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);

	// profitable check
	// exactInputSingle will fail if this amount not met
	uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
	uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);

	// call exactInputSingle for swapping token1 for token0 in pool w/fee2
	uint256 amountOut0 =
	swapRouter.exactInputSingle(
		ISwapRouter.ExactInputSingleParams({
			tokenIn: token1,
			tokenOut: token0,
			fee: decoded.poolFee2,
			recipient: address(this),
			deadline: block.timestamp + 200,
			amountIn: decoded.amount1,
			amountOutMinimum: amount0Min,
			sqrtPriceLimitX96: 0
		})
	);

	// call exactInputSingle for swapping token0 for token 1 in pool w/fee3
	uint256 amountOut1 =
	swapRouter.exactInputSingle(
		ISwapRouter.ExactInputSingleParams({
			tokenIn: token0,
			tokenOut: token1,
			fee: decoded.poolFee3,
			recipient: address(this),
			deadline: block.timestamp + 200,
			amountIn: decoded.amount0,
			amountOutMinimum: amount1Min,
			sqrtPriceLimitX96: 0
		})
	);

	// end up with amountOut0 of token0 from first swap and amountOut1 of token1 from second swap
	uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
	uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

	TransferHelper.safeApprove(token0, address(this), amount0Owed);
	TransferHelper.safeApprove(token1, address(this), amount1Owed);

	if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
	if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);

	// if profitable pay profits to payer
	if (amountOut0 > amount0Owed) {
		uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

		TransferHelper.safeApprove(token0, address(this), profit0);
		pay(token0, address(this), decoded.payer, profit0);
	}
	if (amountOut1 > amount1Owed) {
		uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
		TransferHelper.safeApprove(token0, address(this), profit1);
		pay(token1, address(this), decoded.payer, profit1);
	}
}
```
:::

## コントラクト全体

:::details PairFlash.sol
```solidity
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';

import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol';
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';

/// @title Flash contract implementation
/// @notice An example contract using the Uniswap V3 flash function
contract PairFlash is IUniswapV3FlashCallback, PeripheryImmutableState, PeripheryPayments {
    using LowGasSafeMath for uint256;
    using LowGasSafeMath for int256;

    ISwapRouter public immutable swapRouter;

    constructor(
        ISwapRouter _swapRouter,
        address _factory,
        address _WETH9
    ) PeripheryImmutableState(_factory, _WETH9) {
        swapRouter = _swapRouter;
    }

    /// @param fee0 The fee from calling flash for token0
    /// @param fee1 The fee from calling flash for token1
    /// @param data The data needed in the callback passed as FlashCallbackData from `initFlash`
    /// @notice implements the callback called from flash
    /// @dev fails if the flash is not profitable, meaning the amountOut from the flash is less than the amount borrowed
    function uniswapV3FlashCallback(
        uint256 fee0,
        uint256 fee1,
        bytes calldata data
    ) external override {
        FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData));
        CallbackValidation.verifyCallback(factory, decoded.poolKey);

        address token0 = decoded.poolKey.token0;
        address token1 = decoded.poolKey.token1;

        TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0);
        TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1);

        // profitable check
        // exactInputSingle will fail if this amount not met
        uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1);
        uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0);

        // call exactInputSingle for swapping token1 for token0 in pool w/fee2
        uint256 amountOut0 =
            swapRouter.exactInputSingle(
                ISwapRouter.ExactInputSingleParams({
                    tokenIn: token1,
                    tokenOut: token0,
                    fee: decoded.poolFee2,
                    recipient: address(this),
                    deadline: block.timestamp,
                    amountIn: decoded.amount1,
                    amountOutMinimum: amount0Min,
                    sqrtPriceLimitX96: 0
                })
            );

        // call exactInputSingle for swapping token0 for token 1 in pool w/fee3
        uint256 amountOut1 =
            swapRouter.exactInputSingle(
                ISwapRouter.ExactInputSingleParams({
                    tokenIn: token0,
                    tokenOut: token1,
                    fee: decoded.poolFee3,
                    recipient: address(this),
                    deadline: block.timestamp,
                    amountIn: decoded.amount0,
                    amountOutMinimum: amount1Min,
                    sqrtPriceLimitX96: 0
                })
            );

        // end up with amountOut0 of token0 from first swap and amountOut1 of token1 from second swap
        uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0);
        uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1);

        TransferHelper.safeApprove(token0, address(this), amount0Owed);
        TransferHelper.safeApprove(token1, address(this), amount1Owed);

        if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed);
        if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed);

        // if profitable pay profits to payer
        if (amountOut0 > amount0Owed) {
            uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed);

            TransferHelper.safeApprove(token0, address(this), profit0);
            pay(token0, address(this), decoded.payer, profit0);
        }
        if (amountOut1 > amount1Owed) {
            uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed);
            TransferHelper.safeApprove(token0, address(this), profit1);
            pay(token1, address(this), decoded.payer, profit1);
        }
    }

    //fee1 is the fee of the pool from the initial borrow
    //fee2 is the fee of the first pool to arb from
    //fee3 is the fee of the second pool to arb from
    struct FlashParams {
        address token0;
        address token1;
        uint24 fee1;
        uint256 amount0;
        uint256 amount1;
        uint24 fee2;
        uint24 fee3;
    }
    // fee2 and fee3 are the two other fees associated with the two other pools of token0 and token1
    struct FlashCallbackData {
        uint256 amount0;
        uint256 amount1;
        address payer;
        PoolAddress.PoolKey poolKey;
        uint24 poolFee2;
        uint24 poolFee3;
    }

    /// @param params The parameters necessary for flash and the callback, passed in as FlashParams
    /// @notice Calls the pools flash function with data needed in `uniswapV3FlashCallback`
    function initFlash(FlashParams memory params) external {
        PoolAddress.PoolKey memory poolKey =
            PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1});
        IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
        // recipient of borrowed amounts
        // amount of token0 requested to borrow
        // amount of token1 requested to borrow
        // need amount 0 and amount1 in callback to pay back pool
        // recipient of flash should be THIS contract
        pool.flash(
            address(this),
            params.amount0,
            params.amount1,
            abi.encode(
                FlashCallbackData({
                    amount0: params.amount0,
                    amount1: params.amount1,
                    payer: msg.sender,
                    poolKey: poolKey,
                    poolFee2: params.fee2,
                    poolFee3: params.fee3
                })
            )
        );
    }
}
```
:::
