# The 0 to 1 Guide for MEV **Published by:** [Blockchain at Berkeley](https://paragraph.com/@blockchainatberkeley/) **Published on:** 2021-12-21 **URL:** https://paragraph.com/@blockchainatberkeley/the-0-to-1-guide-for-mev ## Content By: 0xmebius This is a quick and dirty guide to MEV meant to get you up to speed on the latest in the space, nothing more, nothing less. The guide is sorted so that each subsequent topic builds upon previous knowledge, and increases in complexity as topics advance. Obviously skip things you already know. The guide is also nested depending on the level of depth you wish to explore for each particular topic. Each nested child topic represents a further niche concept in the parent topic. Most general Crypto/DeFi topics will just point you to existing high quality material (no need to reinvent the wheel) but more advanced MEV topics (and alpha) will consist of everything I know and what I’ve learned along the way. Just be warned this is effectively throwing you in the deep end. By the end of this you should be able to build your own MEV Bots. Good luck!OverviewBackgroundWhat is Blockchain?What is Ethereum?Smart Contract OverviewWhat is DeFi?ERC-20 Token OverviewWhat are Stablecoins?What are AMMs?What are Decentralized Banks?ForksCentralized ExchangesMEVMEV Strats 101SandwichingArbitrageLiquidationsFrontrunningJIT LiquidityLong Tail MEVExample MEV BotsPGAsFlashbotsSmart Contracts & Dev ToolingGame Theory, Social Dynamics & SecurityAlpha LeaksRust ResourcesBackgroundWhat is Blockchain?Easy (~5min): https://www.coinbase.com/learn/crypto-basics/what-is-a-blockchain Medium (~30min)Blockchain Facts: What Is It, How It Works, and How It Can Be UsedA blockchain is a digitally distributed, decentralized, public ledger that exists across a network. It is most noteworthy in its use with cryptocurrencies and NFTs.https://www.investopedia.comWhat is Ethereum?Easy (~5min):What is Ethereum? (A Complete Guide) | ethereum.orgA full overview of what Ethereum is, how it works, what it does and how to start using or building on it. Explained in simple terms.https://ethereum.orgMedium (~1hr):Ethereum Whitepaper | ethereum.orgAn introductory paper to Ethereum, published in 2013 before its launch.https://ethereum.orgHard (~1 day):Developer Intro:Ethereum development documentation | ethereum.orgIntroducing the ethereum.org developer documentation.https://ethereum.orgRabbit Hole:Ethereum: A Comprehensive Learning GuideYour educational guide to the world of Ethereum. Learn how Ethereum works and how to connect to it. This page includes technical and non-technical articles, guides, and resources.https://ethereum.orgSmart ContractsEasy:Smart contracts: What are they and their benefits | ethereum.orgA non-technical introduction to smart contractshttps://ethereum.orgHard: https://github.com/ethereumbook/ethereumbook/blob/develop/07smart-contracts-solidity.asciidoc#what-is-a-smart-contract Learn through a Course (~7 Days):#1 Solidity Tutorial & Ethereum Blockchain Programming Course | CryptoZombiesCryptoZombies is The Most Popular, Interactive Solidity Tutorial That Will Help You Learn Blockchain Programming by Building Your Own Fun Game with Zombies - Master Blockchain Development with Web3, Infura, Metamask & Ethereum Smart Contracts and Become a Blockchain Developer in Record Time!.https://cryptozombies.ioLearn Everything Fast (~1 Day):Learn By Example:GitHub - JamesANZ/learn-solidity-with-examples: A repo full of smart contracts written in solidityA repo full of smart contracts written in solidity - JamesANZ/learn-solidity-with-exampleshttps://github.comBoilerplate Code:ContractsThe official documentation for OpenZeppelin Libraries and Toolshttps://docs.openzeppelin.comWhat is DeFi?Quick High Level:What is DeFi? | Benefits and Use of Decentralised Finance | ethereum.orgAn overview of DeFi on Ethereumhttps://ethereum.orgIf You Want to Read Everything: https://docs.ethhub.io/built-on-ethereum/open-finance/what-is-open-finance/ERC-20 Tokenshttps://cointelegraph.com/explained/erc-20-tokens-explained Anyone can deploy an ERC 20 token on the Ethereum blockchain. Depending on gas prices it can cost anywhere from $5-$500 to deploy an ERC-20 token contract. Compared to creating a whole new blockchain from scratch, ERC-20s are the easiest way for anyone to create a cryptocurrency thus making it the most commonly used mechanism to launch memecoins. Developer Docs: https://ethereum.org/en/developers/docs/standards/tokens/erc-20/#topERC20The official documentation for OpenZeppelin Libraries and Toolshttps://docs.openzeppelin.comERC-20: Token StandardA standard interface for tokens. The following standard allows for the implementation of a standard API for tokens within smart contracts. This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party.https://eips.ethereum.orgFind Tokens:Token Tracker | EtherscanThe list of ERC-20 Tokens and their Prices, Market Capitalizations and the Number of Holders in the Ethereum Blockchain on Etherscan.https://etherscan.ioStablecoinsA stablecoin is a cryptocurrency with the sole purpose of achieving parity with the US Dollar. Stablecoins help increase liquidity in the DeFi space by negating the need to constantly on and off ramp crypto with fiat and allowing an easy mechanism to exchange other crypto assets with dollar based tokens. There are two broad overarching types of stablecoins. Centralized and Algorithmic stablecoins: Centralized Stablecoins* consist of a corporation that accepts dollar deposits and mint the corresponding amount of stablecoins for the depositor. Centralized stablecoins have the widest adoption by far due to their ease of use, integration with much of the traditional financial system and centralized exchanges. The two most widely used stablecoins are Tether’s USDT and Circle’s USDC with a combined circulating supply of ~117 Billion USD. However, these centralized stablecoins go against the entire ethos of the trustless decentralized nature of blockchain. There is significant uncertainty regarding the true backing of these stablecoins. Tether is notoriously opaque and has never produced an audited report regarding the backing of it’s stablecoins. Read more here. Circle, while nowhere near as suspect still has questions regarding the assets backing its coin and should likewise be treated with caution.* Decentralized Stablecoins* represent the purest form of a dollar pegged cryptocurrency in DeFi. At its core decentralized stablecoins attempt to achieve dollar parity by having users deposit collateral and mint the protocol’s native stablecoin against their deposited assets. *Read this to get a complete understanding of how they work. There are a lot of existing stablecoin protocols. The largest and most widely used is MakerDAO’s protocol which mint’s the native stablecoin DAI. Developer Docs:The Maker Protocol White Paper | Feb 2020This white paper describes the Maker Protocol, a series of smart contracts built on the Ethereum blockchain, enablilng users to generate the Dai stablecoin.https://makerdao.comMakerDAO Technical Docs | Maker Protocol Technical DocsThe Maker Protocol is the platform through which anyone, anywhere can generate the Dai stablecoin against crypto collateral assets. Learn how it works.https://docs.makerdao.comAnother more recent project is the Liquity protocol and their native stablecoin LUSD. They offer greater capital efficiency (you can mint more stablecoins against the same assets) by utilizing a novel liquidation mechanism. Developer Docs:Official Liquity V2 Documentation | Liquity DocsLiquity V2 is a decentralized borrowing and stablecoin protocol that builds on the success of V1. It enhances it in several ways to offer the best borrowing experience, a highly resilient Ethereum-native stablecoin (BOLD), and sustainable on-chain yield. Last updatedhttps://docs.liquity.orgFinally, there are more exotic flavors of algorithmic stablecoins, some which attempt to maintain dollar parity without collateral but rather various algorithmic monetary policies. These are much more dangerous and prone to failure due to the fact that they rely on external market dynamics and “soft” pegs. They often fail catastrophically if certain economic limits are breached. Read more here: [https://cryptobriefing.com/algorithmic-stablecoin-crashes-50-devs-scramble-fix/ https://cointelegraph.com/news/iron-finance-bank-run-stings-investors-a-lesson-for-all-stablecoins\](https://cryptobriefing.com/algorithmic-stablecoin-crashes-50-devs-scramble-fix/ https://cointelegraph.com/news/iron-finance-bank-run-stings-investors-a-lesson-for-all-stablecoins)What is an Automated Market Maker (AMM)?I have 1 bitcoin. I want to swap my bitcoin for 1 bitcoin worth of ethereum. I could deposit my bitcoin on a centralized exchange (covered later) and swap it just like selling 1 Apple stock and buying Tesla stock on a traditional stock exchange. These exchanges follow an order book model. I post an order to sell X Bitcoin for Y Ethereum (or Z USDC, N Dogecoin, etc.) and a counterparty with a matching buy order for X Bitcoin will fill that order. This works great on high speed centralized systems but falls apart very quickly on decentralized networks where transactions can only get executed every ~15 seconds. Imagine trying to implement a system meant to match thousands of orders a second on a decentralized computing network only capable of executing ~150 transactions every 15 seconds and having each transaction cost ~$50-$300. Obviously we need a new system to exchange assets given the computational limits of blockchains. Read this: https://www.coindesk.com/learn/2021/08/20/what-is-an-automated-market-maker/A look at Uniswap V2. The OG AMMUnderstand Everything:Developer Docs:The Uniswap Protocol | UniswapIntroductionhttps://docs.uniswap.orgGitHub - Uniswap/v2-core: 🦄 🦄 Core smart contracts of Uniswap V2🦄 🦄 Core smart contracts of Uniswap V2. Contribute to Uniswap/v2-core development by creating an account on GitHub.https://github.comUniswap V3Uniswap* V3 introduces significantly more complexity to the previous AMM paradigm with the aim of increasing capital efficiency and reducing price impact of large trades.* Understand Everything:Developer Docs:Uniswap Overview | UniswapProtocol, Interface, Labshttps://docs.uniswap.orgGitHub - Uniswap/v3-core: 🦄 🦄 🦄 Core smart contracts of Uniswap v3🦄 🦄 🦄 Core smart contracts of Uniswap v3. Contribute to Uniswap/v3-core development by creating an account on GitHub.https://github.comWhat is Curve?Curve* can be best summarized as Uniswap V2, with more hard math to reduce slippage. Curve is an AMM primarily meant to swap assets of similar value. Curve’s most liquid pool is 3CRV which consists of USDC, USDT and DAI. Curve’s pricing formula allows significantly better pricing for large swaps from one stablecoin to another with reduced price impact compared to using something like Uniswap.* Understand Everything:Developer Docs:Procotol Overview - Curve 1.0.0 documentationThis documentation outlines the technical implementation of the core Curve protocol and related smart contracts. It may be useful for contributors to the Curve codebase, third party integrators, or technically proficient users of the protocol.https://curve.readthedocs.ioGitHub - curvefi/curve-contract: Vyper contracts used in Curve.fi exchange pools.Vyper contracts used in Curve.fi exchange pools. Contribute to curvefi/curve-contract development by creating an account on GitHub.https://github.comDecentralized BankA traditional bank allows you to deposit money and take out loans. Decentralized banks are just like that. I can deposit a variety of cryptocurrencies (Bitcoin, Ethereum, USDC, USDT, etc.) and earn interest on my deposits. The interest is typically algorithmically controlled (i.e., if there are a lot of people borrowing bitcoin, I’ll earn a higher interest rate by depositing bitcoin compared to depositing USDC). Similarly, I can also take out loans against my deposits. If I deposit 10,000 USDC, (depending on the protocol parameters) I can take out a loan of $9000 worth of Ethereum. Aave Intro:What Is Aave? Inside the DeFi Lending Protocol - DecryptDeFi protocol Aave is one of the largest lenders of cryptocurrency and its AAVE token has a larger market cap than rivals Maker or Compound. Here's how it works.https://decrypt.coUnderstand Everything:Developer Docs:Aave Protocol OverviewExplore our developer docs to get started.https://aave.comGitHub - aave/aave-protocol: Aave Protocol Version 1.0 - Decentralized Lending PoolsAave Protocol Version 1.0 - Decentralized Lending Pools - aave/aave-protocolhttps://github.comCompound Compound is similar to AAVE. Read this if you want to see a slightly different implementation but much of the core concepts remain the same. Understand Everything:Developer Docs:Compound IIICompound is an algorithmic, autonomous interest rate protocol built for developers, to unlock a universe of open financial applications.https://docs.compound.financeGitHub - compound-finance/compound-protocol: The Compound On-Chain ProtocolThe Compound On-Chain Protocol. Contribute to compound-finance/compound-protocol development by creating an account on GitHub.https://github.comLiquity/Maker DaiThe lines between Decentralized Lending Banks/Protocols and Decentralized Stablecoins get a little blurry. Both systems fundamentally allow you to deposit assets and take out a loan against these assets. The key difference is decentralized stablecoin protocols have the ability to mint new stablecoins out of thin air while lending protocols require other depositors to deposit assets before you are able to borrow them.OraclesBlockchain is a closed off distributed computer. It has no access to the rest of the World Wide Web. This means you cannot natively make an api call, google something, or download files from a smart contract living on Ethereum. Most importantly, you cannot even generate a cryptographically secure random number within a smart contract. Thus the concept of Oracles were invented. Introductions: https://chain.link/education/blockchain-oracles Developer Docs:Chainlink Documentation | Chainlink DocumentationSimple, clean, and comprehensive documentation for any developer to learn, experiment, and build with the Chainlink platform. Start building now.https://docs.chain.linkForksThe overwhelming majority of blockchain code is open-sourced. To clarify, every piece of smart contract code on the blockchain is publicly accessible. However, the code that exists on the blockchain is effectively a compiled binary and is hard to read and understand. Most projects often post the original precompiled source code on GitHub so users, developers and auditors can verify it’s security and legitimacy. This naturally makes it quite trivial for someone to copy and paste existing protocols and smart contracts and deploy them as their own and that is exactly what happens. These copy and pasted versions of protocols are commonly referred to as Forks. Forks have varying degrees of modifications. They can copy and paste the exact code or they can create significant modifications that add new features or security improvements (and unintentional security flaws too). You might ask why anyone would use a fork rather than an original protocol. Oftentimes, forks employ various strategies to bring users and liquidity to their protocol. The most common strategy is called a Vampire Attack in which the fork offers users better rewards, fee rates, etc. to incentivize them to migrate. SushiSwap was a copy and paste fork of Uniswap V2 that brilliantly executed a vampire attack on Uniswap V2 and is one of the most successful forks to date. Read more here:Sushiswap: A Uniswap Fork and DeFi ProtocolA look at SushiSwap, a fork of Uniswap that incentivized migration from Uniswap to SushiSwap in exchange for SUSHI tokens, and how Uniswap ultimately benefited.https://www.gemini.comWhat is a Vampire Attack? SushiSwap Saga ExplainedSo what is a vampire attack? And how was SushiSwap able to use a vampire attack to attract over $1B of liquidity in less than a week? You'll find answers to these questions in this article.https://finematics.comCentralized ExchangesCentralized Exchanges are venues in which users can trade assets through a corporation’s internalized system. Think of it like a stock exchange but for crypto. That’s literally all it is. Centralized Exchanges are notably different that Decentralized Exchanges for a number of reasons:Almost all Centralized Exchanges now require you to KYC* (Know Your Customer) due to a tightening of regulatory requirements. This typically involves providing sensitive personal information like your full name, address, SSN, passport, etc. Centralized Exchanges may also block users in certain geographical areas due to regulatory requirements. (Binance blocks all US based users for example). Decentralized Exchanges have no such requirements.*Centralized Exchanges custody the assets you wish to trade with*. This means to trade, you have to send your cryptocurrency to the exchange’s own wallet. This has a number of implications, most importantly security. If the Centralized Exchange gets hacked, you have no recourse. This is not like the stock market where you can always undo a transaction that was proven to be malicious/illegal/unauthorized. The blockchain does not care whether or not the transaction was unintentional. If the transaction was signed with the valid private key, it will be executed, accepted and immutably recorded on the blockchain. Hacks happen a lot: *https://www.wired.com/2014/03/bitcoin-exchange/Centralized Exchanges have costs associated with withdrawing or depositing assets.* If you make a trade on Uniswap, immediately after the trade, your wallet will contain the assets you just purchased. In contrast, centralized exchanges have varying wait times if you wish to withdraw your assets after making a trade. In the absolute best case it’ll take ~5min for you to initiate the withdrawal request, have the exchange process the request and send your assets to the indicated wallet. In the worst case (especially if you’re doing a large transfer), exchanges may require additional verification, waiting periods for bank funds to settle (if you paid with fiat), or even delays in the event there is insufficient liquidity and the exchange has to unlock funds stored in cold wallets. Furthermore some exchanges may charge withdrawal and deposit fees in addition to the gas fees you pay for the on chain transfer.*There are a lot of centralized exchanges with varying degrees of regulatory compliance, security and user experience. Some top exchanges by reputation and volume are Coinbase, Kraken, Gemini & Binance.MEVNow that you’ve developed a basic understanding of some of the lego pieces in the blockchain ecosystem it’s time to dive into the world of MEV. MEV, Maximal Extractable Value/Miner Extractable Value is basically any automated interaction you can do on the blockchain that has positive expected value. Importantly, it is not speculating on the prices of assets, YOLOing into a ponzi-esque yield farming protocol or any sort of traditional investment strategy. One kind of accurate way to think about it: MEV is to DeFi what HFT is to the stock market. Introduction:Maximal extractable value (MEV) | ethereum.orgAn introduction to maximal extractable value (MEV)https://ethereum.orghttps://research.paradigm.xyz/MEV The OG Flashboys 2.0 (Hard. Required if you want to build something. Seriously. Read it first):Very Very Fun Reads (Not hard. Just insightful):Ethereum is a Dark ForestIt's no secret that the Ethereum blockchain is a highly adversarial environment. If a smart contract can be exploited for profit, it eventually will be. But this unforgiving environment pales in comparison to the mempool. If the chain itself is a battleground, the mempool is something worse: a dark forest.https://www.paradigm.xyzEscaping the Dark ForestOn September 15, 2020, a small group of people worked through the night to rescue over 9.6MM USD from a vulnerable smart contract. This is our story.https://samczsun.comRekt - Return to the dark forestDeFi / Crypto - A new anonymous author speaks out. Join us, as we venture deep into the Dark Forest to uncover a mafia business model being operated by bloXrouteLabs. This protection racket turns Ethereum into a pay-to-play game, which only the frontrunners can win.https://rekt.newsMEV Strats 101MEV strategies basically consist of a set of on-chain interactions with the goal of ending up with more money than you started with by the end of the execution sequence.SandwichingSandwiches are the most notorious form of MEV. They are the blockchain equivalent to the frontrunning strategies employed by HFT firms laid out in Michael Lewis’s Flash Boys. At its core a sandwich exploits the existence of pending transactions waiting to be confirmed on the blockchain. If you see a pending order to buy 100,000 USDC worth of Ethereum through Uniswap, the logical conclusion is that the price of Ethereum will go up after that transaction has been executed. You want to buy Ethereum immediately before the targeted transaction has been executed and then immediately sell that same Ethereum right after the target transaction executed. In practice, you can use the pricing formulas detailed in the Uniswap whitepapers to calculate the *exact* price impact that any order will have on a trading pair. This is a crucial advantage that sandwich attacks have over tradfi frontrunning where slippage is a probabilistic calculation. The deterministic nature of each individual trade on decentralized exchanges allows you to derive and calculate optimal trade sizes to frontrun a purchase with, allowing you to extract the globally maximal profit from any sandwich attack. Learn more here:DEFI Sandwich Attack ExplainDEFI Sandwich Attack Explain In this article, I am going to summarise what is sandwich attacks with an example and mathematical view so you can understand crypto market manipulation. Sandwich attacks ...https://medium.comA quick ethics tangent:* Sandwich attacks are typically excoriated within the DeFi space and viewed as negative externality. There are two ways to look at Sandwich Attacks. The Bad Way and the Good Way.* The Bad Way* views sandwich attacks as a purely exploitive strategy that preys upon uninformed retail users who don’t fully understand the underlying network dynamics of blockchain and the implications of the slippage parameters they set when making a trade. The most brutal sandwich attacks often occur when a user YOLOs into a newly launched shitcoin and through a desire to be one of the first buyers of the coin set slippage to absurdly high values (sometimes as high as 99%) inevitably resulting in them receiving exactly their minimum specified output amount — this amount is an order of magnitude lower than they otherwise would have received in the absence of a sandwich attack.* The Good Way* views the entirety of this set of interactions through the lens of economic efficiency. When a user submits a swap, they effectively declare their maximum willingness to pay through the parameter minOutput/maxInput. If their order fills at a more favorable price than the declared WTP, it implies the existence of a consumer surplus and consequently the absence of a Nash Equilibrium. A third party, the sandwich bot operator, moves the economic system towards the Nash Equilibrium such that the market meets the consumer’s maximum WTP while also extracting value for the operator. In doing so, the sandwich bot has generated more global utility and reached the Nash Equilibrium where no other action would produce additional utility given the current state of the system and the declared economic preferences of all agents involved.* Both ways are reasonable positions to view sandwich attacks and in truth the reality likely lies somewhere along the spectrum of the Good Way and the Bad Way. A couple parting thoughts to ponder:Sandwich attacks will always exist. If you don’t run a bot, someone else willThis practice is widespread in the equities market and an accepted dynamicFrontrunning as referenced in Flashboys still occurs to this dayA novel trade mechanism called Payment for Order Flow (PFOF) has enabled retail brokerages to offer no-fee trades by routing orders through market makers like Citadel. These market makers pay brokerages for retail order flow since they don’t face the same degree of adverse selection they otherwise would when trading against informed counterparties on the public stock exchangeThe effects of HFT practices in equities are far more opaque due to the existence of Dark Pools, the centralized nature of equity markets and complexity of equity market architecturesArbitrageArbitrage involves buying an asset at a discount on one venue and simultaneously selling it at a different venue for a higher price. Arbitrage is a mechanism to make markets efficient and reduces price discrepancies of assets across different venues. Read more here:Crypto Arbitrage Trading: How to Make Low-Risk GainsNot all crypto trading strategies have to be high-risk, high reward. For traders looking for a near risk-free option, you might want to explore arbitrage trading.https://www.coindesk.comThere are many many different flavors of arbitrage. Some are absolutely considered to be MEV while others incorporate more traditional financial strategies: Atomic Arbitrage If you paid attention to the smart contracts section you should know that smart contracts allow you to package a series of on chain interactions, sequentially execute them, and at the end of execution, check for a set of conditions. If the conditions are not met, the smart contract can force the execution to fail effectively undoing all the on chain interactions that just occurred. The implications of this mechanism are enormous. In traditional forex arbitrage, when you execute a multi hop arbitrage, you run the risk that the market moves against your position while you are halfway through your arbitrage forcing you to sell at a loss to return to your original denominated currency. With the existence of atomic execution, not only will every leg of your hop be guaranteed to execute one after another with no race conditions (Ethereum is a singular global state machine that can only process transactions sequentially), but your smart contract code can record your initial starting balance, and at the end of execution can assert startingBalance