(01) TONDEX, Orderbook style DEX using Uniswap V4

Eugene Cho
Tokamak Network
Published in
11 min readNov 2, 2023

Article series : Developing DEX on the Tokamak Network’s Titan

This is the first in a series of three articles about developing a DEX on Tokamak Network’s Titan network.

TL;DR

  1. Uniswap V4 brings new features like singleton architecture and hooks, which will enable new services like limit orders.
  2. Tokamak Network has planned a DEX (tentatively named TONDEX) that utilizes the new features of Uniswap V4 to implement CEX features such as limit orders.

Introduction

Centralized exchanges have market makers whose sole role is to provide liquidity. These market makers are pre-agreed with the exchanges and are exempt from transaction fees, and they make money from high-frequency trading. However, in a DEX that aims to be decentralized, there is no entity to introduce or manage these market makers, so the rise of automated market makers (AMMs) that rely solely on algorithms has been a major contributor to the proliferation of DEXs.

However, one of the core features of an exchange, limit orders, was virtually impossible on Uniswap until V3. Aside from the liquidity generated by AMM, V3 did not provide the ability to monitor the number of orders placed by trading customers and deliver the status in real time. Therefore, the core function of the swap function was to simply exchange at the market price based on the preset liquidity, excluding the provision of real-time liquidity. Therefore, the volume for each price was automatically generated, so there was no need to painstakingly create an order book to show how much buy/sell volume was accumulated.

However, the demand for limit trading was growing in the market. Each buyer and seller has a different price they are willing to pay, and only a fraction of them will meet on a market price and execute the trade, so most users want to trade on a centralized exchange (CEX), where they can place an order at the price they want, and see how others’ orders change in real-time for each price.

Of course, in V3, there were attempts to implement these limit order features using a combination of front-end and smart contracts. A typical approach is to purchase UNISWAP’s LP, receive NFTs (UNISWAP’s range order transactions), lock the NFTs, and create a bot that is delegated to perform limit orders. However, this approach has not been widely used due to its complexity and security concerns.

New possibilities with V4

However, in V4, we could build a native dApp with these limit trades by default. This is because V4 includes innovative features that were not previously available.

First, the Singleton feature, which allows you to manage multiple liquidity pools as a single pool, enables trading efficiency. The advantage of this strategy is that DeFi liquidity can be centralized on Uniswap instead of being spread across multiple exchanges. For example, it becomes possible to leverage multiple different decentralized exchanges that do not have the “critical mass” to support average-sized swaps by bundling them together. The effect of this liquidity concentration can lead to better transaction prices for users. Some argue that this consolidation will make a blockchain project less encouraged to build their own decentralized exchanges and more willing to build them on top of Uniswap.

Second, Hooks are introduced to monitor what’s happening in liquidity pools and react in real-time. Hooks are plugins that allow you to customize the way pools, swaps, fees, and LP positions interact, so you can create a variety of custom AMM pools with Hooks while maintaining the liquidity and security of the Uniswap protocol. As smart contracts, Hooks have the advantage of being able to influence a pool’s lifecycle, not just when it’s created. Previously, you could only set parameters with a contract at the time the pool was created, and you couldn’t change them (For more…).

However, there is a downside. It can be abused by malicious developers. In the DeFi world, where everything works with open source and no moderators, Hooks add a layer of complexity to the security considerations because they can be abused to put innocent users at greater risk.

In other words, these are features that in the past would have been provided by a third party in the form of a bot, and people would have been wary of using them, but because they’re all hosted directly on Uniswap’s backend or frontend, people just trust them. This increases the risk of being scammed easily.

There’s a lot of discussion about the different services that these singletons and hooks will enable, and the pros and cons that come with them. In particular, it is significant that limit order, which was not possible in V3 without using a bot, can be implemented natively in V4. While a V3-based DEX pursued the immediate trading in the spot market, a V4-based DEX allows users to do limit orders and starts to greatly appeals to them for investment purposes. For more information on the actual implementation of limit orders using V4, please refer to the following article (the development environment used is Foundry).

Previously, Uniswap V3 was only a simple exchange function (swap), but now it is possible to implement limit orders, making it a trading platform that can realize full-fledged investment profits. The convenience of implementing limit orders in a native environment is undeniable. For example, if you write an after-swap hook connected to the WETH/USDC 0.05% pool and set a condition “Sell at market if WETH after-swap price breaks $2,000”, it will be automatically executed if the price actually breaks $2,000 after the swap. Previously, you would have had to use an off-chain backend to constantly monitor the price of the chain and manually execute the swap, or use an off-chain backend to constantly monitor the price of the chain and initiate the trade once the condition was met.

Of course, you also have to consider the various raids on MEV bots, and without proper slippage protection, large purchase orders can be vulnerable to JIT, sandwiching, etc. Nevertheless, hooks are innovative in that they create a tool that can be publicly distributed and fairly used by everyone, allowing any kind of transaction for a pool to be created natively on the chain, opening up many new possibilities for Uniswap.

Innovation isn’t limited to DEXs. Hooks open up a whole new set of possibilities for integration with DeFi protocols. For example, in addition to limit orders, time-weighted token purchases, and dynamic fees, Hooks can be used to lock in stablecoins at the right price and help lending markets close non-performing positions (according to Ilgiz Gimaltdinov, a contributor to the DeFi protocol Gearbox).

It could also have implications for the Launchpad platform. Various DeFi financial instruments created on L2 will be able to be actively traded on DEXs at the desired price. In addition, the role of DEXs will increase as a platform where various derivatives can be traded at any price. This increase in trading convenience will naturally improve the efficiency of investment in DeFi products and increase related investment.

Evolving DEX and Vision of TONDEX

TONDEX (tentative name) is a DEX that is being developed with the goal of opening in the first half of next year by utilizing the advantages of such limit orders on the Tokamak Network. In particular, with the similar UX to the that of centralized exchanges, TONDEX puts its aim to become easier to use for beginners. Currently, the basic UX/UI has been completed, and full-scale development is expected to be carried out next year with the upgraded functionality of V4. I will introduce the details of our plans later.

The first thing you’ll notice about TONDEX is the limit order feature. Just like on a centralized exchange, you can place an order at a desired price and it will be executed when the conditions are met. It can be implemented by utilizing the Hooks feature in V4. This allows you to see a stock market-like order book, as shown in the image below, with liquidity provided by clients in real-time, in addition to the liquidity volume pre-set by the AMM. This will make it easier to reach new customers with less experience in DeFi.

<Figure 1. UX/UI of TONDEX with the limit order feature>

As functionality changes, so does the UX that expresses it. If a DEX has a unique feature, a new UX for DeFi may be more appropriate than blindly following the UX of a centralized exchange. In the case of Unibot app, for example, it has been praised for focusing on a new UX for DEXs and breaking away from the simple imitation of centralized exchange UX. Based on the observation that customers share the price information and their trend-following trading is done via Telegram, the app help users share price information as a link on Telegram and execute limit orders immediately on Telegram.

<Figure 2. Unibot.app with limit orders on Telegram (https://unibot.app/)>

As such, a V4-based dApp is still a nascent market, even though a new innovation pops up every day. Tokamak Network’s TONDEX is also planning to introduce a new UX by investigating the varying needs of customers.

References

Summarizing the three major innovations of Uniswap V4

Korean Version

Article series : Developing DEX on the Tokamak Network’s Titan

이 글은 Tokamak Network의 Titan 네트워크 상에서 DEX를 개발하는 것을 주제로 하는 3편의 시리즈 중에서 첫 번째입니다.

TL;DR

  1. 유니스왑 V4는 싱글톤 아키텍처와 후크와 같은 새로운 기능을 제공하여 지정가 주문과 같은 새로운 서비스를 가능하게 할 것이다.
  2. 토카막 네트워크는 유니스왑 V4의 새로운 기능을 활용하여 지정가 주문과 같은 CEX 기능을 구현하는 DEX(가칭 TONDEX)를 계획하고 있다.

Introduction

중앙화된 거래소에는 유동성을 제공하는 역할만 담당하는 시장조성자가 있다. 이들은 거래소와 사전협의하여 거래수수료는 면제받으며 고빈도매매를 통해 수익을 올린다. 하지만 탈중앙화를 목표로 하는 DEX에서는 이러한 시장조성자를 인위적으로 내세우거나 관리할 주체가 없다. 따라서 오로지 알고리즘에 의존하여 작동하는 자동시장조성자(AMM)의 등장은 DEX의 확산에 큰 기여를 하게 된 것이다.

다만, 거래소의 핵심 기능이라 할 수 있는 지정가거래(limit order)는 Uniswap은 V3까지만 하더라도 사실상 불가능했다. 지정가거래는 다양한 매입, 매도 조건을 걸어놓고 조건에 맞을때 자동체결되도록 하는 것인데, V3에서는 AMM으로 생성된 유동성외에 거래고객이 실시간으로 걸어놓은 주문수량 까지 모니터링하고 상태를 실시간으로 전달해주는 기능을 제공하지 않았기 때문이다. 따라서 고객의 실시간 유동성 제공은 배제한 채, 사전에 설정된 유동성을 바탕으로 시장가로 단순 교환에 충실한 Swap기능이 핵심이 되었던 것이다. 그러므로 각 호가별로 물량도 자동으로 생성된 물량이므로 굳이 매수/매도 물량이 얼마나 쌓여있는지를 알려주는 호가창을 공들여 만들 필요도 없었다.

하지만 시장에서는 지정가매매에 대한 수요는 커져만 갔다. 매수/매도자 각각은 자신이 원하는 가격이 천차만별이며, 이 중 일부만이 시장가격에 합의하고 매매를 이루게 된다. 따라서 대다수의 사용자들은 중앙화된 거래소(CEX)처럼 원하는 가격에 주문을 넣고, 이러한 주문이 각 호가마다 어떻게 변동되는지 실시간으로 파악하면서 거래하기를 희망하기 때문이다.

물론 V3에서도 이러한 지정가거래 기능을 프론트엔드와 스마트컨트랙트를 적절히 조합하여 구현하고자 하는 시도가 있었다. UNISWAP의 LP를 구입하고 NFT받은 후(UNISWAP의 range order 거래), 해당 NFT를 Lock하고 지정가거래를 위임받은 Bot을 생성하는 방식이 대표적이다. 하지만 이런 방식은 복잡한 절차와 보안상의 문제로 인해 널리 사용되지 못했던 것이다.

New possibilities with V4

하지만 이번에 V4에서는 이러한 지정가 거래기능을 내재화 하여 기본적으로 구현할 수 있게 되었다. 그 이유는 종전에는 제공하지 않았던 혁신적인 기능을 V4에 담았기 때문이다.

첫째, 여러 유동성 풀(pool)을 하나로 관리할 수 있는 Singleton 기능으로 인해 거래의 효율성을 기대할 수 있게 되었다, 이 전략의 장점은 탈중앙 금융 유동성이 여러 거래소에 분산되지 않고 유니스왑에 집중될 수 있다는 점이다. 예를 들어, 평균규모의 스왑을 지원하기 위한 ‘임계 질량’에 미치지 못하는 여러 개의 서로 다른 탈중앙화 거래소를 하나로 묶어 활용하는 것이 가능해진다. 이러한 유동성 집중의 효과로 인해 사용자에게 더 나은 거래 가격을 제공할 수 있다. 이러한 통합의 효과로 인해 각 블록체인 프로젝트가 자체 탈중앙 거래소를 구축할 이유가 줄어들고 유니스왑을 기반으로 구축할 이유가 늘어날 것이라는 견해도 있다.

둘째, 유동성 풀에서 어떤 일이 벌어지고 있는지 모니터링하고 실시간으로 대응할 수 있는 Hook이 도입되었다. Hook은 플러그인으로서 풀, 스왑, 수수료, LP 포지션이 상호 작용하는 방식을 사용자화 할 수 있도록 해준다. 따라서 유니스왑 프로토콜의 유동성과 보안을 유지한 채, Hook을 통해 다양한 맞춤형 AMM 풀을 만들 수 있는 것이다. Hook은 스마트 컨트랙트로서 pool의 생성시점뿐만 아니라 pool의 라이프사이클 어디에서든 영향을 미칠 수 있다는 장점이 있다. 종전에는 pool이 생성되는 시점에서만 contract로 파라메타를 설정했으며 변경이 불가능했다 (참고)

하지만 단점도 있다. 악의를 가진 개발자가 악용하는 것이다. 중재자 없이 모든 것이 공개된 소스코드로 작동되는 디파이 세계에서는 이러한 Hook가 선의의 사용자를 더 위험하게 만드는 용도로 악용될 수 있으므로 Hook는 보안 측면에서 고려할 문제가 더욱 복잡해진다.

즉, 예전같으면 서드파티가 Bot의 형태로 제공했을 기능들로서 사람들이 경계를 하면서 사용했는데, 이 제는 이 모든 것이 유니스왑의 백엔드나 프런트엔드에서 바로 호스팅되니까 사람들이 그냥 믿고 사용하게 되는 것이다. 이러면 손쉽게 사기를 당할 위험이 높아지게 된다.

이러한 Singleton과 Hook의 도입이 가져다 줄 다양한 서비스, 그리고 그에 따른 장단점에 대해서 활발히 논의되고 있다. 특히 V3에서는 bot을 이용하지 않고서는 수행할 수 없었던 지정가거래가 V4에서는 native로 구현이 가능하게 된 것이 시사하는 바는 크다. Swap 중심의 DEX에서는 현물시장에서의 즉각적인 매매로서 교환 그 자체에 충실했다면, 이제 본격적으로 limit order가 가능해진 DEX에서는 투자목적의 매매자들에게도 크게 어필을 하게 된 것이다. 참고로 V4를 이용한 limit order의 실제구현에 대해서는 다음 글을 참조하면 된다(적용된 개발환경은 Foundry이다).

종전의 Uniswap V3는 단순한 교환기능(swap) 뿐이었지만, 이제는 지정가거래(limit order) 구현이 가능해져서 본격적인 투자차익을 실현시키는 거래플랫폼의 역할을 할 수 있게 되었다. 지정가거래를 네이티브 환경에서 구현한다면 그 편리성은 두말할 필요가 없다. 예를 들어, WETH/USDC 0.05% 풀에 연결된 애프터 스왑 훅을 작성하고, “WETH 애프터 스왑 가격이 2,000달러를 돌파하면 시장가로 매도”라는 조건을 설정하는 경우, 스왑 후 실제로 가격이 2,000달러를 돌파하면 자동으로 체결된다. 예전 같으면 오프체인 백엔드를 통해 체인의 가격을 지속적으로 모니터링 하고, 수동으로 스왑을 실행하던가, 아니면 오프체인 백엔드를 통해 체인의 가격을 지속적으로 모니터링하고 조건이 충족된 후 거래를 시작해야 했었다.

물론 오프체인 백엔드를 통해 거래를 실행하는 경우, MEV 봇에 대한 다양한 레이드도 고려해야 하며, 슬리피지 보호가 제대로 이루어지지 않으면 대규모 구매 주문은 JIT, 샌드위치 등에 취약할 수도 있다. 그럼에도 후크는 모든 사람이 공개적으로 배포하고 공정하게 사용할 수 있는 도구를 만들어 풀에 대한 모든 종류의 거래를 체인에서 기본적으로 생성할 수 있게 하고, 유니스왑에 많은 새로운 가능성을 열어준다는 점에서 혁신적이다.

혁신은 DEX에만 국한되지 않는다. Hook는 탈중앙 금융 프로토콜과 통합할 수 있는 완전히 새로운 가능성을 열어주기 때문이다. 예를 들어, 지정가 주문, 시간가중 토큰 구매, 동적 수수료 외에도 Hook를 사용하여 스테이블코인을 적정 가격에 고정하고 대출 시장이 부실 포지션을 청산하는 데 도움을 줄 수 있다(탈중앙 금융 프로토콜인 Gearbox의 기여자 Ilgiz Gimaltdinov의 견해).

또한 런치패드 플랫폼에도 영향을 미칠 수 있다고 본다. L2를 기반으로 생성되는 다양한 디파이 금융상품이 DEX에서도 원하는 가격에 활발히 거래될 수 있게 된다. 그외에도 다양한 파생상품들이 원하는 가격에 거래될 수 있는 플랫폼으로서 DEX의 역할은 커질 전망이다. 이렇게 거래 편리성이 증가하면 당연히 디파이 상품의 투자의 효율성도 좋아지고 관련 투자도 증대된다.

Evolving DEX and Vision of TONDEX

(가칭) TONDEX는 토카막네트워크에서 이러한 지정가거래의 장점을 살려서 내년 상반기 오픈을 목표로 개발중인 DEX다. 특히 화면 UX는 중앙화된 거래소의 UX와 유사하도록하여, 초보자들도 손쉽게 사용하는 것에 목표를 두고 있다. 현재 UX/UI에 대한 기초작업은 완료하였으며, 이번 V4의 업그레이드를 반영하여 내년도에 본격적인 개발이 이뤄질 예정이다. 이에 대한 상세한 기획내용은 차후 소개하기로 한다.

TONDEX에서 가장 먼저 눈여겨볼 점은 지정가매매 기능이다. 중앙화된 거래소에서처럼 원하는 가격에 주문을 넣고, 조건이 충족되면 체결된다. V4를 활용한 Hook 기능을 활용하여 구현할 수 있다. 이로 인해 AMM에 의해 사전에 설정된 유동성 물량 외에도 실시간 제공되는 고객의 유동성이 더해져서 아래 그림과 같이 주식시장과 유사한 호가창을 볼 수 있게 된다. 이로 인해 DeFi 경험이 낮은 신규 고객들에게도 좀더 쉽게 다가갈 수 있을 것이다.

<Figure 1. 지정가주문 기능을 반영한 TONDEX의 UX/UI>

기능이 변화하면 이를 표현하는 UX도 변화한다. 만약 DEX만의 고유한 기능이 있다면 중앙화된 거래소의 UX를 무조건 추종하기보다는 DeFi만의 새로운 UX가 더 어울릴 수도 있다. 대표적으로 unibot app의 경우, DEX만의 새로운 UX에 집중하여, 중앙화된 거래소 UX를 단순모방하는 것을 탈피하였다는 평을 받고 있다. 고객들의 주요 시세 정보공유와 추종매매가 텔레그램을 통해 이뤄지는 점에 착안하여, 시세정보를 텔레그램에 링크로 공유할 수 있고, 해당 텔레그램 상에서 즉시 지정가매매를 실행하는 것을 구현한 것이다.

<Figure 2. 텔레그램에서 지정가주문이 가능한 Unibot.app (https://unibot.app/)>

이처럼 디파이는 여전히 초기 시장으로서 매일마다 새로운 혁신이 쏟아져 나오고 있다. 토카막네트워크의 TONDEX도 변화하는 고객의 수요를 다각도로 조사하여, 새로운 UX를 선보여 나갈 계획이다.

참고자료

Summarizing the three major innovations of Uniswap V4

--

--