Secret Markets: Front Running Prevention for Automated Market Makers
Learn how constant function market makers powered by "secret contracts" on Secret Network can address privacy and usability challenges for decentralized exchanges like Uniswap 🦄
Hello Secret Agents!
Today, we’re delving into a very specific and obvious problem faced by centralized and decentralized exchanges: FRONT RUNNING. While front running has existed in traditional finance for decades, it is an illegal attack vector that only insiders may exploit. However, due to the public nature of blockchains, front-running attacks happen all the time. Because users can see transactions and their corresponding gas prices before a block is mined, it is easy for attackers to submit a transaction with a higher gas price, which would result in their own transaction being mined first.
For this post, we are interested in examining the front running problem in the context of Automated Market Makers (AMMs). This will help explain how Secret Markets (a Secret Uniswap built on Secret Network) will prevent and mitigate front running. In 2019, I wrote about preventing front running with private smart contracts, specifically exploring how front running affects decentralized exchanges with open order books, such as 0x.
These days, almost all of the DeFi volume is on AMMs, where the problem of automated front running is still very real. In fact, Hayden Adams, the creator of Uniswap, introduced the original smart contracts to Vitalik Buterin in this thread about improving the front-running resistance of constant-product market makers!
“Blockchains, and specifically smart contracts, have promised to create fair and transparent trading ecosystems. Unfortunately, we show that this promise has not been met. We document and quantify the widespread and rising deployment of arbitrage bots in blockchain systems, specifically in decentralized exchanges. Like high-frequency traders on Wall Street, these bots exploit inefficiencies in decentralized exchanges, paying high transaction fees and optimizing network latency to frontrun, i.e., anticipate and exploit, ordinary users’ trades.”
Front Running on Automated Market Makers
Front-running attacks on AMM platforms like Uniswap are fairly easy to grasp, if you are familiar with blockchain technology and smart contracts. It’s not really surprising that Bancor experienced a front-running attack soon after going live. Uniswap is no different; however, it's indirectly providing liquidity for many tokens within Ethereum DeFi.
"While automated market makers have been studied in both theory and practice, “constant function market makers” (CFMMs) have applied a deterministic pricing rule in the context of digital asset exchange, redefined the process of liquidity provisioning for market making, and effectively democratized access to global pools of capital." – Dmitriy Berenzon
Uniswap Liquidity Mechanism
Uniswap is powered by a constant product formula and implemented in a system of non-upgradeable smart contracts on Ethereum. It obviates the need for trusted intermediaries, prioritizing decentralization, censorship resistance, and security.
Pairs act as automated market makers, standing ready to accept one token for the other as long as the “constant product” formula is preserved. This formula, most simply expressed as
x * y = k, states that trades must not change the product (
k) of a pair’s reserve balances (
k remains unchanged from the reference frame of a trade, it is often referred to as the invariant.
- When the supply of the underlying token reserve decreases as Alice is buying, the price of the token being purchased increases
- When the supply of the underlying token reserve increases as Alice is selling, the price of the token being sold decreases
“Because Ethereum transactions occur in an adversarial environment, smart contracts that do not perform safety checks can be exploited for profit. If a smart contract assumes that the current price on Uniswap is a “fair” price without performing safety checks, it is vulnerable to manipulation. For example, a bad actor could easily insert transactions before and after the swap (a “sandwich” attack) causing the smart contract to trade at a much worse price, profit from this at the trader’s expense, and then return the contracts to their original state.”
Basically, given the public nature of many blockchains, attackers can see large buy / sell orders that will change price significantly. Leveraging this knowledge, Bob can insert transactions in front of Alice’s. In other words, actors who can influence the order in which transactions are included in a block can affect the economic outcome of trades. This poses an obvious challenge to the blockchain industry and cryptocurrency markets. Arbitrage bots of this nature cost exchanges and their users millions of dollars (at least)!
Privacy is necessary for the universe of decentralized finance to grow from Billions to Trillions of dollars in total value.
Front Running on Uniswap
According to this recent audit of Uniswap, two strategies for exploitation can be used by anyone who can see unconfirmed transactions and submit their own transactions with carefully chosen gas prices. The Uniswap router includes some features that provide some degree of protection against the first strategy, but no such mitigations exist for the second.
1. Moving the Market Against the Trader
In this variant, an actor who can observe unconfirmed transactions can attempt to insert trades before and after the target trade, manipulating the Pair's price in a way that will result in a profit for the attacker, and a worse price for the trader.
2. Sandwiching Large Trades With Mint and Burn
In this second variant, the attacker watches for large trades, and sandwiches the target trade with calls to mint and burn with a very large position relative to the initial size of the pool. The attacker is therefore able to extract a sizable proportion of the LP fees for that trade without exposing themselves to the price risk inherent to providing liquidity on Uniswap. Neither the core protocol nor the periphery contracts have guards against this attack...
“To mitigate frontrunning, Uniswap allows traders to specify a maximum price when placing an order. Therefore, if a miner front runs an order, the user cannot be forced into accepting the worse price. Although they might miss the trade, they won’t suffer from a costlier price. Combined with expiring orders to prevent miners from withholding signed transactions and processing them at a more advantageous price, it’s clear that Uniswap has a very user-first mindset.” -- Cooper Turley, formerly of DeFi Rate
How can Secret Network help?
Secret Network enables privacy-preserving, “secret” smart contracts with encrypted inputs, outputs, and state. Nobody, including the nodes running and validating the computations, can see any private data processed within secure enclaves. The pool of incoming or unprocessed transactions would be a secret.
In other words, we have an encrypted mempool. This prevents malicious actors from gaining unfair advantages over honest users by watching the mempool. Therefore, Secret Network is in a great position to create a fairer DeFi ecosystem!
Decentralized Finance on Secret Network
As we have alluded to earlier, the Secret Network community is developing several building blocks, which will create a fully private and front-running resistant DeFi product for the blockchain ecosystem. These building blocks include:
- Secret Token standard: ERC-20 like smart contract based token issuance. Given the encrypted nature of secret contracts, SecretTokens are privacy tokens
- Ethereum ←→ Secret Network multi-sig bridge: Lock assets on Ethereum and mint wrapped privacy tokens (ETH ←→ secretETH) on Secret Network
- Secret Markets AMM built with secret contracts to provide front-running resistance and anonymity to ETH DeFi users
When these building blocks are functional, Ethereum and ERC-20 token holders will be able to do the following:
- Deposit ETH or ERC-20 tokens and mint corresponding secret tokens
- Send tokens to other Secret Network participants (transactional privacy),
- Swap tokens privately with no need to worry about front running (computational privacy)
- Withdraw ETH or ERC-20 tokens and burn secretETH or secretERC-20s
The more actions each and every user does with secretETH or any other secretTokens on Secret Network, the more privacy they will get at a lower cost. This creates privacy network effects - meaning programmable privacy is also composable privacy!
So what now? Well, all of these ideas gain power as liquidity on Secret Network increases. We have been watching the development of the overall DeFi ecosystem closely and we have some interesting ideas for bringing more activity and more users to Secret Network... so stay tuned. 🤫