BTC
ETH
HTX
SOL
BNB
View Market
简中
繁中
English
日本語
한국어
ภาษาไทย
Tiếng Việt

TWAMM: A New Idea for Efficiently Handling Large Orders on Uniswap

Moni
Odaily资深作者
This article is about 8709 words, reading the full article takes about 13 minutes
An article to understand the new automated market maker TWAMM.
AI Summary
Expand
An article to understand the new automated market maker TWAMM.

overview

Odaily Translator |


overview

This paper introduces a new type of automated market maker (AMM) that can help traders on Ethereum execute large orders efficiently.

We call it the Time Weighted Average Market Maker, abbreviated as TWAMM (pronounced "tee-wham").

Introduction

Introduction

Suppose Alice wants to buy $100 million worth of ETH on-chain, it would be very expensive to execute an order of this size on an existing AMM like Uniswap, this is to prevent Alice from knowing something inside that they don’t , so it must charge Alice a high fee.

Now, Alice's best option is to manually split her order into several parts and execute them within a few hours, giving the market time to realize she has no inside information and give her a better price.

If she sends several large sub-orders, each order still has a significant impact on price and is vulnerable to sandwich attacks by adversarial traders. On the other hand, if she sends many small sub-orders, she will have to take on all the work and risk of the active transaction, and will pay the miners a high cost in the form of transaction gas fees.

secondary title

Two basic concepts related to "market making"

1. Market Maker

Consider this market has two financial assets, say USDC and ETH. The market maker is a participant in this market, and he hopes to trade any asset with another asset at any time.

If you have 100 million USDC and want to use it to buy ETH, you may not be able to find another person who wants to do the opposite transaction at the same time. Instead, you will likely enter a market that consists of one or more market makers and trade with them.

2. Adverse selection

The profit market makers make from the spread is effectively a fee they charge on each trade. They lose money when prices go against them—when they buy an asset and the price goes down, or sell an asset and the price goes up.

Unfortunately for market makers, prices tend to move in the opposite direction of their operations, a phenomenon known as adverse selection. This happens because traders who are informed about future price movements are more likely to place large trades with market makers.

secondary title

Automated Market Maker

text

1. Constant trading formula

The constant trading formula is a simple rule that allows anyone to instantly create a new market and a new AMM for a new pair of assets.

To create a new constant transaction AMM (CPAMM) between two assets X and Y, a user called a Liquidity Provider (LP) deposits reserves x and y of these two assets.

The ratio of these assets at any given time represents the instant price on the AMM, or the price it charges for a very small order. For example, if a CPAMM has 2,000 USDC and 1 ETH in its reserves, its instantaneous price of ETH will be 2,000 USDC.

text

2. Examples

For example, a CPAMM of ETH/USDC has 2,000 USDC and 1 ETH in its reserves, so x = 2,000, y = 1, so x * y = k = 2,000. The instantaneous price of this AMM is 2,000 / 1 = 2,000 USDC per ETH.

If a trader comes to buy 2,000 USDC worth of ETH, that means they deposit 2,000 USDC in X for reserve, so we will have x = 2,000 + 2,000 = 4,000.

Then, since k = 2000, we must get y = x/k = 2000/4000 = 0.5 after the transaction. Since y was originally 1, 1 – 0.5 = 0.5 ETH must have flowed to the trader.

Since traders bought 0.5 ETH with 2000 USDC, the average price they paid was 4,000 USDC per ETH. This high price relative to the instantaneous price reflects the large order size on AMM liquidity.

3. Price effects and adverse selection

In the above case, when the cost of a small order is only 2,000 USDC per ETH, the trader has to pay a fee of 4,000 USDC per ETH for his large order. This price difference is called the price impact of the order. The larger the size of the incoming order, the greater the impact on the price.

secondary title

Execute large orders on the current AMM

1. Split the order manually

As we have seen, the transaction costs of executing a single large order on an AMM are set to be high. This excellent article digs into the issue and recommends some solutions.

In short, traders who wish to execute large orders on an AMM should not execute them in a single trade: they are better off splitting the order into several parts. This may involve sending orders to multiple AMMs at once, but those AMMs also have limited liquidity at any given point in time. Over time, the larger the order, the more it makes sense to split it up.

For example, let's say an investor wants to buy $100 million in ETH on-chain, but since they don't have any short-term information about the price of ETH, their order may take some time to execute. In this case, they might split the order into 10 orders of $10 million each and execute them every hour, thereby reducing the price impact of each order.

2. Trade-offs for sub-order sizes

Obviously, if a very large order is split into parts, each individual sub-order will still be large and have a corresponding price impact. At this time, it is useful to split the order into smaller ones, but this will bring two new problems at the same time.

The first problem is operational complexity, which means increased risk and workload. A trader may split his trade into the wrong amount or choose the wrong direction. On the other hand, his computer might crash in order to prevent some orders from being executed. And even if everything goes well, the process takes time and effort, which can affect people's attempts at more valuable things.

secondary title

Analogy with traditional finance

In the traditional financial field, if investors or institutions want to buy $100 million in Apple stock, they will not directly send a $100 million market buy order to the exchange. They also don't send 10 orders worth $10 million. Splitting an order into sub-orders much smaller than this is impractical for the vast majority of people without dedicated trading staff and infrastructure.

Instead, they are likely to send large orders to a broker, who will do the algorithmic trading for them for a fee. The broker will execute the trade for a specified period of time, say eight hours, with prices referenced to a certain standard. The broker has a team dedicated to executing such trades safely and economically.

1. TWAP order

Perhaps the most basic type of algorithmic trading is the time-weighted average price or TWAP (pronounced "tee-whap") order. As the name implies, if a TWAP order worth $100 million in Apple stock is executed within eight hours, it will eventually be traded at a price close to the time-weighted average price of Apple stock within that time period.

For example, if Apple stock traded at $100 for four hours and $120 for the other four hours during the period, the time-weighted average price would be ($100 * 4 + $120 * 4)/8 = $110 , the broker will execute TWAP orders close to that price.

While the details of how this works vary, brokers will most likely execute this trade by breaking it up into many smaller portions and sending them to the market throughout the day. Buying $100 million of Apple stock in 8 hours is equivalent to buying roughly $350 of Apple stock every 100 milliseconds, something we should all expect a broker to do.

secondary title

Time Weighted Average Market Maker

Time Weighted Average Market Makers (TWAMM) provide the on-chain equivalent of TWAP orders. With its own unique logic algorithm for order splitting and direct connection with embedded exchanges, TWAMM executes smooth transactions with lower gas fees. At the same time, arbitrageurs will align the price of the TWAMM embedded exchange with the market price, ensuring execution around the time-weighted average price of the asset.

1 Overview

Each TWAMM facilitates transactions between specific asset pairs, such as ETH and USDC.

TWAMM includes an embedded AMM, which is a standard constant product market maker for both assets. Anyone can use this embedded AMM to transact at any time as if it were a normal AMM.

Traders can submit standing orders to TWAMM, which are orders to sell a fixed amount of an asset for a fixed number of blocks — for example, an order to sell 100 ETH in the next 2,000 blocks.

TWAMM decomposes these standing orders into an infinite number of infinitely small virtual sub-orders that will be traded with the embedded AMM at a uniform rate over time. Be aware that processing these virtual sub-order transactions individually would cost an infinite amount of gas, but closed-ended math allows us to calculate their cumulative impact only when needed.

Over time, the execution of standing orders will push the price of the embedded AMM away from the price of other markets. When this happens, arbitrageurs will trade against the embedded AMM price, keeping it aligned, ensuring good execution of long-term orders.

If the long-term sale makes ETH on the embedded AMM cheaper than a specific centralized exchange, then arbitrageurs will buy ETH from the embedded AMM and sell it on the centralized exchange to make a profit when its price recovers.

2. Ethereum update

2.1 Blocks

Ethereum packages transactions into sequential chunks, also known as blocks, that occur approximately every 13 seconds. In this article, we will number each block: block 1 is followed by block 2, then block 3, and so on.

2.2 Miners

Decentralized groups of miners compete to process each block, and anyone with an internet connection can become a miner. This means that running a program like an AMM on Ethereum is non-secret: everyone has to calculate exactly what will be produced given the inputs.

2.3 Gas fee

Computing power is a scarce resource on Ethereum, so users must pay miners in the form of gas fees. The more computation involved in a given transaction, the more gas it consumes. And this gas fee is paid entirely by the person submitting the transaction.

3. Basic transaction design concept

3.1 Standing orders

Alice wants to buy 100 million USDC worth of ETH within the next 8 hours, or about 2,000 blocks. She enters a standing order in TWAMM to buy 2,000 block ETH worth 100 million USDC, which equates to 50,000 USDC per block.

As mentioned above, we do not know in advance which miners will process these future transactions on TWAMM. This also means that Alice's order must be visible to everyone, leading to the information leakage problem we will discuss below.

3.2 Order pool

Suppose Bob wants to sell 500 ETH at USDC price in the next 5,000 blocks, which is equivalent to selling 0.1 ETH per block.

And Charlie wants to sell 100 ETH at the price of USDC in the next 2,000 blocks, that is, sell 0.05 ETH per block.

As soon as Charlie's order expires within 2,000 blocks, Bob's and Charlie's orders are combined in a pool.

This ETH sale pool will sell ETH at 0.15 ETH per block for the next 2,000 blocks. Bob will be able to get 66% of the USDC earned by the mining pool (0.1/0.15 ≈ 66%); Charlie will get 33% of the USDC earned by the mining pool (0.05/0.15 ≈ 33%).

3.3 Virtual order

For the next 2,000 blocks, TWAMM must buy 50,000 USDC worth of ETH on behalf of Alice and sell 0.15 ETH in USDC on behalf of the ETH selling pool.

We can imagine that TWAMM splits these two sub-orders into trillions of sub-orders of tiny sub-orders, which we call virtual orders (actually, it splits them into an infinite number of infinitesimal virtual orders).

The TWAMM then takes turns executing these virtual orders against its embedded AMM: first Alice's virtual order, then one from the ETH sales pool, then another Alice's order, and so on.

3.4 Arbitrage

Because Alice bought much more ETH than the ETH pool sold, the price of ETH on the embedded AMM will increase every block.

When this price is high enough relative to ETH prices elsewhere, arbitrageurs will buy cheaper ETH on other exchanges and sell it on the embedded AMM, bringing their price in line with the market average and ensuring better execution Alice orders. '

3.5 Order Expiry

After block 2,000, Alice's order will be fully executed, as will Charlie's order. Bob's order to sell ETH is still valid for the next 3,000 blocks, during which TWAMM will continue to execute at a rate of 0.1 ETH per block.

Barring any other external activity, over time this will force the price of ETH on the embedded AMM lower, and will also allow arbitrageurs to recover once they get out of the price.

3.6 Token Economy

Because neither Alice, Bob, nor Charlie is eager to execute their orders, other market participants can infer that their orders represent less adverse selection than would otherwise be the case and can provide them with low price-impact execution.

text

4. Infinitesimal Virtual Orders

We mentioned above that TWAMM splits long-term orders into infinitely small sub-orders. This is done for two reasons: fluency and efficiency.

4.1 Fluency

The main goal of TWAMM is to execute long-term orders smoothly over time so that they can be executed at prices close to the prevailing time-weighted average price.

As we reduced the size of the virtual trades, the price movement on the AMM became smoother.

In extreme cases, the price movement is very smooth when executing virtual trades due to the infinite number of infinitely small trades.

4.2 Efficiency

implement

implement

1. Lazy Evaluation

TWAMM treats virtual sub-orders as taking place in the space between blocks, which is important for evading sandwich attacks.

To achieve this in a gas-efficient manner, TWAMM uses lazy evaluation, computing the impact of a virtual transaction only when it needs to determine the outcome of an interaction.

Every time a user interacts with TWAMM (for example, by placing a trade using the embedded AMM or adding a new standing order), TWAMM retroactively calculates the impact of all virtual trades that occurred since the last interaction.

Since these virtual transactions only interact with TWAMM's embedded AMM, TWAMM behavior is fully deterministic between external interactions. Even if TWAMM moved 1 million blocks between external interactions, the next time someone interacts with it, it will still be able to accurately calculate the outcome of all intervening virtual transactions.

For frontends that plug into TWAMM, virtual transactions that are not yet represented on-chain can be processed by keeping track of the current block number and doing the TWAMM calculations themselves.

2. Gas optimization

2.1 Pooling Orders

As the example shows, when we have multiple standing orders in the same trade direction (i.e. sell ETH for USDC), we pool them together and then split them into virtual orders. TWAMM can then use an algorithm to track balances, the same version of the algorithm that tracks billions of dollars of LP token incentives in protocols like Compound and Uniswap.

Technically, each TWAMM always has two long-term order pools, one for each asset: for example, an order pool for selling USDC and an order pool for selling ETH. It's worth mentioning that at any given time, one or both of these order pools may be empty.

2.2 Long-Term Order Expiration

A complication arises when using order pooling with lazy evaluation.

Imagine that Bob places a standing order to sell 100 ETH in the next 100 blocks, and Charlie also places an order to sell 200 ETH in the next 200 blocks, both orders Both are sold at a price of 1 ETH per block.

Assuming no one interacts with the TWAMM for the next 150 blocks, at which point a new external interaction occurs. In the first 100 blocks after Bob and Charlie place their order, their orders will be pooled into a common order that sells 2 ETH per block. However, for the next 50 blocks, Charlie's order becomes independent and only sells 1 ETH per block.

This means we have to do two separate transaction calculations to find out what happened:

* Calculate the results of the first 100 blocks at a time;

* Calculate the results of the last 50 blocks at a time.

In the worst case, if every block for the past 150 blocks has an order expiration, it means that TWAMM will have to process one transaction per block, destroying gas efficiency.

The simplest solution to this problem is to limit the number of blocks that are eligible for order expiration: for example, TWAMM could specify that orders only expire every 250 blocks, or approximately every hour.

2.3 Canceling Long-Term Orders

Users can cancel standing orders at any time. In practice, this would allow users to choose a cancellation time for their own orders until the block completes the order transaction. In this case, the gas burden on the system does not increase, since all cancellations are the user's own decision and thus require them to pay for the gas themselves.

3. Virtual Trade Math

3.1 Definition

Suppose t blocks have been produced since the last time TWAMM performed any virtual transaction.

For simplicity, assume no long-term order expires, so the pool that sells X sells x_{rate} per block for the entire time period, and the pool that sells Y sells y_{rate} per block for the entire time period part.

Then the total amount of X sold during this period is tx_{rate} = x_{in}, and the total amount of Y sold during this period is ty_{rate}=y_{in}.

Let us denote the AMM reserves embedded at the beginning of the time period as x_{ammStart} and y_{ammStart} respectively.

3.2 Formula

in

in

From the constant product formula, we know

secondary title

Similarly,

potential attack vector

1. Sandwich attack

1.1 Description

In the sandwich attack, the attacker Atticus sees that the trader Trey is about to trade on the AMM. Atticus profited by sending two orders, sandwiching Trey's order.

Imagine that Trey sent an order to the AMM to buy ETH with USDC, and Atticus discovered the order at this time, so Atticus placed the order before Trey and bought ETH on the AMM, driving the price up. Atticus is losing money on this order since he is paying the AMM and having a price impact.

When Trey's order was executed, he had to buy ETH at a higher price because Atticus pushed up the price, and at this time Trey's actual order price was further pushed up.

Now, Atticus is selling his ETH back to the AMM. Since Trey has pushed up the price of the AMM since Trey bought it, he is actually selling at a higher price than he bought it, so he is able to make a profit.

However, this attack only makes sense for Atticus if Atticus can guarantee that Trey will sell his ETH back to the AMM immediately after the purchase. This type of attack is actually possible if Atticus is a miner, makes a deal with a miner, or uses a service like Flashbots within a given block.

1.2 Sandwich order and virtual order

At first glance, virtual orders seem especially vulnerable to sandwich attacks because everyone knows they're coming.

However, since they are executed between a certain number of blocks, orders are preserved. A dummy order attacker who wants to "clip" TWAMM would have to trade with the embedded AMM at the end of a block, which would cause the dummy order to be executed at a bad price between blocks, and then start at the next block trade in the other direction.

Currently, there is no way for an attacker to guarantee that they will only transact at the end of a given block, since the attack can only be performed on the premise that they must transact at the beginning of the next block. The problem may become more acute when multiple blocks of maximum extractable value (MEV) become more common and allow traders to be sandwiched between multiple blocks.

2 Information disclosure

The biggest tradeoff that long-term traders may encounter in TWAMM is that they face the risk of information leakage when placing "publicly visible" orders, which is difficult to avoid due to the nature of Ethereum.

If a trader places a standing order of a large enough size, other traders may want to front him/her and buy the asset in the TWAMM embedded AMM and elsewhere to later sell it back to the exchange as a standing order Zhebin pushed up the price.

Since users can cancel their standing orders at any time, we expect overly aggressive traders with large orders to be exploited by other traders, therefore, we need to control the overall impact of information leakage.

2.1 Example

Imagine that fraudster Sally has noticed an aggressive front-running opportunity on TWAMM. At this point she was able to buy $1 million in ETH from the liquidity aggregator, which in turn drove up the price of the entire market. She can then place a large long-term order on TWAMM, however, to buy $100,000 in ETH every block for the next 24 hours.

secondary title

here

You can findhereCheck out the Python reference implementation of TWAMM.

on GitHubJupyter Notebook Demonstrates the behavior of TWAMM, which contains multiple canceled standing orders and the operation behavior of arbitrageurs.

in conclusion

in conclusion

We have outlined the design framework for TWAMM, but our work has only just begun.

If you are interested in solving this or similar problems, you can contact Uniswap Labs by email or DM on Twitter.

ETH
Uniswap
Welcome to Join Odaily Official Community