Introducing LongSwap: an MEV resistant AMM

Introduction

Have you ever swapped tokens on a DEX like Uniswap or Balancer? If yes, then there’s a chance that you have been a victim of a sandwich or frontrunning attack. In most cases, these attacks would steal a tiny fraction of your transaction value, so you might not even notice. But in case of a large transaction, the impact could be as high as a hundred thousand Dollars! Estimates of total value lost to MEV attacks are ~$700 Million+.

Another downside with traditional AMMs is high slippage for big orders. This prevents protocols/DAOs from getting good value for their sizable holdings or automating their treasury management.

One solution proposed to these problems is Time-Weighted Average Market Makers or TWAMMs. Envisioned by the Paradigm research team in 2021, TWAMMs provide a gas efficient way to execute swaps on-chain without worrying about MEV attacks.

TLDR: Announcing LongSwap TWAMMs for MEV resistant swaps, low slippage on large transactions and Time-weighted average price orders. Try LongSwap today here.

What is a TWAMM?

In simple words, a TWAMM is an AMM that allows one to place a long-term order. That is, a swap transaction that swaps given tokens to desired tokens, over a specified time duration.

Contrast this to a traditional DEX swap, that immediately swaps tokens in a single block. How does swapping over multiple blocks help? 

Protection against MEV attacks

Most sandwich attacks use Flash loans. Since flash loans need to be repaid in the same block, order execution over multiple blocks, flash loans can’t be used.

Also, for MEV attacks, the attacker needs to collude with the block creator. This becomes increasingly difficult over many blocks.

Low slippage for large orders

In a traditional AMM, the larger the size of the order, the more slippage is to be expected. This slippage depends on size of the order and liquidity in the pool.

But in a TWAMM, the orders are executed in many small chunks (Virtual Orders), each incurring much less slippage. Meanwhile, the gas costs are a fraction of what it’d cost if you were to execute all these swaps yourself.

Time-Weighted Average Price

Many entities, such as DAOs or derivative protocols may need to restructure their treasuries/collateral from time to time. When they do it, they wouldn’t want a huge market impact and want to dollar cost average their token purchases over time.

With LongSwap, these entities can permissionlessly, transparently and gas-efficiently swap a huge amount of tokens and get a Time-weighted average price for their orders.

Technical architecture

A TWAMM is basically a smart contract that has a traditional constant-product AMM embedded within. This smart contract keeps track of long-term orders (LTOs) and executes small chunks of the LTOs, called virtual orders (VOs), against the embedded AMM.

TWAMM workflow
TWAMM workflow

Since a smart contract can’t initiate transactions against itself, TWAMM design relies on arbitrageurs for this. 

Whenever an arbitrageur executes a traditional or “short swap” on the TWAMM,  it first executes all the pending VOs, passing on the gas costs to the arbitrageur. But it also creates an incentive for them. After all VO executions, it is likely that the AMM will be slightly unbalanced compared to market prices. An arbitrageur can exploit this disparity to make up for their costs.

Arbitrageurs can query the state of the smart contract at every block and as soon as it becomes profitable, they can execute the trade. If they wait further, it is possible that a swap becomes more profitable, but it is also possible that some other arbitrageur executes the swap earlier at a lower profit. This competition increases the number of times VOs are executed and keeps the prices very close to the market prices.

LongSwap implementation

LongSwap has implemented TWAMM on Balancer V2.

LongSwap architecture
LongSwap architecture

LongSwap is implemented as a Balancer v2 custom weighted pool. Thus, most interactions with the pool take place via Balancer Vault. And Vault calls certain hooks on the pool contract.

Due to contract size limit on Ethereum, we have to back every TWAMM pool with another contract which keeps account of all active long term orders and their respective payouts.

Why Balancer?

Balancer offers a framework to build custom pools. With custom pools you can handle all the math for an AMM, whereas Balancer Vault holds the tokens and takes care of balance transfers.

This gives developers flexibility to implement something complex like TWAMM. While, the Vault takes care of many routine tasks like minting/burning LP tokens, token transfers, etc, in a secure, battle tested way.

Another benefit of building on Balancer is arbitrage efficiency. Arbitrageurs can do swaps using internal balances and Flash swaps and some of this value gets transferred to users placing Long-term swaps.

How do I use it?

You can use LongSwap today using following two methods:

Using the UI:

  1. Go to app.longswap.xyz.

  2. Choose pair, amounts, duration.

  3. (One time) approve Balancer vault to spend your tokens.

  4. Place a Long term order.

  5. After the duration has elapsed, come back and withdraw your bought tokens.

  6. You can also cancel the order mid-way, or do a partial withdrawal, without canceling the order.

Directly interacting with the smart contract:

DAOs and power users may want to bypass the UI. You can directly interface with the smart contracts as follows:

  1. You have to first send a join transaction of kind PLACE_LONG_TERM_ORDER to Balancer Vault.

  2. You will get an order id and an expiration block in the LongTermOrderPlaced event.

  3. After the blockchain reaches the expiration block, place an exit transaction of kind  WITHDRAW_LONG_TERM_ORDER with your order id.

For more details visit our Documentation.

Security

Our contracts have been reviewed for security by Certora as part of their accelerator program.

Also, most of non-math functionality, such as token transfers are handled by Balancer Vault, which has been battle-tested over the past two years. So, we get protection against  common attacks like re-entrancy for free.

Conclusion

In future posts, we’d like to talk more about how we handled some of the key challenges.

  • Protection against Denial of Service attacks

  • Gas optimizations

  • Scalable distribution of rewards, and more…

We can’t wait for you to try out LongSwap at app.longswap.xyz. For any feedback, suggestions, collaboration requests, feel free to reach out at codesherpa.xs@gmail.com or DM on Twitter at @FinanceXs.

Subscribe to LongSwap
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.