深入 Uniswap V4 源码 - PathKey Library

adshao 发布于 2025-02-14 阅读 2591

本文介绍了PathKey库的结构体定义及其方法,特别是getPoolAndSwapDirection函数的实现。内容详尽,涵盖了结构体字段含义及如何计算交易池和方向的逻辑,是对Uniswap v4相关概念的深入理解。

PathKey Library

结构体定义

PathKey

struct PathKey {
    Currency intermediateCurrency;
    uint24 fee;
    int24 tickSpacing;
    IHooks hooks;
    bytes hookData;
}
  • intermediateCurrency:中间代币
  • fee:手续费
  • tickSpacing:池子 tick 间隔
  • hooks:Hooks 合约
  • hookData:Hooks 数据

方法定义

getPoolAndSwapDirection

根据输入代币和中间代币信息,计算交易池子和交易方向。

/// @notice Get the pool and swap direction for a given PathKey
/// @param params the given PathKey
/// @param currencyIn the input currency
/// @return poolKey the pool key of the swap
/// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
function getPoolAndSwapDirection(PathKey calldata params, Currency currencyIn)
    internal
    pure
    returns (PoolKey memory poolKey, bool zeroForOne)
{
    Currency currencyOut = params.intermediateCurrency;
    (Currency currency0, Currency currency1) =
        currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);

    zeroForOne = currencyIn == currency0;
    poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks);
}

PoolKey 中介绍了 PoolKey 结构体,Uniswap v4 通过 currency0currency1feetickSpacinghooks 来唯一标识一个池子,其中,currency0 地址小于 currency1 地址。

因此,在 getPoolAndSwapDirection 中确定交易池子时,首先排序 currency0currency1,结合 feetickSpacinghooks,得到 poolKey

根据 currencyIn 是否等于 currency0,确定交易方向 zeroForOne,因为此时 currency0token0

该文章收录于
深入理解 Uniswap V4
72 订阅 15 篇内容

0 条评论