スワップ
シングルスワップ
Uniswapでは、仮想通貨間のスワップ(通貨交換)を行うことができます。
例を通じて、Uniswapでスワップを行う2つの関数「swapExactInputSingle」と「swapExactOutputSingle」について説明していきます。
swapExactInputSingle
この関数は、特定の数量のトークンを別のトークンに交換する時に使います。
例えば、あなたが一定量のETHを持っており、それを可能な限り多く別のトークンに交換したい場合に使います。
この関数では、交換の詳細を「ExactInputSingleParams」というデータで指定し、Uniswapの「ISwapRouter」インターフェース内の「exactInputSingle」関数を呼び出します。
swapExactOutputSingle
この関数は、特定の数量のトークンを欲しいトークンに交換する時に使います。
例えば、最低限のトークン量で別のトークンと交換したい場合に使います。
この関数では、交換の詳細を「ExactOutputSingleParams」というデータで指定し、、Uniswapの「ISwapRouter」インターフェース内の「exactOutputSingle」関数を呼び出します。
この例では、特定のトークンのアドレスを直接コードに組み込んでいますが、実際の取引ではトランザクションごとに異なるトークンやプールを選択でき、柔軟性を持たせられます。
スマートコントラクトからUniswapを利用する場合、外部の価格情報が不可欠です。 これがないと、他のトレーダーによって取引が先取りされ、損失が生じる可能性があります。
この例は学習のためのものであり、実際に使用されているコードではありません。
コントラクトのセットアップ
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples we pass in the swap router as a constructor argument instead of inheriting it.
// More advanced example contracts will detail how to inherit the swap router safely.
// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.
ISwapRouter public immutable swapRouter;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
// For this example, we will set the pool fee to 0.3%.
uint24 public constant poolFee = 3000;
constructor(ISwapRouter _swapRouter) {
swapRouter = _swapRouter;
}
...上記コントラクトでは、トークンのコントラクトアドレスとプール内の手数料をハードコードしています。
正確なinputスワップ
スマートコントラクトからトークンを引き出してスワップを実行するには、以下のステップを踏みます。 以下のステップには、呼び出し元(ユーザー)からのトークン引き出しとUniswapプロトコルのルーターコントラクトへのトークン承認が含まれます。
-
トークン引き出しの承認 まず、呼び出し元(ユーザー)は、Uniswapプロトコルのルーターコントラクトに対して、ユーザーが所有しているトークンの引き出しを許可する必要があります。 これにより、Uniswapプロトコルがユーザーが所有するトークンを引き出して使用できるようになります。
-
Daiトークンの転送 次に、呼び出し元(ユーザー)のアドレスから一定数量のDaiをコントラクトに転送します。 この際、転送するDaiの数量を「
amount」として指定します。
...
/// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9
/// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router.
/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
/// @param amountIn The exact amount of DAI that will be swapped for WETH9.
/// @return amountOut The amount of WETH9 received.
function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
// msg.sender must approve this contract
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
...パラメーター
スワップを実行するには、ExactInputSingleParamsというデータを渡す必要があります。
以下はパラメータの説明です。
- tokenIn(入力トークン)
- スワップの時に交換元として使用するトークンのコントラクトアドレス。
- tokenOut(出力トークン)
- スワップの結果として得られるトークンのコントラクトアドレス。
- fee(手数料ティア)
- スワップを実行する適切なプールコントラクトを特定する、プールの手数料情報。
- recipient(受取アドレス)
- スワップによって得られたトークンが送信されるアドレス。
- deadline(有効期限)
- スワップが失敗する
unix時間。 - これにより、トランザクションが長期間保留されたり、価格が急激に変動した場合にトランザクションが実行されないように保護します。
- スワップが失敗する
- amountOutMinimum(最小出力トークン量)
- この値は
0に設定されていますが、本番環境では非常に重要。 - この値はSDKやオンチェーンの価格オラクルを使用して計算され、スワップによって得られるトークン量が一定の最小量以上であることを確認するために使用されます。
- これにより、フロントランニングや価格操作による悪意ある価格での取引から保護されます。
- この値は
- sqrtPriceLimitX96
- この値も
0に設定されていますが、本番環境では価格の制限を設定する。 - 価格の影響を制御したり、価格に関連する様々なメカニズムを設定したりする時に役立ちます。
- この値も
関数呼び出し
...
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
amountOut = swapRouter.exactInputSingle(params);
}
...正確なoutputスワップ
Exact Outputスワップは、取得したいトークン数量と最低限の入力トークン量を交換します。
例えば、ある数量の特定のトークンを得る必要がある場合、Exact Outputスワップを使用できます。 この場合、必要な出力トークン量を指定し、その出力量を確実に得るために最小でどれだけの入力トークンが必要かを計算します。 そして、その最小量以上の入力トークンを提供して、指定した出力量を確保します。
ただし、このスワップを使うと、スワップが実行された後に入力したトークンが余る可能性があるため、スワップの最後に余った入力トークンを呼び出し元のアドレスに返金します。 これにより、トークンの無駄を最小限に抑えることができます。
関数呼び出し
...
/// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH.
/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
/// @param amountOut The exact amount of WETH9 to receive from the swap.
/// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9.
/// @return amountIn The amount of DAI actually spent in the swap.
function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend the specified `amountInMaximum` of DAI.
// In production, you should choose the maximum amount to spend based on oracles or other data sources to achieve a better swap.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
amountIn = swapRouter.exactOutputSingle(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
}
}スワップコントラクト
スワップコントラクトの完成版は以下になります。
SwapExamples.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using
// `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity.
// More advanced example contracts will detail how to inherit the swap router safely.
ISwapRouter public immutable swapRouter;
// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
// For this example, we will set the pool fee to 0.3%.
uint24 public constant poolFee = 3000;
constructor(ISwapRouter _swapRouter) {
swapRouter = _swapRouter;
}
/// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9
/// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router.
/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
/// @param amountIn The exact amount of DAI that will be swapped for WETH9.
/// @return amountOut The amount of WETH9 received.
function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
// msg.sender must approve this contract
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
amountOut = swapRouter.exactInputSingle(params);
}
/// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH.
/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
/// @param amountOut The exact amount of WETH9 to receive from the swap.
/// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9.
/// @return amountIn The amount of DAI actually spent in the swap.
function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend the specifed `amountInMaximum` of DAI.
// In production, you should choose the maximum amount to spend based on oracles or other data sources to acheive a better swap.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
amountIn = swapRouter.exactOutputSingle(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
}
}
}マルチホップスワップ
以下はUniswapプロトコルのバージョン3(v3)で利用可能な複数のトークン間でスワップを行う方法を示すデモンストレーションコードです。
この例は学習のためのものであり、実際に使用されているコードではありません。
コントラクトのセットアップ
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples we pass in the swap router as a constructor argument instead of inheriting it.
// More advanced example contracts will detail how to inherit the swap router safely.
// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.
ISwapRouter public immutable swapRouter;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
// For this example, we will set the pool fee to 0.3%.
uint24 public constant poolFee = 3000;
constructor(ISwapRouter _swapRouter) {
swapRouter = _swapRouter;
}
...正確なinputマルチホップスワップ
以下のようなプロセスで実行されます。
-
特定の入力トークンに対して、指定された出力トークン量を得たいと考えます。
-
スワップの進行に従い、中間的なステップとして、異なるトークン間のスワップが行われることがあります。 これらの中間ステップでは、入力トークンから出力トークンへの変換が行われ、その都度手数料(
fee)がかかります。 -
最終的に、最大の出力量を得ることを目指して、複数の中間ステップを経て、出力トークンが得られます。
パラメーター
- path(パス)
- このパスは(
tokenAddress - fee - tokenAddress)のような形で、トークン間のスワップシーケンスを示します。 - 各要素は、トークンのコントラクトアドレスや手数料などを指定し、スワップの途中でどのトークンをどのようにスワップするかを示します。
- このパスは(
- recipient(受取アドレス)
- スワップで得た出力アセットを送信するアドレス。
- deadline(有効期限)
- トランザクションが失敗する
unix時間。 - これにより、トランザクションが長時間保留されたり、価格が急激に変動する場合にトランザクションが失敗するのを防ぎます。
- トランザクションが失敗する
- amountIn(入力アセットの量)
- 最初に提供される入力アセットの数量。
- この量をスワップの入力として使用します。
- amountOutMin(最小出力アセット量)
- トランザクションが成功するための条件となる、最小の出力アセット量。
- この値未満の場合、トランザクションは失敗します。
- 本番環境では、期待される価格を示すためにSDKを使用したり、高度なセキュリティを持つシステムではオンチェーン価格オラクルを利用することが一般的です。
関数の呼び出し
...
/// @notice swapExactInputMultihop swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool.
/// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output.
/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
/// @param amountIn The amount of DAI to be swapped.
/// @return amountOut The amount of WETH9 received after the swap.
function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) {
// Transfer `amountIn` of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
// Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.
// The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.
// Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0
});
// Executes the swap.
amountOut = swapRouter.exactInput(params);
}
...正確なoutputマルチホップスワップ
任意の入力トークンを固定された出力トークン量と交換する方法です。 このスワップ方法は、マルチホップスワップの中では一般的ではなく、特定の状況で使用されます。コードのほとんどは他のスワップ方法と同じですが、1つ注目すべき違いがあります。 それは、パス(取引の経路)は逆順にエンコードされる点です。 出力トークン量が固定されていて入力トークン量が可変なため、入力トークン量を求めるために逆順にする必要があります。
パラメーター
-
path(取引の経路)
- パスは、
tokenAddress Fee tokenAddressの順序でエンコードされますが、実際の実行では逆順に処理されます。 - これらの変数は、スワップシーケンス内の各プールコントラクトアドレスを計算するために必要です。
- マルチホップスワップルーターコードは、これらの変数を使用して正しいプールを自動的に見つけ、スワップシーケンス内の各プールで必要なスワップを実行します。
- パスは、
-
recipient(受取アドレス)
- 出力アセットの送り先アドレス。
- スワップによって得たアセットがどこに送信されるかを指定します。
-
deadline(有効期限)
- トランザクションが失敗する
unix時間。 - これにより、トランザクションが長時間保留されたり、価格が急激に変動する場合にトランザクションが失敗するのを防ぎます。
- トランザクションが失敗する
-
amountOut(出力アセットの希望量)
- WETH9などの取得したいトークンの量。
- このスワップは、指定された量のWETH9を得るために実行されます。
-
amountInMaximum(最大入力トークン量)
- DAIをWETH9の指定された
amountOutと交換するために必要となるDAIの最大量。 - このパラメータは、トランザクションが大幅な価格変動によって失敗するのを防ぐために設定されます。
- DAIをWETH9の指定された
関数呼び出し
...
/// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool.
/// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different in for exact output swaps.
/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
/// @param amountOut The desired amount of WETH9.
/// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9.
/// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut.
function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified `amountInMaximum` to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend `amountInMaximum`.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
// The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
// The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case USDC is the "shared" token.
// For an exactOutput swap, the first swap that occurs is the swap which returns the eventual desired token.
// In this case, our desired output token is WETH9 so that swap happens first, and is encoded in the path accordingly.
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI),
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum
});
// Executes the swap, returning the amountIn actually spent.
amountIn = swapRouter.exactOutput(params);
// If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransferFrom(DAI, address(this), msg.sender, amountInMaximum - amountIn);
}
}マルチホップコントラクト
SwapExamples.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using
// `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples, we purposefully pass in the swap router instead of inherit the swap router for simplicity.
// More advanced example contracts will detail how to inherit the swap router safely.
ISwapRouter public immutable swapRouter;
// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
// For this example, we will set the pool fee to 0.3%.
uint24 public constant poolFee = 3000;
constructor(ISwapRouter _swapRouter) {
swapRouter = _swapRouter;
}
/// @notice swapInputMultiplePools swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool.
/// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output.
/// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed.
/// @param amountIn The amount of DAI to be swapped.
/// @return amountOut The amount of WETH9 received after the swap.
function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) {
// Transfer `amountIn` of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
// Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps.
// The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools.
// Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9),
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0
});
// Executes the swap.
amountOut = swapRouter.exactInput(params);
}
/// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool.
/// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different in for exact output swaps.
/// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,
/// the calling address will need to approve for a slightly higher amount, anticipating some variance.
/// @param amountOut The desired amount of WETH9.
/// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9.
/// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut.
function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified `amountInMaximum` to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend `amountInMaximum`.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
// The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
// The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case USDC is the "shared" token.
// For an exactOutput swap, the first swap that occurs is the swap which returns the eventual desired token.
// In this case, our desired output token is WETH9 so that swap happpens first, and is encoded in the path accordingly.
ISwapRouter.ExactOutputParams memory params =
ISwapRouter.ExactOutputParams({
path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI),
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum
});
// Executes the swap, returning the amountIn actually spent.
amountIn = swapRouter.exactOutput(params);
// If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransferFrom(DAI, address(this), msg.sender, amountInMaximum - amountIn);
}
}
}