Skip to content

Encode_Uniswap_V3_Path

Elnaril edited this page Apr 1, 2024 · 1 revision

How to encode a Uniswap V3 path?

Let's say we want to encode the Uniswap V3 path to swap WETH for UNI on a 1% pool:

path = (
    '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',  # in token
    10000,  # 1% pool fee
    '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'  # out token
)

V3_SWAP_EXACT_IN

If we want to swap with an exact in_amount, we just need to write:

from uniswap_universal_router_decoder import RouterCodec
codec = RouterCodec()

encoded_path = codec.encode.v3_path("V3_SWAP_EXACT_IN", path)

The result is the following bytes:

b"\xc0*\xaa9\xb2#\xfe\x8d\n\x0e\\O'\xea\xd9\x08<ul\xc2\x00'\x10\x1f\x98@\xa8]Z\xf5\xbf\x1d\x17b\xf9%\xbd\xad\xdcB\x01\xf9\x84"

V3_SWAP_EXACT_OUT

Now, if we want to swap with an exact out_amount, we just need to write:

from uniswap_universal_router_decoder import RouterCodec
codec = RouterCodec()

encoded_path = codec.encode.v3_path("V3_SWAP_EXACT_OUT", path)

The result is the following bytes:

b"\x1f\x98@\xa8]Z\xf5\xbf\x1d\x17b\xf9%\xbd\xad\xdcB\x01\xf9\x84\x00'\x10\xc0*\xaa9\xb2#\xfe\x8d\n\x0e\\O'\xea\xd9\x08<ul\xc2"

Ending words

As you can see, V3 paths are super easy to build with this SDK. Despite that, it's not even a necessary step as the SDK handles it for you when you build the transaction data!

Clone this wiki locally