LibUniswapV3
Last updated
Last updated
This is a Solidity library called LibUniswapV3 that provides functions for swapping assets on Uniswap v3.
The swapUniswapV3
function is tailored for executing token swaps on Uniswap V3, a more advanced and flexible version of the Uniswap protocol. It begins by extracting key parameters from the input
byte array using assembly for efficiency, including the amount of the input token (amountIn
), recipient's address, pool address (poolAddress
), input and output token addresses (assetIn
and assetOut
), and the swap fee (fee
). A special data
byte array is prepared, embedding the assetIn
address, to be used in the swap call. The function then determines the swap direction (zeroForOne
) based on the order of the input and output assets. It executes the swap by calling the swap
method on the Uniswap V3 pool contract, passing parameters like the recipient, swap direction, input amount, and a price limit determined by the constants MIN_SQRT_RATIO
and MAX_SQRT_RATIO
. Finally, it calculates the output amount (amountOut
) based on the returned values from the swap, ensuring the correct output amount is obtained whether swapping for token 0 or token 1 in the pool.
Input
input
bytes memory
A byte array containing necessary swapping parameters.
Output
The amount received after swapping.
The uniswapV3SwapCallback
function is an internal callback function used in Uniswap V3 swaps, typically called by the Uniswap V3 pool contract during a swap operation. The function first checks if both amount0Delta
and amount1Delta
are non-positive, in which case it reverts the transaction as this indicates an invalid state. Then, it extracts the assetIn
address from the data
byte array using assembly for efficient memory access. Finally, the function transfers the appropriate amount of assetIn
(determined by whether amount0Delta
or amount1Delta
is positive) to the sender of the transaction (msg.sender
), fulfilling the liquidity requirements of the swap on Uniswap V3.
input
amount0Delta
int256
the changes in the amount of the first token involved in the swap
amount1Delta
int256
the changes in the amount of the second token involved in the swap
data
bytes memory
a byte array containing additional information needed for the callback.