(02) Exploring new services of DEX with Uniswap v4 key features

Eugene Cho
Tokamak Network
Published in
10 min readNov 28, 2023

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

This is the second in a series of three articles about developing a DEX on Tokamak Network’s Titan network.
(01) TONDEX, Orderbook style DEX using Uniswap V4
(02) Exploring new services of DEX with Uniswap v4 key features (this article)
(03) Developing TONDEX utilizing Uniswap (upcoming)

TL;DR

  1. Utilizing the core functionality of Uniswap V4 will enable not only limit order but also complex DeFi services that have never been seen before.
  2. TONDEX, which will be open-sourced after development, may include advanced DeFi services as well as limit order utilizing Uniswap V4 features.

Introduction

In this article, I’ll discuss how the three key features of Uniswap V4 — Singleton, Hooks, and Flash accounting — can transform new DEX services and outline how these improvements can be incorporated into TONDEX (more specific TONDEX development plan will be presented in the next issue).

V4 Core Features: Singletons and Hooks

With the introduction of singleton contracts in V4, complex transactions can be aggregated into a single contract, making it possible to implement complex services across multiple protocols at lower fees. For example, when deploying multiple liquidity pools, as shown in the figure below, deploying them in a singleton contract can reduce deployment costs by up to 99%.

<Increased efficiency of liquidity pool deployment: with V3 (left), with V4 (right). source>

V4 also introduces the ability to utilize hooks to implement various trading features such as limit trading. Hooks are plugins used to customize interactions with liquidity pools, exchanges, fees, and liquidity providers (LPs). The hook mechanism allows developers to execute specific actions at key points in a liquidity pool’s lifecycle (e.g., before/after a swap or before/after an LP position change).

This gives developers more flexibility to define and execute custom logic, and allows them to bind hooks to specific liquidity pools to control the behavior and interaction of the pools. For example, developers can create hooks that check for certain conditions before each swap or execute additional actions when there is a change in LP positions. Likewise, limit orders, which trigger a swap to be executed when a certain price is reached, are also possible using this principle.

In addition to hooks, Uniswap V4 has another component called “action hooks”. This is a way to execute a hook contract only when certain flag conditions are met (see the flowchart below). For example, before an asset exchange, the contract checks a flag to evaluate the volatility of the liquidity pool. If liquidity is high, the flag becomes true and the hook is executed. If liquidity is insufficient, the flag will be false and the contract will refuse to execute. This allows you to prevent the swap from being executed if there is insufficient liquidity at that point in time, even if you have placed a limit order.

How to use an action hook (Source: YBB Capital Researcher Ac-Core Homemade)

Examples of new services enabled by V4 core features

To summarize the effect of V4 in one word, it would be increased market efficiency. Of course, the above features of V4 are not finalized and may change going forward. However, It suffices to say that V4’s general outline gives a good idea of what new services DEXs will be able to offer.

First, time-weighted average market makers (TWAMM) are possible, which means that when a large number of orders come in, the effect on price can be offset by gradually executing large orders over a period of time instead of all at once. This is possible because of the hook’s ability to react to real-time conditions. This reduces impermanent losses that can be caused by a lack of liquidity in a particular price range.

Second, it allows for dynamic fees. Through hooks, liquidity pools can dynamically adjust fees based on market volatility or other input parameters to better adapt to market conditions.

Third, there is room for high-frequency trading (HFT), which is often used by market makers. In general, in capital markets, HFT plays the role of a market maker, which not only ensures the trading efficiency of the market, but also increases price efficiency based on instant arbitrage. However, in the DeFi space, high-frequency trading has not been possible due to high fees and the block generation time required by L1. Therefore, until V3, automated market makers (AMMs) were relied upon and limit trading was not technically possible.

However, from V4, in addition to limit trades using hooks, market makers that provide long-term liquidity or high-frequency trades can also significantly reduce their fees through multiple fee tiers.

As a result, the AMM function is basically based on pre-provided liquidity, but in addition, real-time liquidity generated by market makers and regular users placing limit trades can be added. If V4 is implemented as an L2-based DEX with high-speed transaction processing, it means one step closer to such high-frequency trading, as the processing speed and fees will be low.

However, it is important to consider how to design a high-frequency trading strategy when everyone can see the trades that the other party is about to execute on a public blockchain. This transparency of trading requires a different high-frequency trading strategy compared to traditional capital markets. For example, it may be possible to compete more aggressively with competitors using the same strategy when trading, or to avoid competition with a unique strategy that is inherently difficult for competitors to implement in terms of investment size or investment time horizon.

Fourth, V4 will enable the sophistication of DeFi services. While the DeFi market has been criticized for its inefficiency, V4’s new features allow for the emergence of complex financial services that improve market efficiency. In addition to V4’s limit order and singleton contracts, it also introduces flash accounting, which clears only the transaction balance at the end of the block after various transactions are processed internally within the singleton contract. This enables efficient Defi products that do not have to worry about gas costs even when they are composed of various DeFi services.

As an example of the expected sophistication of DeFi services, we can consider the launch of complex and sophisticated DeFi services that are linked to real-time liquidity. The idea is to maximize the utility of funds by using hooks to determine how much liquidity needs to be provided in real-time, and then automatically deposit the rest of the liquidity into lending protocols.

In addition, it will be possible to launch tokens that invest in multiple other tokens and trade them like EFTs. You can make this EFT-like tokens exchangeable in a single singleton contract. This will allow for portfolio diversification in DeFi, something that has only been possible in the CeFi world.

This concept can be extended to launchpads, where promising projects can be launched simultaneously, along with fund tokens that diversify the investment into these projects. This can be done by making ETF-like tokens exchangeable for the tokens of the investee projects in a single singleton contract.

New services of TONDEX

As such, TONDEX’s development direction may include not only limit order but also advanced DeFi services. Of course, how much and how far customers want it must be fully researched in advance, so it is necessary to accurately grasp customer reactions and potential demand through continuous publication of articles or public seminars, etc.

TONDEX, which will be developed based on customer feedback, will be released as an open source. It will be possible to use TONDEX as it is, or to modify some of the code for various applications. The details of these directions will be discussed in the next article.

References

Uniswap V4: Breaking Down the Upgrades for DeFi Enthusiasts

Uniswap V4: A Saga of Hooks, Bidding Farewell to Fork Swap

Uniswap v4: The liquidity Marketplace

6 Reasons DeFi Will Stay Inefficient (and Profitable)

DeFi Is the Next Frontier of High-Frequency Trading

Korean Version

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

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

(01) TONDEX, Orderbook style DEX using Uniswap V4
(02) Exploring new services of DEX with Uniswap v4 key features (this article)
(03) Developing TONDEX utilizing Uniswap (upcoming)

TL;DR

  1. Uniswap V4의 핵심기능을 활용하면 지정가매매뿐만 아니라 종전에는 볼 수 없었던 복합적인 DeFi 서비스가 가능해진다.
  2. 개발 후 오픈소스로 공개될 TONDEX의 개발방향에는 Uniswap V4의 기능활용한 지정가매매뿐만 아니라 고도화된 DeFi 서비스도 포함될 수 있다.

Introduction

본 글에서는 Uniswap V4의 3대 핵심기능인 Singleton, Hook, 그리고 Flash accounting 기능이 어떻게 새로운 DEX서비스를 바꿔놓을 수 있는지를 소개하고, 이러한 개선점이 TONDEX에 어떻게 반영될 수 있는지 그 방향성을 소개하고자 한다 (좀더 구체적인 TONDEX의 개발방향은 다음호에 소개될 예정이다).

V4의 핵심기능 : Singleton과 Hook

V4에서는 싱글톤 컨트랙트를 도입함으로써, 복잡한 거래를 하나의 컨트랙트 안에 모을 수 있게 되어 다양한 프로토콜을 오가는 복잡한 서비스를 저렴한 수수료로 구현할 수 있게 되었다. 일례로 아래 그림에서 보듯이 다양한 유동성 풀을 배포할 때, singleton contract에 모아서 배포하면 배포비용을 최대 99%까지 줄일 수 있다.

<유동성 풀 배포의 효율성 증가 : V3 이용시(좌), V4 이용시(우) source>

또한 V4에서는 후크(hook)를 활용하여 지정가 매매와 같은 다양한 거래기능을 구현할 수 있게 되었다. 후크(Hook)는 유동성 풀, 거래소, 수수료, 유동성 공급자(LP)와의 상호작용을 사용자 정의하는데 사용되는 플러그인으로, 개발자는 후크 메커니즘을 통해 유동성 풀의 수명 주기에서 주요 시점(예: 스왑 전/후 또는 LP 포지션 변경 전/후)에 특정 작업을 실행할 수 있다.

따라서 개발자가 좀더 유연한 방식으로 사용자 정의 로직을 정의하고 실행할 수 있으며, 후크를 특정 유동성 풀에 바인딩하여 풀의 동작과 상호 작용을 제어할 수 있다. 예를 들어, 개발자는 각 스왑 전에 특정 조건을 확인하거나 LP 포지션에 변화가 있을 때 추가 작업을 실행하는 후크를 만들 수 있다. 특정 가격에 도달했을 때 스왑이 실행되게 하는 이른바 지정가 매매(limit order)도 이러한 원리로 가능하게 된다.

Hook 외에도 유니스왑 V4에는 “액션 후크(action hook)”이라 불리는 다른 구성 요소가 있다. 특정 플래그 조건이 충족될 때만 후크 컨트랙트 실행하는 방식이다(아래 순서도를 참조). 예를 들어, 자산 교환 전에 컨트랙트는 유동성 풀의 변동성을 평가하기 위해 플래그를 확인한다. 유동성이 높으면 플래그가 True가 되고, 후크가 실행된다. 만약 유동성이 충분하지 않은 경우라면 플래그는 거짓이 되어 컨트랙트 실행을 거부하게 된다. 이러한 기능을 활용하면 설령 지정가주문을 걸어놓았다 하더라도 해당 시점에서 유동성이 충분하지 못한 경우, swap이 실행되지 않도록 할 수 있는 것이다.

<액션 후크의 작동사례 (출처: YBB Capital Researcher Ac-Core Homemade)>

V4 핵심기능을 활용한 새로운 서비스 전망

V4가 가져올 효과를 한마디로 표현한다면 시장효율성(market efficiency)의 증대다. 물론 상기에서 소개한 V4의 기능들은 최종확정된 것이 아니므로, 향후에 변경될 수 있다. 그럼에도 전체적인 윤곽을 통해 DEX에서 제공가능한 새로운 서비스는 어떤 것이 가능할지 가늠해볼 수 있다.

첫째, TWAMM(Time-Weighted Average Market Maker)이 가능하다.즉, 대량의 주문이 들어오면 한번에 처리하지 않고 일정기간에 걸쳐 대량 주문을 점진적으로 체결함으로써 가격에 미치는 효과를 상쇄할 수 있다. 이는 실시간 상황에 맞게 대응할 수 있는 후크때문에 가능한 서비스다. 따라서 특정가격대의 유동성 부족으로 인해 발생할 수 있는 비영구적손실을 줄일 수 있다.

둘째, 동적 수수료 적용이 가능하다. 유동성 풀은 후크를 통해 시장 변동성이나 기타 입력 매개변수에 따라 수수료를 동적으로 조정하여 시장 상황에 더 잘 적응할 수 있다.

셋째, 시장조정자들이 주로 사용하는 고빈도매매(HFT : High Frequency Trading)도 가능해질 여지가 생겼다. 일반적으로 자본시장에서 고빈도매매는 시장의 거래효율성을 확보해줄 뿐만 아니라, 즉각적인 차익거래를 기반으로 가격 효율성도 증대시켜주는 시장조성자(market maker)의 역할을 한다. 하지만 그간 DeFi 영역에서는 높은 수수료 문제, 그리고 L1에서 요구하는 일정시간의 블록생성시간으로 인해 이러한 고빈도 매매가 불가능했다. 따라서 V3까지는 자동화된 시장조성자(AMM)에 의존하게 되었고 지정가매매도 기술적으로 불가능했다.

하지만 V4부터는 후크를 이용한 지정가거래뿐만 아니라, Multiple fee tier 설정을 통해 장기간 유동성을 제공하는 시장조성자 혹은 고빈도매매에 대하여 수수료를 대폭 인하해 줄 수도 있다. 이로인해 기본적으로는 사전에 제공된 유동성에 의한 AMM 기능을 뼈대로 하되, 여기에 추가하여 시장조성자 역할을 하는 측과 일반 사용자들이 지정가 매매를 함으로써 발생하는 실시간 유동성이 추가될 수 있게 되었다. 이러한 V4가 고속의 거래처리가 가능한 L2기반의 DEX로 구현되면 프로토콜 자체의 처리속도와 수수료까지 저렴하므로 이러한 고빈도 매매에 한걸음 더 다가갈 수 있다.

다만, 공개된 블록체인 상에서 모든 사람이 상대방이 체결하려는 트레이딩을 볼 수 있다면 어떻게 고빈도매매 전략을 설계할 것인지 고민해야 한다. 이러한 거래 투명성은 전통적인 자본 시장과는 다른 고빈도매매 전략을 필요로 한다. 트레이딩 시에 경쟁자의 동일한 전략을 하더라도 좀더 공격적으로 경쟁하거나 투자규모나 투자기간 측면에서 경쟁자가 본질적으로 하기힘든 고유의 전략으로 경쟁을 피하는 방식도 가능할 것이다.

넷째, Defi 서비스의 고도화다. 그간 DeFi 시장은 비효율적이라는 견해가 많았지만 V4의 새로운 기능으로 인해 시장의 효율성을 개선하는 복잡한 금융서비스가 등장할 수 있게 되었다. V4의 지정가거래와 싱글톤 컨트랙트, 여기에 더하여 싱글톤 컨트랙트 내부적으로 다양한 거래가 처리된 후 블록이 종결되는 시점에서의 거래잔액만 청산되는 flash accounting 기능도 도입되어 개별적인 디파이 서비스를 복합적으로 구성하더라도 가스비 걱정이 없는 효율적인 Defi 상품이 가능해진 것이다.

예상되는 DeFi 서비스 고도화를 예를 들어보자면, 실시간 유동성과 연계하는 복합적이고 고도화된 디파이 서비스의 출시를 생각해볼 수 있다. 이는, 후크를 사용하여 실시간으로 유동성 제공이 필요한 범위를 파악한 뒤, 그 범위 밖에 있는 유동성을 자동으로 대출 프로토콜에 예치하는 방식으로 자금의 효용을 극대화하는 것이다.

뿐만 아니라 다수의 토큰에 투자하는 토큰을 출시하여 마치 EFT처럼 거래할 수 있을 것이다. 하나의 싱글톤 컨트랙트안에서 투자대상 토큰으로 모두 교환가능하게 하면 된다. 이렇게 하면 CeFi 세계에서만 해오던 포트폴리오 분산투자를 DeFi에서도 가능하게 할 수 있다.

이러한 분산투자 개념을 론치패드로 확장하면, 유망 프로젝트를 동시에 런칭하면서, 이들 프로젝트에 분산투자하는 펀드토큰을 함께 런칭할 수도 있다. 여기서도 하나의 싱글톤 컨트랙트안에서 투자대상 프로젝트의 토큰으로 모두 교환가능하게 하면 된다.

TONDEX의 새로운 서비스 모색

이처럼 지정가매매뿐만 아니라 고도화된 DeFi 서비스도 TONDEX의 개발방향에 포함될 수 있다. 물론 고객이 얼마나 어디까지 원하는지 사전에 충분히 조사가 되어야 하므로 지속적인 미디엄 아티클 발간과 공개 세미나 등을 통해 고객의 반응과 잠재수요를 정확히 파악하는 것이 필요하다.

고객의 의견을 토대도 개발될 TONDEX는 오픈소스로 공개될 예정이다. TONDEX를 그대로 사용할 수도, 일부 코드를 수정하여 다양하게 응용할 수도 있을 것이다. 이러한 활용성에 대한 상세한 내용은 다음 3편에 이어진다.

참고자료

Uniswap V4: Breaking Down the Upgrades for DeFi Enthusiasts

Uniswap V4: A Saga of Hooks, Bidding Farewell to Fork Swap

Uniswap v4: The liquidity Marketplace

6 Reasons DeFi Will Stay Inefficient (and Profitable)

DeFi Is the Next Frontier of High-Frequency Trading

--

--