Anatomy of an Arbitrage
Background
Whether or not you call it Miner Extractable Value or Maximal Extractable Value, it is hard to deny that MEV is a hot topic within the crypto community. There have been fantastical stories of people quitting their day jobs and raking in 6 figures a month doing MEV(while learning several exotic programming languages). Although for the most part these are fabricated, MEV is profitable for some.
One of the major misconceptions is that the people making money are doing rocket science. Although there certainly is a lot of technical work being done, the overall concepts behind successful MEV strategies are not that complex. There is a huge gap between what people in the MEV community know & what the non-coding people in the crypto space know about the field. In order to demystify the topic for the less technical audience, I thought it would be a good opportunity for me to do an in-depth walk through of an arbitrage bot end-to-end.
The code that I will be going through can be found here & was written by the team at Flashbots. For those of you who are not familiar Flashbots, I will give you a little bit of background on the organization. According to their Github ‘Flashbots is a research and development organization working on mitigating the negative externalities of Maximal Extractable Value (MEV) extraction techniques and avoiding the existential risks MEV could cause to stateful blockchains like Ethereum.’ Flashbots allows Searchers (the coder performing MEV) to circumvent the mempool by directly interacting with miners.
Caveats
A couple of caveats before I start diving in. I do not recommend you run this code with the goal of making money, in fact you will (most likely) lose money running it.
Flashbots has estimated that even if you are familiar with Javascript & Solidity, it would still take 3 months of hard work & dedication to start making money in MEV.
The learning curve for arbs & other MEV opportunities is steep because it requires so many skills:
Knowing Solidity & at least one other programming language
Being good at risk management
Being familiar with Defi
DevOps
Prior Knowledge
Before I dive into breaking down the code, it is worth pointing out that prior knowledge of the following topics will be useful for understanding this but is not not required:
Automated Market Makers
Uniswap (specifically V2), Sushiswap
Smart Contracts
What is Arbitrage?
What is arbitrage? According to Investopedia - ‘Arbitrage is the simultaneous purchase and sale of the same asset in different markets in order to profit from tiny differences in the asset's listed price.’ Arbitrages have been around for a long time in TradFi before the rise of MEV in crypto space.
The rise of Automated market maker (AMMs) has coincided with the rise of arbitrage in the crypto space. ‘Automated market makers are autonomous trading mechanisms that eliminate the need for centralized exchanges and related market-making techniques.’[Source] You can think of AMM as a computer program that automates the process of providing liquidity.
The largest and most popular AMM is Uniswap, which has inspired many forks, including Sushiswap. Uniswap has reinvented its mechanics a couple of times, but this arb focuses on V2. The mechanics of Uniswap V2 are relatively simple. Each trading pair has a pool containing each token. Uniswap uses the 'constant product market maker model' to determine the price of the pair. The formula is simply x*y = k. Which states that the reserves of each token must not change the product(k) after a trade is performed.
The basic idea of arbitrages(or arbs, for short) in crypto is to find mispricing of an asset in two (or more) markets and make a profit. Hypothetically you could do this manually but it would be quite the time costly process (& the bots would eat your dinner) so coding is the best option.
How does an Arbitrage work?
What I explained a bit earlier is the simplified version of an arb. What actually goes on under the hood is a little bit more complex. The rest of this article will go over how the ‘simple-arbitrage’ bot works.
Environment Set up
Setting up your environment. In order to run any code that interacts with Ethereum, you need a couple of things:
Wallet private key
Node RPC URL
This is how you access Ethereum data
Addresses of the AMMs you want to interact with
Address of the coins you want to look for arbitrages
Bot part 1: Gathering Information
Now that some of the logistical stuff is out of the way, let's get to the fun part. The meat & potatoes of an arb bot is figuring out which exchanges have pairs with different prices. So first & foremost, this bot gathers & aggregates the addresses of several known dexes. It then calls Uniswap’s smart contract, to get an aggregated list of every single (!) Uniswap pair(it does this for the other AMMs of interest, as well). Now, since this bot is requesting so many pairs, it does it in batches, allowing for the most efficient process.
Now what happens after we get all pairs? Technically, we could start looking for arb opportunities. However, these bots deploy another layer of filtering to make this process even quicker. They filter out all pairs that do not have Ethereum. Why? Ethereum is the currency of bribing(we will get to this later) in Flashbots, so it makes everyone’s lives easier if the arb involves it. Supplementary, looking for pairs that involve Ethereum makes it easy for finding the optimal trading path - all arbs will look like this :
Exchange Ethereum for Token A on Exchange A
Exchange Token A for Ethereum on Exchange B
Another mechanism it employs is that it only keeps pairs that have a pair on another exchange (i.e. a possible arb opp).
Bot part 2: Looking for arbitrage opportunities
Now that we have all the pairs we can get to finding arbs. This program has a clever mechanism where it ‘listens’ to every new mined block on Ethereum. Once it detects a new mined block it does a couple of things. First it it calculates the reserves for each token in all of the pairs we are tracking(important for determining the optimal arbitrage amount).
After calculating reserve amounts, it then iterates through every pair to see if there exists a combination with mismatched pricing on two exchanges. Now, normally this would be enough. However, due to the mechanisms behind Uniswap, this is not. In order to maximize profit, there is a certain value of Ethereum you must trade with. Why? It has to do with the market maker conditions of Uniswap V2 (remember xy =k?). Depending on the reserves, the optimal trading amount changes. So in order to find this amount, the author brute forces through a list of possible trading amounts to find the one with the largest money-making potential. Although this logic may work, it is slow & there are better ways to do this using statistics/calculus
Once this is done - the author begins to work with Flashbots. As I alluded to earlier, Flashbots is a service that allows searchers to directly interact with miners. A major part of this system is paying miners with ‘bribes’ so your transaction will be included in the optimal block. Another key part of this game is making your transactions as gas-efficient as possible.
An added benefit is Flashbots allows you to simulate transactions. This allows you to test if you transaction will work(if it does not you can revert it). Secondarily, it allows you to estimate the amount of gas you will need to spend. Once you test that it works, send your transactions in & that is the end of the process!
Conclusion:
This was a fairly simple arb bot. As I alluded to in various parts of the piece, it can be optimized in many different ways. However, what I went over is the skeleton of how most arbitrage bots work.
Arbs are a very large piece of the MEV pie but they are not the only strategy in town. Liquidations, sandwiches & forms of long-tailed MEV are other examples.
If you enjoyed this piece - give me a follow on Twitter & follow my blog. I hope to demystify other technical pieces of crypto.
