Skip to content
Back to search

uniswap-universal-router-decoder

Uniswap Universal Router SDK - Decode and Encode Transactions - Uniswap V2, V3 & V4

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/elnaril--uniswap-universal-router-decoder/badge.svg)](/listings/elnaril--uniswap-universal-router-decoder)

HTML

<a href="/listings/elnaril--uniswap-universal-router-decoder"><img src="/api/listings/elnaril--uniswap-universal-router-decoder/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

A good practice is to use [Python virtual environments](https://python.readthedocs.io/en/latest/library/venv.html), here is a [tutorial](https://www.freecodecamp.org/news/how-to-setup-virtual-environments-in-python/).

The library can be pip installed from [pypi.org](https://pypi.org/project/uniswap-universal-router-decoder/) as usual:

# update pip to latest version if needed
pip install -U pip

# install the decoder from pypi.org
pip install uniswap-universal-router-decoder

To install it from source:

pip install .

or for contributors:

pip install -e '.[mcp]' --group dev

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,052 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Uniswap Universal Router Decoder & Encoder
  2. <!-- mcp-name: io.github.Elnaril/uniswap-universal-router-decoder -->
  3. > Many thanks to **everyone** who has ☕️ [offered some **coffees**!](https://github.com/Elnaril/uniswap-universal-router-decoder/discussions/11) ☕️
  4. > or ⭐ [**starred** this project!](https://github.com/Elnaril/uniswap-universal-router-decoder/stargazers) ⭐
  5. > It is **greatly** appreciated! :)
  6. ---
  7. <p align="center">
  8. <img width="75%" src="https://raw.githubusercontent.com/Elnaril/uniswap-universal-router-decoder/master/python_uniswap_universal_router_sdk_small.jpg">
  9. </p>
  10. ---
  11. #### Project Information
  12. [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/uniswap-universal-router-decoder)](https://pypi.org/project/uniswap-universal-router-decoder/)
  13. [![GitHub release (latest by date)](https://img.shields.io/github/v/release/Elnaril/uniswap-universal-router-decoder)](https://github.com/Elnaril/uniswap-universal-router-decoder/releases)
  14. [![PyPi Repository](https://img.shields.io/badge/repository-pipy.org-blue)](https://pypi.org/project/uniswap-universal-router-decoder/)
  15. [![GitHub](https://img.shields.io/github/license/Elnaril/uniswap-universal-router-decoder)](https://github.com/Elnaril/uniswap-universal-router-decoder/blob/master/LICENSE)
  16. [![Uniswap Universal Router Decoder MCP on mcprush](https://mcprush.com/badge/uniswap-universal-router-decoder-mcp/score.svg)](https://mcprush.com/to/uniswap-universal-router-decoder-mcp?ref=badge)
  17. #### Code Quality
  18. [![Tests & Lint](https://github.com/Elnaril/uniswap-universal-router-decoder/actions/workflows/tests.yml/badge.svg)](https://github.com/Elnaril/uniswap-universal-router-decoder/actions/workflows/tests.yml)
  19. [![CodeQL](https://github.com/elnaril/uniswap-universal-router-decoder/workflows/CodeQL/badge.svg)](https://github.com/Elnaril/uniswap-universal-router-decoder/actions/workflows/github-code-scanning/codeql)
  20. [![Test Coverage](https://img.shields.io/badge/dynamic/json?color=blueviolet&label=coverage&query=%24.totals.percent_covered_display&suffix=%25&url=https%3A%2F%2Fraw.githubusercontent.com%2FElnaril%2Funiswap-universal-router-decoder%2Fmaster%2Fcoverage.json)](https://github.com/Elnaril/uniswap-universal-router-decoder/blob/master/coverage.json)
  21. [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
  22. [![Type Checker: basedpyright](https://img.shields.io/badge/%20type%20checker-basedpyright-%231674b1?style=flat&labelColor=ef8336)](https://docs.basedpyright.com/)
  23. [![Linter: flake8](https://img.shields.io/badge/%20linter-flake8-%231674b1?style=flat&labelColor=ef8336)](https://flake8.pycqa.org/en/latest/)
  24. ---
  25. ## Release Notes
  26. See the [release notes page](https://github.com/Elnaril/uniswap-universal-router-decoder/wiki/Release_Notes)
  27. ### v4.0.0 - breaking changes
  28. - Update COMMAND_TYPE_MASK to 0x7f to match UR
  29. - Add support for the PAY_PORTION_FULL_PRECISION command (0x07)
  30. - Add support for the BALANCE_CHECK_ERC20 command (0x0e)
  31. - Add support for the V3_POSITION_MANAGER_PERMIT command (0x11)
  32. - Add support for the V3_POSITION_MANAGER_CALL command (0x12)
  33. - Add support for the EXECUTE_SUB_PLAN command (0x21)
  34. - Add `revert_on_fail` to the encoder methods for the commands whose failure the UR can tolerate
  35. - Capture the bytes some callers append after the UR arguments as `trailing_data`, and re-append them when rebuilding
  36. the calldata, so a decoded call can be rebuilt byte-for-byte
  37. - Make the chained function builders public and expose the `encoder` & `decoder` modules
  38. - Reduce CI time
  39. - Add a `publish.yml` GitHub Actions workflow that automatically publishes the package to PyPI and the MCP Registry with OIDC
  40. Trusted Publishing
  41. - Agent-friendly changes:
  42. - Add `Encoder.function_input()` / `AsyncEncoder.function_input()` to rebuild the calldata from a decoded call
  43. - Add `decoded_input_to_dict()` and `transaction_to_dict()` to render the decoder output as JSON-friendly dicts
  44. - Add the `ur-decode` and `ur-encode` command line tools, including `ur-encode v3-path` and its `encode_v3_path` MCP
  45. counterpart
  46. - Add the `ur-mcp` MCP server (optional `mcp` extra) so AI agents can drive the codec, including `encode_calldata`
  47. to rebuild the calldata from a decoded call
  48. - Annotate the MCP tools as read-only so a host can auto-approve them, and give them human-readable titles
  49. - The command descriptions (`ur-encode list` / `describe` and the `list_commands` / `describe_command` MCP tools) now
  50. describe the decoded call format and its ABI parameters, instead of the encoder methods
  51. - Add the MCP Registry metadata (`server.json`) to make the `ur-mcp` server discoverable
  52. - Add `AGENTS.md` and `llms.txt` for AI agents, plus a `mcp` PyPI keyword
  53. - Add `tests/test_version_consistency.py` to keep the packaging version, `server.json` and the README `mcp-name:`
  54. marker in sync
  55. ---
  56. ## Overview and Points of Attention
  57. The object of this library is to decode & encode transactions sent to the Uniswap Universal Router (UR)
  58. on Ethereum Mainnet, though it would work on any compatible chain where the UR is deployed. See Version Mapping below.
  59. This Python SDK is based on, and intended to be used with [web3.py](https://github.com/ethereum/web3.py)
  60. The target audience is Python developers who are familiar with the Ethereum blockchain concepts and web3.py, and how DEXes work.
  61. The same codec is also available without Python, through the `ur-decode` / `ur-encode` command line tools and the optional
  62. `ur-mcp` MCP server (see "Command line interface" and "MCP server" below): both print JSON, so shell scripts and AI
  63. agents can drive it too.
  64. ⚠ Before using this library, ensure you are familiar with general blockchain concepts. The Python API also expects
  65. [web3.py](https://github.com/ethereum/web3.py) knowledge in particular.
  66. ⚠ Not all UR functions supported by this SDK are available through the CLI or MCP tools:
  67. run `ur-encode list` and look for the "rebuildable" flag.
  68. ### List of supported Uniswap Universal Router Functions
  69. | Command Id | Universal Router Function | Underlying Action - Function | Supported |
  70. |-------------|-----------------------------|------------------------------|:---------:|
  71. | 0x00 / 0 | V3_SWAP_EXACT_IN | | ✅ |
  72. | 0x01 / 1 | V3_SWAP_EXACT_OUT | | ✅ |
  73. | 0x02 / 2 | PERMIT2_TRANSFER_FROM | | ✅ |
  74. | 0x03 / 3 | PERMIT2_PERMIT_BATCH | | ✅ |
  75. | 0x04 / 4 | SWEEP | | ✅ |
  76. | 0x05 / 5 | TRANSFER | | ✅ |
  77. | 0x06 / 6 | PAY_PORTION | | ✅ |
  78. | 0x07 / 7 | PAY_PORTION_FULL_PRECISION | | ✅ |
  79. | 0x08 / 8 | V2_SWAP_EXACT_IN | | ✅ |
  80. | 0x09 / 9 | V2_SWAP_EXACT_OUT | | ✅ |
  81. | 0x0a / 10 | PERMIT2_PERMIT | | ✅ |
  82. | 0x0b / 11 | WRAP_ETH | | ✅ |
  83. | 0x0c / 12 | UNWRAP_WETH | | ✅ |
  84. | 0x0d / 13 | PERMIT2_TRANSFER_FROM_BATCH | | ✅ |
  85. | 0x0e / 14 | BALANCE_CHECK_ERC20 | | ✅ |
  86. | 0x0f / 15 | placeholder | | N/A |
  87. | 0x10 / 16 | V4_SWAP | | ✅ |
  88. | | | 0x06 - SWAP_EXACT_IN_SINGLE | ✅ |
  89. | | | 0x07 - SWAP_EXACT_IN | ✅ |
  90. | | | 0x08 - SWAP_EXACT_OUT_SINGLE | ✅ |
  91. | | | 0x09 - SWAP_EXACT_OUT | ✅ |
  92. | | | 0x0b - SETTLE | ✅ |
  93. | | | 0x0c - SETTLE_ALL | ✅ |
  94. | | | 0x0e - TAKE | ✅ |
  95. | | | 0x0f - TAKE_ALL | ✅ |
  96. | | | 0x10 - TAKE_PORTION | ✅ |
  97. | 0x11 / 17 | V3_POSITION_MANAGER_PERMIT | | ✅ |
  98. | 0x12 / 18 | V3_POSITION_MANAGER_CALL | | ✅ |
  99. | 0x13 / 19 | V4_INITIALIZE_POOL | | ✅ |
  100. | 0x14 / 20 | V4_POSITION_MANAGER_CALL | | ✅ |
  101. | | | 0x02 - MINT_POSITION | ✅ |
  102. | | | 0x0b - SETTLE | ✅ |
  103. | | | 0x0d - SETTLE_PAIR | ✅ |
  104. | | | 0x0e - TAKE | ✅ |
  105. | | | 0x11 - TAKE_PAIR | ✅ |
  106. | | | 0x12 - CLOSE_CURRENCY | ✅ |
  107. | | | 0x13 - CLEAR_OR_TAKE | ✅ |
  108. | | | 0x14 - SWEEP | ✅ |
  109. | | | 0x15 - WRAP | ✅ |
  110. | | | 0x16 - UNWRAP | ✅ |
  111. | 0x15 - 0x20 | placeholders | | N/A |
  112. | 0x21 / 33 | EXECUTE_SUB_PLAN | | ✅ |
  113. | 0x22 - 0x3f | placeholders | | N/A |
  114. | 0x40 / 64 | ACROSS_V4_DEPOSIT_V3 | | ❌ |
  115. All the ✅ commands can be decoded and encoded. `V4_SWAP`, `V4_POSITION_MANAGER_CALL` and `EXECUTE_SUB_PLAN` can also
  116. be decoded, but they cannot be rebuilt from a decoded call (see "How to rebuild the calldata from a decoded call").
  117. ### Version Mapping
  118. Here is the mapping between the Universal Router versions and the SDK ones
  119. | UR Version | UR address on Ethereum | Python SDK version|
  120. |:----------:|------------|:-----------------:|
  121. | v2.1.2 | [`0x23617e59A5925b2A4Bf75d73ff6711cD0b29De85`](https://etherscan.io/address/0x23617e59A5925b2A4Bf75d73ff6711cD0b29De85) | v3.1.0 & v4.0.0|
  122. | v2.1.1 | [`0x4C82D1fBFe28C977cBB58D8C7FF8FCF9F70a2cCA`](https://etherscan.io/address/0x4C82D1fBFe28C977cBB58D8C7FF8FCF9F70a2cCA) | v3.0.0 |
  123. | v2 | [`0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af`](https://etherscan.io/address/0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af) | v2.0.0 & v2.1.0 |
  124. | v1.2 | [`0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD`](https://etherscan.io/address/0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD) | v0.9.0 to v1.2.1 |
  125. | v1 | [`0xEf1c6E67703c7BD7107eed8303Fbe6EC2554BF6B`](https://etherscan.io/address/0xEf1c6E67703c7BD7107eed8303Fbe6EC2554BF6B) | v0.8.0 |
  126. ---
  127. ## Installation
  128. A good practice is to use [Python virtual environments](https://python.readthedocs.io/en/latest/library/venv.html), here is a [tutorial](https://www.freecodecamp.org/news/how-to-setup-virtual-environments-in-python/).
  129. The library can be pip installed from [pypi.org](https://pypi.org/project/uniswap-universal-router-decoder/) as usual:
  130. ```bash
  131. # update pip to latest version if needed
  132. pip install -U pip
  133. # install the decoder from pypi.org
  134. pip install uniswap-universal-router-decoder
  135. ```
  136. To install it from source:
  137. ```bash
  138. pip install .
  139. ```
  140. or for contributors:
  141. ```bash
  142. pip install -e '.[mcp]' --group dev
  143. ```
  144. ---
  145. ## Usage
  146. The library exposes 2 classes, `RouterCodec` and `AsyncRouterCodec` with several public methods
  147. that can be used to decode or encode UR data and transactions.
  148. Both `RouterCodec` and `AsyncRouterCodec` are used the same way but either synchronously
  149. or asynchronously for the relevant parts, ie when doing rpc calls.
  150. ### How to instantiate the router codec
  151. 1/ When no need for rpc calls
  152. ```python
  153. from web3 import Web3
  154. from uniswap_universal_router_decoder import RouterCodec
  155. codec = RouterCodec()
  156. ```
  157. 2/ Using the URL of an rpc endpoint
  158. Sync code:
  159. ```python
  160. # Using an rpc endpoint
  161. from uniswap_universal_router_decoder import RouterCodec
  162. rpc_link = "https://..." # your rpc endpoint
  163. codec = RouterCodec(rpc_endpoint=rpc_link)
  164. ```
  165. Async code:
  166. ```python
  167. # Using an rpc endpoint
  168. from uniswap_universal_router_decoder import AsyncRouterCodec
  169. rpc_link = "https://..." # your rpc endpoint
  170. codec = AsyncRouterCodec(rpc_endpoint=rpc_link)
  171. ```
  172. 3/ Using a Web3/AsyncWeb3 instance
  173. Sync code:
  174. ```python
  175. # Using a web3 instance
  176. from web3 import Web3
  177. from uniswap_universal_router_decoder import RouterCodec
  178. w3 = Web3(...) # your Web3 instance
  179. codec = RouterCodec(w3=w3)
  180. ```
  181. Async code:
  182. ```python
  183. # Using an AsyncWeb3 instance
  184. from web3 import AsyncWeb3
  185. from uniswap_universal_router_decoder import AsyncRouterCodec
  186. async_w3 = AsyncWeb3(...) # your AsyncWeb3 instance
  187. codec = AsyncRouterCodec(async_w3=async_w3)
  188. ```
  189. ### How to decode a Uniswap Universal Router transaction input
  190. To decode a transaction input, use the `decode.function_input()` method as follows:
  191. ```python
  192. from uniswap_universal_router_decoder import RouterCodec
  193. trx_input = "0x3593564c000000000000000000 ... 90095b5c4e9f5845bba" # the trx input to decode
  194. codec = RouterCodec()
  195. decoded_trx_input = codec.decode.function_input(trx_input)
  196. ```
  197. Example of decoded input returned by `decode.function_input()`:
  198. ```python
  199. (
  200. <Function execute(bytes,bytes[],uint256)>, # the UR function that executes all commands
  201. {
  202. 'commands': b'\x0b\x00', # the list of commands sent to the UR
  203. 'inputs': [ # the inputs used for each command
  204. (
  205. <Function WRAP_ETH(address,uint256)>, # the function corresponding to the first command
  206. { # and its parameters
  207. 'recipient': '0x0000000000000000000000000000000000000002', # code indicating the recipient of this command is the router
  208. 'amountMin': 4500000000000000000 # the amount in WEI to wrap
  209. },
  210. {
  211. 'revert_on_fail': True # flag indicating if the transaction must revert when this command fails
  212. },
  213. ),
  214. (
  215. <Function V3_SWAP_EXACT_IN(address,uint256,uint256,bytes,bool)>, # the function corresponding to the second command
  216. { # and its parameters
  217. 'recipient': '0x0000000000000000000000000000000000000001', # code indicating the sender will receive the output of this command
  218. 'amountIn': 4500000000000000000, # the exact amount sent
  219. 'amountOutMin': 6291988002, # the min amount expected of the bought token for the swap to be executed
  220. 'path': b"\xc0*\xaa9\xb2#\xfe\x8d\n\x0e\\O'\xea\xd9\x08<ul\xc2" # the V3 path (tokens + pool fees)
  221. b'\x00\x01\xf4\xa0\xb8i\x91\xc6!\x8b6\xc1\xd1\x9dJ.' # can be decoded with the method decode.v3_path()
  222. b'\x9e\xb0\xce6\x06\xebH',
  223. 'payerIsSender': False # a bool indicating if the input tokens come from the sender or are already in the UR
  224. },
  225. {
  226. 'revert_on_fail': True # flag indicating if the transaction must revert when this command fails
  227. },
  228. )
  229. ],
  230. 'deadline': 1678441619, # The deadline after which the transaction is no longer valid
  231. 'trailing_data': b'unix\x00\x00\x00\x00\x00\x0c' # optional tag some callers append; the UR ignores it
  232. }
  233. )
  234. ```
  235. `decode.function_input()` reports the bytes some callers append after the UR arguments as `trailing_data` (see the
  236. example above). Pass `find_trailing_data=False` to ignore them.
  237. > **Tip**: You can format the decoded input like above with this [Gedit plugin](https://github.com/Elnaril/gedit-plugin-collection?tab=readme-ov-file#prettifier) ;)
  238. ### How to decode a Uniswap Universal Router transaction
  239. It's also possible to decode the whole transaction, given its hash
  240. and providing the codec has been built with either a valid `Web3` instance or the link to a rpc endpoint.
  241. The decoder will get the transaction from the blockchain and decode it, along with its input data:
  242. ```python
  243. # sync code
  244. trx_hash = "0x52e63b7 ... 11b979dd9"
  245. decoded_transaction = codec.decode.transaction(trx_hash)
  246. ```
  247. ```python
  248. # async code
  249. trx_hash = "0x52e63b7 ... 11b979dd9"
  250. decoded_transaction = await codec.decode.transaction(trx_hash)
  251. ```
  252. ### How to encode/decode a Uniswap V3 swap path
  253. `RouterCodec` exposes two mirror methods: `encode.v3_path()` builds a Uniswap V3 path from the ordered tokens and the
  254. pool fees between them, and `decode.v3_path()` reads one back.
  255. ```python
  256. from uniswap_universal_router_decoder import RouterCodec
  257. codec = RouterCodec()
  258. fn_name = "V3_SWAP_EXACT_IN" # Or V3_SWAP_EXACT_OUT
  259. encoded_path = codec.encode.v3_path(fn_name, [token_in_address, 3000, token_out_address]) # bytes
  260. uniswap_v3_path = b"\xc0*\xaa9\xb2#\xfe\x8d\n\x0e ... \xd7\x89" # bytes or str hex
  261. decoded_path = codec.decode.v3_path(fn_name, uniswap_v3_path)
  262. ```
  263. `decode.v3_path()` returns a tuple, starting with the "in-token" and ending with the "out-token", with the pool fees
  264. between each pair. Both methods use that same order: `V3_SWAP_EXACT_OUT` reverses the path when encoding, and the
  265. decoder reverses it back.
  266. ### How to get the decoded data as JSON-friendly dicts
  267. The decoder returns rich Python objects (web3 contract functions, raw bytes, ...) that are not directly serialisable.
  268. Two helpers render that output as plain dicts/lists/strings, ready to be printed as JSON or sent to another system:
  269. - `decoded_input_to_dict()` takes the output of `decode.function_input()`
  270. - `transaction_to_dict()` takes the output of `decode.transaction()`
  271. ```python
  272. import json
  273. from uniswap_universal_router_decoder import RouterCodec, decoded_input_to_dict, transaction_to_dict
  274. codec = RouterCodec()
  275. # from the decoded input
  276. decoded_input = codec.decode.function_input(trx_input)
  277. print(json.dumps(decoded_input_to_dict(decoded_input), indent=2))
  278. # or from the decoded transaction
  279. decoded_transaction = codec.decode.transaction(trx_hash)
  280. print(json.dumps(transaction_to_dict(decoded_transaction), indent=2))
  281. ```
  282. Bytes are rendered as "0x"-prefixed hex strings, and each decoded command becomes a dict with a `command` name,
  283. its `params`, and a `revert_on_fail` flag:
  284. ```json
  285. {
  286. "function": "execute",
  287. "params": {
  288. "commands": "0x0b00",
  289. "inputs": [
  290. {
  291. "command": "WRAP_ETH",
  292. "params": {"recipient": "0x0000000000000000000000000000000000000002", "amountMin": 4500000000000000000},
  293. "revert_on_fail": true
  294. }
  295. ],
  296. "deadline": 1678441619
  297. }
  298. }
  299. ```
  300. ### How to encode
  301. The Uniswap Universal Router allows the chaining of several functions in the same transaction.
  302. This codec supports it (at least for supported functions) and exposes public methods that can be chained.
  303. The chaining starts with the `encode.chain()` method and ends with the `build()` one which returns the full encoded data to be included in the transaction.
  304. Below some examples of encoded data for one function and one example for 2 functions.
  305. Starting with v3.0.0, it is possible to start the chaining with `encode()` instead of `encode.chain()`, making the code a bit more concise.
  306. Default values for deadlines and expirations can be computed with the static methods `get_default_deadline()` and `get_default_expiration()` respectively.
  307. ```python
  308. from uniswap_universal_router_decoder import RouterCodec
  309. default_deadline = RouterCodec.get_default_deadline()
  310. default_expiration = RouterCodec.get_default_expiration()
  311. ```
  312. These 2 functions accept a custom duration in seconds as argument.
  313. `revert_on_fail` can be passed to the methods whose command the UR can tolerate failing: `permit2_permit()`,
  314. `permit2_permit_batch()`, `balance_check_erc20()`, `v3_position_manager_permit()`, `v3_decrease_liquidity()`,
  315. `v3_collect()`, `v3_burn()`, `v4_initialize_pool()`, `build_v4_posm_call()` and `execute_sub_plan()`. It defaults to
  316. `True`; set it to `False` to let the transaction continue if that command fails. The other methods don't accept it,
  317. because the UR ignores that flag for their command.
  318. ### How to rebuild the calldata from a decoded call
  319. As an alternative to chaining the encoder methods, `encode.function_input()` builds the calldata from the decoded form
  320. of an `execute` call. It is the mirror of `decode.function_input()`: where the decoder turns a function input into
  321. commands, this turns the decoded commands back into a function input, so a route can be decoded, edited, and re-encoded.
  322. The expected shape is the one produced by `decoded_input_to_dict()` (and by the `ur-decode` CLI and the MCP server):
  323. its `params.inputs` hold the commands, using the names and parameters the decoder reports (the Universal Router ABI
  324. names).
  325. ```python
  326. from uniswap_universal_router_decoder import RouterCodec, decoded_input_to_dict
  327. codec = RouterCodec()
  328. plan = decoded_input_to_dict(codec.decode.function_input(trx_input))
  329. # tweak the decoded route, then rebuild the calldata from it
  330. plan["params"]["inputs"][0]["params"]["amountMin"] = 2 * 10 ** 18
  331. encoded_data = codec.encode.function_input(plan)
  332. # then in your transaction dict:
  333. transaction["data"] = encoded_data
  334. ```
  335. The `function` key is optional and defaults to `execute`, and the `commands` bytes are ignored: the command list is
  336. rebuilt from the `inputs` entries. The `deadline` key is optional too; when it is absent, the plain
  337. `execute(bytes,bytes[])` form is used instead of `execute(bytes,bytes[],uint256)`.
  338. Some callers append a tag after the ABI-encoded arguments, which the UR ignores. The decoder reports it as
  339. `params.trailing_data`, and `encode.function_input()` re-appends it, so a decoded call can be rebuilt byte-for-byte.
  340. The chained builders take the same value as an optional `trailing_data` argument of `build()`, after `deadline`.
  341. Commands the decoder expands into structures (`V4_SWAP`, `V4_POSITION_MANAGER_CALL`, `EXECUTE_SUB_PLAN`) cannot be
  342. rebuilt this way and raise a `ValueError`.
  343. `revert_on_fail` is honoured only for the commands whose failure the UR can tolerate (`PERMIT2_PERMIT`,
  344. `PERMIT2_PERMIT_BATCH`, `BALANCE_CHECK_ERC20`, `V3_POSITION_MANAGER_PERMIT`, `V3_POSITION_MANAGER_CALL`,
  345. `V4_INITIALIZE_POOL`, `V4_POSITION_MANAGER_CALL`, `EXECUTE_SUB_PLAN`). For every other command the UR ignores the
  346. flag, so it is always cleared. The same applies to the encoder methods: those commands take a `revert_on_fail`
  347. argument (default `True`), the others do not.
  348. `AsyncRouterCodec` exposes the same method (`encode.function_input()`); it is synchronous, so no `await` is needed.
  349. ### How to encode a call to the Uniswap Universal Router function WRAP_ETH
  350. This function can be used to convert eth to weth using the UR.
  351. ```python
  352. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  353. codec = RouterCodec()
  354. encoded_data = codec.encode.chain().wrap_eth(FunctionRecipient.SENDER, amount_in_wei).build(1676825611) # to convert amount_in_wei eth to weth, and send them to the transaction sender.
  355. # then in your transaction dict:
  356. transaction["data"] = encoded_data
  357. # you can now sign and send the transaction to the UR
  358. ```
  359. ### How to encode a call to the Uniswap V2 function V2_SWAP_EXACT_IN
  360. This function can be used to swap tokens on a V2 pool. Correct allowances must have been set before sending such transaction.
  361. ```python
  362. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  363. codec = RouterCodec()
  364. encoded_data = codec.encode.chain().v2_swap_exact_in(
  365. FunctionRecipient.SENDER, # the output tokens are sent to the transaction sender
  366. amount_in, # in Wei
  367. min_amount_out, # in Wei
  368. [
  369. in_token_address, # checksum address of the token sent to the UR
  370. out_token_address, # checksum address of the received token
  371. ],
  372. ).build(timestamp) # unix timestamp after which the trx will not be valid any more
  373. # then in your transaction dict:
  374. transaction["data"] = encoded_data
  375. # you can now sign and send the transaction to the UR
  376. ```
  377. For more details, see this [tutorial](https://hackernoon.com/how-to-buy-a-token-on-the-uniswap-universal-router-with-python)
  378. ### How to encode a call to the Uniswap V2 function V2_SWAP_EXACT_OUT
  379. This function can be used to swap tokens on a V2 pool. Correct allowances must have been set before sending such transaction.
  380. ```python
  381. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  382. codec = RouterCodec()
  383. encoded_data = codec.encode.chain().v2_swap_exact_out(
  384. FunctionRecipient.SENDER,
  385. amount_out, # in Wei
  386. max_amount_in, # in Wei
  387. [
  388. in_token_address,
  389. out_token_address,
  390. ],
  391. ).build(timestamp) # unix timestamp after which the trx will not be valid any more
  392. # then in your transaction dict:
  393. transaction["data"] = encoded_data
  394. # you can now sign and send the transaction to the UR
  395. ```
  396. ### How to encode a call to the Uniswap V3 function V3_SWAP_EXACT_IN
  397. This function can be used to swap tokens on a V3 pool. Correct allowances must have been set before sending such transaction.
  398. ```python
  399. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  400. codec = RouterCodec()
  401. encoded_data = codec.encode.chain().v3_swap_exact_in(
  402. FunctionRecipient.SENDER,
  403. amount_in, # in Wei
  404. min_amount_out, # in Wei
  405. [
  406. in_token_address,
  407. pool_fee,
  408. out_token_address,
  409. ],
  410. ).build(timestamp) # unix timestamp after which the trx will not be valid any more
  411. # then in your transaction dict:
  412. transaction["data"] = encoded_data
  413. # you can now sign and send the transaction to the UR
  414. ```
  415. ### How to encode a call to the Uniswap V3 function V3_SWAP_EXACT_OUT
  416. This function can be used to swap tokens on a V3 pool. Correct allowances must have been set before sending such transaction.
  417. ```python
  418. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  419. codec = RouterCodec()
  420. encoded_data = codec.encode.chain().v3_swap_exact_out(
  421. FunctionRecipient.SENDER,
  422. amount_out, # in Wei
  423. max_amount_in, # in Wei
  424. [
  425. in_token_address,
  426. pool_fee,
  427. out_token_address,
  428. ],
  429. ).build(timestamp) # unix timestamp after which the trx will not be valid any more
  430. # then in your transaction dict:
  431. transaction["data"] = encoded_data
  432. # you can now sign and send the transaction to the UR
  433. ```
  434. ### How to encode a call to the Uniswap Universal Router function PERMIT2_PERMIT
  435. This function is used to give an allowance to the universal router via the Permit2 contract ([`0x000000000022D473030F116dDEE9F6B43aC78BA3`](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)).
  436. It is also necessary to approve the Permit2 contract using the token approve function.
  437. See this [tutorial](https://hackernoon.com/python-how-to-use-permit2-with-the-uniswap-universal-router)
  438. ```python
  439. from uniswap_universal_router_decoder import RouterCodec
  440. codec = RouterCodec()
  441. data, signable_message = codec.create_permit2_signable_message(
  442. token_address,
  443. amount, # max = 2**160 - 1
  444. expiration,
  445. nonce, # Permit2 nonce, see below how to get it
  446. spender, # The UR checksum address
  447. deadline,
  448. 1, # chain id
  449. )
  450. # Then you need to sign the message:
  451. signed_message = acc.sign_message(signable_message) # where acc is your LocalAccount
  452. # And now you can encode the data:
  453. encoded_data = codec.encode.chain().permit2_permit(data, signed_message).build(deadline)
  454. # Then in your transaction dict:
  455. transaction["data"] = encoded_data
  456. # you can now sign and send the transaction to the UR
  457. ```
  458. After that, you can swap tokens using the Uniswap universal router.
  459. #### How to get the current permit2 allowance, expiration and nonce
  460. You can get the nonce you need to build the permit2 signable message like this:
  461. ```python
  462. amount, expiration, nonce = codec.fetch_permit2_allowance(acc.address, token_address) # where acc is your LocalAccount
  463. ```
  464. ### How to chain a call to PERMIT2_PERMIT and V2_SWAP_EXACT_IN in the same transaction
  465. Don't forget to give a token allowance to the Permit2 contract as well.
  466. ```python
  467. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  468. codec = RouterCodec()
  469. # Permit signature
  470. data, signable_message = codec.create_permit2_signable_message(
  471. token_address,
  472. amount, # max = 2**160 - 1
  473. expiration,
  474. nonce, # Permit2 nonce
  475. spender, # The UR checksum address
  476. deadline,
  477. 1, # chain id
  478. )
  479. # Then you need to sign the message:
  480. signed_message = acc.sign_message(signable_message) # where acc is your LocalAccount
  481. # Permit + v2 swap encoding
  482. path = [token_in_address, token_out_address]
  483. encoded_data = (
  484. codec
  485. .encode
  486. .chain()
  487. .permit2_permit(data, signed_message)
  488. .v2_swap_exact_in(FunctionRecipient.SENDER, Wei(10**18), Wei(0), path)
  489. .build(deadline)
  490. )
  491. # Then in your transaction dict:
  492. transaction["data"] = encoded_data
  493. # you can now sign and send the transaction to the UR
  494. ```
  495. ### Uniswap V4 Functions
  496. #### How to build a Uniswap V4 pool key
  497. PoolKey is used to identify a pool.
  498. ```python
  499. from uniswap_universal_router_decoder import RouterCodec
  500. codec = RouterCodec()
  501. pool_key = codec.encode.v4_pool_key(
  502. token_0_address, # or "0x0000000000000000000000000000000000000000" for ETH
  503. token_1_address,
  504. fee, # ex: 3000
  505. tick_spacing, # ex: 60
  506. hooks, # address or "0x0000000000000000000000000000000000000000"
  507. )
  508. ```
  509. #### How to build a Uniswap V4 path key
  510. PathKey is used to identify pools in a multi-hop swaps.
  511. ```python
  512. from uniswap_universal_router_decoder import RouterCodec
  513. codec = RouterCodec()
  514. path_key = codec.encode.v4_path_key(
  515. intermediate_token_address,
  516. fee, # ex: 3000
  517. tick_spacing, # ex: 60
  518. hooks, # address or "0x0000000000000000000000000000000000000000"
  519. hook_data, # ex: b"" if no data
  520. )
  521. ```
  522. #### How to encode a Uniswap V4 pool id
  523. Pool ids are used by V4 contracts to identify pools. For example, you'll need it to request the `StateView` contract.
  524. ```python
  525. from uniswap_universal_router_decoder import RouterCodec
  526. codec = RouterCodec()
  527. pool_id = codec.encode.v4_pool_id(pool_key=pool_key)
  528. ```
  529. #### How to initialize a Uniswap V4 pool with the Universal Router function V4_INITIALIZE_POOL
  530. ```python
  531. trx_params = (
  532. codec
  533. .encode
  534. .chain()
  535. .v4_initialize_pool(pool_key, 1, 1)
  536. .build_transaction(sender_address, ur_address=ur_address)
  537. )
  538. ```
  539. #### How to mint a Uniswap V4 position with the Universal Router function V4_POSITION_MANAGER_CALL
  540. Example where a position on a ETH/TOKEN pool is minted between tick_0 and tick_1
  541. ```python
  542. from uniswap_universal_router_decoder import V4Constants
  543. trx_params = (
  544. codec.
  545. encode.
  546. chain().
  547. permit2_transfer_from( # send tokens to the V4 position manager. UR needs to be permit2'ed
  548. FunctionRecipient.CUSTOM,
  549. token_address,
  550. token_amount,
  551. posm_address
  552. ).
  553. v4_pm_call(). # start encoding the V4 position manager call
  554. mint_position(
  555. pool_key, # a PoolKey object
  556. tick_0,
  557. tick_1,
  558. liquidity, # the provided liquidity
  559. amount_0_max, # slippage protection
  560. amount_1_max, # slippage protection
  561. sender_address,
  562. hook_data, # or b"" if no hook data
  563. ).
  564. settle(token_address, V4Constants.OPEN_DELTA.value, False).
  565. close_currency(eth_address). # eth address is "0x0000000000000000000000000000000000000000"
  566. sweep(eth_address, sender_address). # get back unused ETH
  567. sweep(token_address, sender_address). # get back unused tokens
  568. build_v4_pm_call(codec.get_default_deadline()). # build the V4 position manager call
  569. build_transaction( # build the UR transaction (see "How to build directly a transaction")
  570. sender_address,
  571. eth_amount,
  572. ur_address=ur_address,
  573. )
  574. )
  575. ```
  576. #### How to perform a Uniswap V4 swap with the Universal Router function V4_SWAP
  577. ###### Example using the V4 SWAP_EXACT_IN_SINGLE function to swap ETH for a token
  578. ```python
  579. pool_key = codec.encode.v4_pool_key(
  580. eth_address, # "0x0000000000000000000000000000000000000000"
  581. token_address,
  582. pool_fee, # ex: 3000
  583. tick_spacing, # ex: 60
  584. )
  585. trx_params = (
  586. codec.
  587. encode.
  588. chain().
  589. v4_swap().
  590. swap_exact_in_single(
  591. pool_key=pool_key,
  592. zero_for_one=True,
  593. amount_in=eth_amount,
  594. amount_out_min=token_amount_min,
  595. ).
  596. take_all(token_address, Wei(0)).
  597. settle_all(eth_address, eth_amount). # with eth_address = "0x0000000000000000000000000000000000000000"
  598. build_v4_swap().
  599. build_transaction(account.address, eth_amount, ur_address=ur_address)
  600. )
  601. raw_transaction = w3.eth.account.sign_transaction(trx_params, account.key).raw_transaction
  602. trx_hash = w3.eth.send_raw_transaction(raw_transaction)
  603. ```
  604. ###### Example using the V4 SWAP_EXACT_IN function to swap ETH for a token through 2 pools
  605. path: eth -> token a -> token b
  606. ```python
  607. path_key_eth_token_a = codec.encode.v4_path_key(
  608. token_a_address,
  609. fee,
  610. tick_spacing,
  611. )
  612. path_key_token_a_token_b = codec.encode.v4_path_key(
  613. token_b_address,
  614. fee,
  615. tick_spacing,
  616. )
  617. trx_params = (
  618. codec.
  619. encode.
  620. chain().
  621. v4_swap().
  622. swap_exact_in(
  623. eth_address,
  624. [path_key_eth_token_a, path_key_token_a_token_b],
  625. amount_in,
  626. amount_out_min,
  627. ).
  628. take_all(token_b_address, Wei(0)).
  629. settle_all(eth_address, amount_in).
  630. build_v4_swap().
  631. build_transaction(
  632. account.address,
  633. amount_in,
  634. ur_address=ur_address,
  635. )
  636. )
  637. ```
  638. ### Other chainable functions
  639. (See integration tests for full examples)
  640. #### PAY_PORTION
  641. Example where a recipient is paid 1% of the USDC amount:
  642. ```python
  643. .pay_portion(FunctionRecipient.CUSTOM, usdc_address, 100, recipient_address)
  644. ```
  645. #### PAY_PORTION_FULL_PRECISION
  646. Same as PAY_PORTION but with full precision, where 10**18 represents 100%.
  647. Example where a recipient is paid 50% of the USDC amount:
  648. ```python
  649. .pay_portion_full_precision(FunctionRecipient.CUSTOM, usdc_address, 5 * 10**17, recipient_address)
  650. ```
  651. #### SWEEP
  652. Example where the sender gets back all remaining USDC:
  653. ```python
  654. .sweep(FunctionRecipient.SENDER, usdc_address, 0)
  655. ```
  656. #### TRANSFER
  657. Example where a USDC amount is sent to a recipient:
  658. ```python
  659. .transfer(FunctionRecipient.CUSTOM, usdc_address, usdc_amount, recipient_address)
  660. ```
  661. #### BALANCE_CHECK_ERC20
  662. Reverts if the owner's balance of the given ERC20 token is lower than the minimum amount.
  663. Example where the router must hold at least 1 USDC:
  664. ```python
  665. .balance_check_erc20(ur_address, usdc_address, 1 * 10 ** 6)
  666. ```
  667. #### EXECUTE_SUB_PLAN
  668. Executes a nested plan of commands. The Universal Router calls itself to run the sub-plan, so its commands
  669. are executed in the same transaction and share the same context (recipients, balances, ...).
  670. The sub-plan is built with `encode.chain()` just like the main plan.
  671. Example where a sub-plan transferring USDC is nested in the main plan:
  672. ```python
  673. sub_plan = codec.encode.chain().transfer(FunctionRecipient.SENDER, usdc_address, usdc_amount)
  674. codec.encode.chain().execute_sub_plan(sub_plan).build()
  675. ```
  676. #### V3_POSITION_MANAGER_PERMIT
  677. Approves a spender for a specific V3 position (NFT) using an EIP-712 signature instead of a transaction.
  678. The signable message is built with `create_v3_position_manager_permit_signable_message()`, then signed.
  679. Example where the spender is approved for the position `token_id`:
  680. ```python
  681. permit_params, signable_message = codec.create_v3_position_manager_permit_signable_message(
  682. spender_address,
  683. token_id,
  684. nonce, # the current nonce of the V3 position
  685. deadline,
  686. )
  687. signed_message = acc.sign_message(signable_message) # where acc is your LocalAccount
  688. codec.encode.chain().v3_position_manager_permit(permit_params, signed_message).build(deadline)
  689. ```
  690. #### V3_POSITION_MANAGER_CALL
  691. Calls one of the 3 V3 position manager functions the UR allows: `decreaseLiquidity`, `collect` or `burn`.
  692. Only one function can be called per V3_POSITION_MANAGER_CALL command: the UR forwards the input as a single
  693. call and rejects anything else (including `multicall`). To run several of them, chain several commands in the
  694. same transaction (see the integration test).
  695. The UR must be approved for the position first (see V3_POSITION_MANAGER_PERMIT).
  696. - `decreaseLiquidity` removes liquidity from the position. The freed tokens are NOT sent out: they are recorded
  697. as `tokensOwed0`/`tokensOwed1` on the position, together with ALL the fees earned since the last update
  698. (fees are not prorated, even if only part of the liquidity is removed).
  699. - `collect` sends `min(amountMax, tokensOwed)` to the recipient. `tokensOwed` holds both the principal freed by
  700. `decreaseLiquidity` and the fees, so `collect` alone harvests the fees without touching the liquidity.
  701. - `burn` deletes the position (NFT). It requires the position to be empty (`liquidity == 0` and
  702. `tokensOwed0 == tokensOwed1 == 0`), hence the usual `decreaseLiquidity` -> `collect` -> `burn` order.
  703. Note: `increaseLiquidity` and `mint` are not reachable through the UR (only the 3 functions above are allowed),
  704. they must be called directly on the V3 position manager.
  705. Example where the liquidity of a V3 position is decreased:
  706. ```python
  707. .v3_decrease_liquidity(
  708. token_id, # the id of the V3 position (NFT)
  709. liquidity, # the amount of liquidity to remove
  710. amount_0_min, # the minimum amount of token0 the decrease must free (kept as tokensOwed0, not sent out)
  711. amount_1_min, # the minimum amount of token1 the decrease must free (kept as tokensOwed1, not sent out)
  712. deadline, # when this call is not valid anymore
  713. )
  714. ```
  715. Example where the tokens owed to a V3 position are collected:
  716. ```python
  717. .v3_collect(
  718. token_id, # the id of the V3 position (NFT)
  719. recipient_address, # the address receiving the collected tokens
  720. amount_0_max, # the maximum amount of token0 to collect
  721. amount_1_max, # the maximum amount of token1 to collect
  722. )
  723. ```
  724. Example where an empty V3 position is burned:
  725. ```python
  726. .v3_burn(
  727. token_id, # the id of the V3 position (NFT)
  728. )
  729. ```
  730. #### PERMIT2_TRANSFER_FROM
  731. To use this function, the Universal Router needs to be `PERMIT2`'ed.
  732. Example where 1 `WETH` is transferred from the caller address to the v4 position manager
  733. ```python
  734. .permit2_transfer_from(FunctionRecipient.CUSTOM, weth_address, Wei(1 * 10 ** 18), v4_posm_address)
  735. ```
  736. ### PERMIT2_PERMIT_BATCH & PERMIT2_TRANSFER_FROM_BATCH
  737. Check the corresponding integration tests for an example of how to use these functions.
  738. ### How to build directly a transaction to the Uniswap Universal Router
  739. The SDK provides a handy method to build very easily the full transaction in addition to the input data.
  740. It can compute most of the transaction parameters (if the codec has been instantiated with a valid w3 or rpc url)
  741. or you can provide them.
  742. > See the corresponding integration tests for an async example
  743. Example where a swap is encoded and a transaction is built automatically:
  744. ```python
  745. from uniswap_universal_router_decoder import FunctionRecipient, RouterCodec
  746. codec = RouterCodec(w3)
  747. trx_params = (
  748. codec.encode.chain().v2_swap_exact_in(
  749. FunctionRecipient.SENDER, # the output tokens are sent to the transaction sender
  750. amount_in, # in Wei
  751. min_amount_out, # in Wei
  752. [
  753. in_token_address, # checksum address of the token sent to the UR
  754. out_token_address, # checksum address of the received token
  755. ],
  756. ).build_transaction(
  757. sender_address, # 'from'
  758. deadline=timestamp, # the swap deadline
  759. )
  760. )
  761. ```
  762. And that's it! You can now sign and send this transaction.
  763. A few other important parameters:
  764. - `value`: the quantity of ETH in wei you send to the Universal Router (for example when you wrap them before a swap)
  765. - `trx_speed`: an enum which influences the transaction rank in the block. Values are:
  766. - `TransactionSpeed.SLOW`
  767. - `TransactionSpeed.AVERAGE`
  768. - `TransactionSpeed.FAST` (default)
  769. - `TransactionSpeed.FASTER`
  770. - `max_fee_per_gas_limit`: if the computed `max_fee_per_gas` is greater than `max_fee_per_gas_limit` a `ValueError` will be raised to allow you to stay in control. Default is 100 gwei.
  771. How to use the `trx_speed` parameter:
  772. ```python
  773. from uniswap_universal_router_decoder import TransactionSpeed
  774. .build_transaction(sender_address, trx_speed=TransactionSpeed.FASTER)
  775. ```
  776. ### Command line interface
  777. The package installs two commands that print JSON to stdout, handy for shell scripts or to let an agent drive the codec:
  778. - `ur-encode`: describe the decoded call format and the commands, rebuild calldata from a decoded call, or encode a V3 path
  779. - `ur-decode`: decode a transaction, raw calldata, a custom error or a V3 path
  780. ```bash
  781. # describe the decoded call format and the commands, then describe one of them
  782. ur-encode list
  783. ur-encode describe V3_SWAP_EXACT_IN
  784. # rebuild the calldata of one command, from its name and parameters as decoded (see ur-decode)
  785. ur-encode build --command WRAP_ETH --params '{"recipient": "0x0000000000000000000000000000000000000001", "amountMin": 1000000000000000000}'
  786. # or of several commands at once, from a decoded call in a JSON file (or '-' for stdin)
  787. ur-encode build --plan decoded_call.json --deadline 1676825611
  788. # encode a V3 path: the tokens to swap through, with the pool fees between them
  789. ur-encode v3-path V3_SWAP_EXACT_IN 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 3000 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
  790. # the same path given as a JSON list
  791. ur-encode v3-path V3_SWAP_EXACT_OUT '[0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 3000, 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48]'
  792. # decode raw calldata
  793. ur-decode calldata 0x3593564c0000...
  794. # decode a transaction (needs an rpc endpoint via --rpc or the RPC_URL env var)
  795. ur-decode tx 0x52e63b7... --rpc https://...
  796. ```
  797. A plan file holds a decoded `execute` call, exactly as `ur-decode calldata` prints it:
  798. ```json
  799. {
  800. "function": "execute",
  801. "params": {
  802. "inputs": [
  803. {"command": "WRAP_ETH", "params": {"recipient": "0x0000000000000000000000000000000000000001", "amountMin": 1000000000000000000}}
  804. ],
  805. "deadline": 1676825611
  806. }
  807. }
  808. ```
  809. ### MCP server
  810. The optional `mcp` extra installs `ur-mcp`, a side-effect free [Model Context
  811. Protocol](https://modelcontextprotocol.io) server that exposes the codec to AI agents over stdio. Its tools only
  812. inspect or derive Universal Router data: they never sign or broadcast a transaction.
  813. ```bash
  814. pip install 'uniswap-universal-router-decoder[mcp]'
  815. ```
  816. It provides eight tools:
  817. - `list_commands` / `describe_command`: discover the decoded call format and the commands
  818. - `decode_transaction`: fetch and decode a transaction sent to the UR (needs an RPC endpoint)
  819. - `decode_calldata`, `encode_calldata`, `decode_error`, `decode_v3_path`, `encode_v3_path`: decode/encode data
  820. without an RPC endpoint
  821. `encode_calldata` is the mirror of `decode_calldata`: it rebuilds the calldata from a decoded call, so an agent can
  822. decode a route, edit it and re-encode it (the MCP counterpart of `ur-encode build`).
  823. The tools are annotated as read-only (`readOnlyHint`), and only `decode_transaction` as open-world (`openWorldHint`),
  824. so a host can auto-approve them instead of prompting on every call. Each tool also carries a human-readable title
  825. (`title`) for the host UI.
  826. `decode_transaction` uses the `rpc_url` tool argument, or the `RPC_URL` / `ETH_RPC_URL` environment variables, so a
  827. host can be pointed at any chain by configuring the server environment.
  828. To wire it into an MCP host (Zed, Claude Desktop, ...):
  829. ```json
  830. {
  831. "mcpServers": {
  832. "uniswap-universal-router-decoder": {
  833. "command": "ur-mcp", # or absolute path to ur-mcp in your virtual env.
  834. "env": {"RPC_URL": "https://..."}
  835. }
  836. }
  837. }
  838. ```
  839. ### Utility functions
  840. #### How to compute the gas fees
  841. The SDK provides handy methods to compute the current "priority fee" and "max fee per gas":
  842. Sync code:
  843. ```python
  844. from uniswap_universal_router_decoder.utils import compute_gas_fees
  845. priority_fee, max_fee_per_gas = compute_gas_fees(w3) # w3 is a valid Web3 instance
  846. ```
  847. Async code:
  848. ```python
  849. from uniswap_universal_router_decoder.utils import async_compute_gas_fees
  850. priority_fee, max_fee_per_gas = await async_compute_gas_fees(async_w3) # async_w3 is a valid AsyncWeb3 instance
  851. ```
  852. #### Ticks, sqrtPriceX96 and liquidity
  853. These functions can be useful to estimate the arguments needed to mint positions.
  854. ⚠️ The implementation of all tick, sqrtPriceX96, and liquidity related functions differs from the contracts:
  855. if you want the exact same results/numbers, do not use them.
  856. They can be imported `from uniswap_universal_router_decoder.utils`.
  857. For examples, check the integration tests for Uniswap V4.
  858. ```python
  859. compute_sqrt_price_x96() # Compute the sqrtPriceX96 from the Wei amounts
  860. convert_sqrt_price_x96() # Compute the price from the sqrtPriceX96
  861. sqrt_price_x96_to_floor_tick() # Convert a sqrtPriceX96 to floor tick
  862. tick_to_sqrt_price_x96() # Convert a tick to sqrtPriceX96
  863. tick_to_prices() # Compute price_0 (with currency_0 as the quote currency) and price_1 (with currency_1 as the quote currency)
  864. at a given tick
  865. price_0_to_closest_tick() # Compute the closest tick to a given price; useful to compute a price range lower and upper ticks
  866. compute_liquidity() # Compute theoretical liquidity as used to mint positions.
  867. ```
  868. ## Tutorials and Recipes on the Uniswap Universal Router:
  869. See the [SDK Wiki](https://github.com/Elnaril/uniswap-universal-router-decoder/wiki).
  870. ## News and Q&A:
  871. See the [Discussions](https://github.com/Elnaril/uniswap-universal-router-decoder/discussions) and [𝕏](https://twitter.com/ElnarilDev)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.