⛏️ MEV + πŸ€– Flashbots

“We took the first deep look at MEV and released our findings through MEV-Explore, a public dashboard and live MEV transactions explorer. After scraping the Ethereum blockchain starting from the first block of 2020, we’ve classified more than 1.3M MEV transactions and found a total of at least $708M worth of Extracted MEV since Jan 1st 2020, as well as $12.6M wasted gas fees on failed MEV transactions, equivalent to 6,234 Ethereum blocks of wasted blockspace.”

By @cryptoleek.eth

⛏️ How does Miner work?

To understand MEV, we need to understand how does miner pick up txns.

mev

⛏️ What's MEV?

Miner Extractable Value (MEV), where blockchain miners are able to extract profits at the expense of users by arbitrarily reordering, including, or excluding transactions within a block. Miners can determine the order of when transactions are processed on the blockchain and exploit that power to their advantage.

The Flash Boys 2.0 paper coined the term "miner extractable value" (MEV)

⛏️ Common MEV Actions

  • Front Running
  • Sandwich Bot
  • Back Running

⛏️ Front Running

Front Running is a way to manipulate txns sequences by peeping the mempool. And the front runners can initiate a same transaction with higher gas fee to benefit themselves.

⛏️ Front Running II - Typical Examples

  • IDO Sniping Bot
  • Liquidity Bot
  • Liquidation Bot
  • Harvest Bot

⛏️ Front Running III - Further Reading

An epic story to read and understand more about Front Running in general. Ethereum is a Dark Forest.

⛏️ Sandwich Bot

Sandwich Bot Attack is a technique, which usually follows a similar course:

  • 1. Detect the victim’s transaction.
  • 2. Front-Run the victim’s transaction.
  • 3. Victim transacts and suffers higher slippage.
  • 4. The attacker then back-runs the victim.

⛏️ Sandwich Bot II - A simple Diagram

⛏️ Sandwich Bot III - Further Reading

Bad Sandwich: DeFi Trader 'Poisons' Front-Running Miners for $250K Profit. Wrecking sandwich traders for fun and profit.

⛏️ Back Running

Back Running is similar to Front Running, but vice versa. A good article to read is The fastest draw on the Blockchain: Ethereum Backrunning

⛏️ In Action

Now start to build MEV and Get πŸ€‘πŸ€‘πŸ€‘

1st, set up your own Node by using Geth

2nd, peek the mempool ...

❌❌❌, I am kidding. It's kinda bad.

Why? πŸ€”

⛏️ It's bad for Ethereum

  • An adversarial env and hard to beat others. ☣️☣️☣️
  • Gas Bidding War βš”οΈβš”οΈβš”οΈ
  • Polluted the ethereum states with a lot of garbage / failed txns 🚨🚨🚨
  • And it's killing ethereum. ☠️☠️☠️

πŸ€– FlashBots

Official: Flashbots is a research and development organization working on mitigating the negative externalities of current MEV extraction techniques and avoiding the existential risks MEV could cause to state-rich blockchains like Ethereum.

Plain: We can't fix MEV, then we work with it. To enable a permisionless, transparent and fair ecosystem for MEV extraction.

πŸ€– Official Offerings

  • Flashbots Auction
  • Flashbots Data
  • Flashbots Research

πŸ€– Flashbots Auction

  • A permissionless, transparent, and fair ecosystem for efficient MEV extraction and frontrunning protection
  • A private communication channel between users and miners for communicating preferred transaction order.
  • A mev-geth, a patch on top of the go-ethereum client, along with the mev-relay, a transaction bundle relayer

πŸ€– MEV-Geth Miner

A miner may profit from it by accepting MEV bundles either via direct block.coinbase payments, or with extra transactions that pay the block's coinbase

Guarantee PGA Dark-txPool MEV-Geth
Permissionless βœ… ❌ βœ…
Efficient ❌ ❌ βœ…
Pre-trade privacy ❌ βœ… βœ…
Failed trade privacy ❌ ❌ βœ…
Complete privacy ❌ ❌ ❌
Finality ❌ ❌ ❌

πŸ€– Searcher (More Relevant)

Searcher is a term describing Etherem bot operators / users looking for fast, risk controlled or frontrunning protected bundled-txn execution via Flashbots MEV-Relay with out disclosing txns info on mempool by sending enough GAS or brbing miners to send $ETH to coinbase via smart contract::

block.coinbase.transfer(_ethAmountToCoinbase);

πŸ€– Searcher II Use cases

  • Bot operators looking for fast, and risk free access to blockspace (eg. arbitrage and liquidation bots)
  • Ethereum users looking for frontrunning protection on their transactions (eg. AMM traders)
  • Ethereum Dapps with advanced use cases like account abstraction or gasless transactions (eg. tornado.cash, mistX and cowswap)

πŸ€– Flashbots Data

  • MEV-Explore v0 a public dashboard and live transaction explorer for MEV transactions
  • Flashbots dashboard a public dashboard of the activity taking place on Flashbots

πŸ€– Flashbots MEV-Explore v0

πŸ€– Flashbots dashboard

πŸ€– Flashbots Research

A research hub for MEV, tackling and uncovering questions relevant to the short, medium and long-term future of the ecosystem.

πŸ€– A real horror story

Blockchain is a very adversarial env. There are lots of phishing sites and impersonators try to steal your private keys. One of my community member got phished and exposed his private key. All Ethers / ERC20 Tokens have been transfered out immediately. However, he still has 2000 sushi vested in the farming pool. How can we save him from desperate?

πŸ€– A taste of flashbot

A simple Flashbots "searcher" for submitting a transaction from an executor account, but paying for the transaction from a sponsor account. This is accomplished by submitting a Flashbots transaction bundle, with the first "sponsor" transaction paying the "executor" wallet in ETH, followed by a series of executor transactions that spend this newly received ETH on gas fees.

πŸ€– Setup

We have 3 seperate accounts. One account is hacked account, another is sponsor account (who is gonna provide gas), last is the account the erc20 token will be transfered in.

πŸ€– Setup II

Left (Hacked Account) with no $ETH, Middle (Sponsor Account) and Right is to recieve the 5000 TTT from Hacked Account

hacked sponsor recipient

πŸ€– Coding I

Connect to Testnet, prepare for wallets and setup TransferERC20 action

          
          const walletRelay = new Wallet(FLASHBOTS_RELAY_SIGNING_KEY)

          // ======= UNCOMMENT FOR GOERLI ==========
          const provider = new providers.InfuraProvider(5, process.env.INFURA_API_KEY || '');
          const flashbotsProvider = await FlashbotsBundleProvider.create(provider, walletRelay,
          'https://relay-goerli.epheph.com/');
          // ======= UNCOMMENT FOR GOERLI ==========

          const walletExecutor = new Wallet(PRIVATE_KEY_EXECUTOR);
          const walletSponsor = new Wallet(PRIVATE_KEY_SPONSOR);

          const block = await provider.getBlock("latest")

          // ======= UNCOMMENT FOR ERC20 TRANSFER ==========
          const tokenAddress = "0xA766A59AA95Be7B06726650233cAEa39122204bd";
          const engine: Base = new TransferERC20(provider, walletExecutor.address, RECIPIENT, tokenAddress);
          
        

πŸ€– Coding II

Build the txn bundle, the first txn is to sponsor the second txn. Second tx is to transfer Erc20

          
          const bundleTransactions: Array = [{
            transaction: {
              to: walletExecutor.address,
              gasPrice: gasPrice,
              value: gasEstimateTotal.mul(gasPrice),
              gasLimit: 121000,
            },
            signer: walletSponsor
          },
          ...sponsoredTransactions.map((transaction, txNumber) => {
            return {
              transaction: {
                ...transaction,
                gasPrice: gasPrice,
                gasLimit: gasEstimates[txNumber],
              },
              signer: walletExecutor,
            }
          })]
          const signedBundle = await flashbotsProvider.signBundle(bundleTransactions)
          
        

πŸ€– Coding III

Simulation and send bundle!

          
          provider.on('block', async (blockNumber) => {
            const simulatedGasPrice = await checkSimulation(flashbotsProvider, signedBundle);
            const targetBlockNumber = blockNumber + BLOCKS_IN_FUTURE;
            const bundleResponse = await flashbotsProvider.sendBundle(bundleTransactions, targetBlockNumber);
            if ('error' in bundleResponse) {
              throw new Error(bundleResponse.error.message)
            }
            const bundleResolution = await bundleResponse.wait()
            if (bundleResolution === FlashbotsBundleResolution.BundleIncluded) {
              console.log(`Congrats, included in ${targetBlockNumber}`)
              process.exit(0)
            } else if (bundleResolution === FlashbotsBundleResolution.BlockPassedWithoutInclusion) {
              console.log(`Not included in ${targetBlockNumber}`)
            } else if (bundleResolution === FlashbotsBundleResolution.AccountNonceTooHigh) {
              console.log("Nonce too high, bailing")
              process.exit(1)
            }
          })
          
        

πŸ€– Live Demo

Hopefully this can help my friend to save his lost assets ... πŸ™πŸ™πŸ™

πŸ€– Further Reading

Chainlink MEV Solution

Chainlink is developing Fair Sequencing Services (FSS)β€”an MEV solution that uses a decentralized oracle network to fairly order transactions sent to an on-chain smart contract. By separating the ability to order transactions from the ability to produce blocks, malicious value extraction such as frontrunning can be prevented through predefined ordering policies.

More Reading on Chainlink FSS

FSS is still under development, shall give a in-depth look once it's into mature state.

MEV Introduction

Flashbots Introduction

Flashbots Gasless Txn (Code Demo)

πŸ‘πŸ» Q & A

Thanks!

Please ❀️, ⏩ and πŸ””

Chainlink