Перейти к содержимому

Mev в ethereum что это

  • автор:

Прикладной MEV или как наводить свой порядок в блоке Еthereum

На хабре уже заходили в тёмный лес MEVа, но почти не затрагивали его прикладную сторону. В этой статье рассмотрим основную инфраструктуру MEVа на эфире и разберём несколько примеров, как это работает сегодня.

Введение

MEV (maximal extractable value) — это процесс извлечения профита из сети блокчейна путем добавления, удаления или изменения порядка транзакций, включенных в блок. Данная концепция зародилась в комьюнити эфира довольно давно (конечно, если исчислять в криптогодах), но начал MEV выходить на новый уровень объемов с ростом DeFi инфраструктуры, которая открыла больше возможностей для серчеров.

Простыми словами принцип работы MEVа следующий: «Эй, майнер, поставь мою транзакцию рядом с той, чтобы я заработал 1 ETH, а я тебе за это дам половину от этого». Очевидно, что это win-win ситуация, как для того, кто нашел эту транзакцию (серчеры), так и для тех, кто может изменять порядок транзакции при создании блока.

Важным термином в работе с MEVом является мемпул. В терминологии блокчейна, мемпул — это пул ожидания для транзакций, которые ещё не были добавлены в блок и все еще не подтверждены, то есть находятся в состоянии pending. Само собой, любой желающий может увидеть все транзакции, которые находятся в этом ожидании и понять, как они могут повлиять на те или иные состояния контрактов.

Что ищут сегодня в блокчейне?

На момент написания статьи самыми популярными направлениями использования механик MEVа сейчас являются:

DEX арбитраж и сендвичинг. Мемпул предоставляет уникальную возможность для трейдеров — предвидеть цены на биржах. Большинство децентрализованных бирж работают по алгоритмах маркет мейкинга, что позволяет, зная текущее состояние пулов (контрактов бирж) и входящие сделки из мемпула узнать состояние цены после каждой предстоящей сделки в блоке. Здесь для серчеров открывается возможность, как для обычного арбитража между разными биржами внутри одного блока, так и для сендвичинга — покупки и продажи вокруг одной сделки или наоборот.

Например, трейдер увидел в мемпуле большую транзакцию на покупку токена AOWL, после чего он отправил майнеру свои 2 транзакции: на свою покупку этого токена прямо перед большой сделкой и моментальной продажей после этой сделки.

Ликвидации. Протоколы кредитования, такие как Maker, Compound и Aave, требуют, чтобы пользователи вносили залог (например, ETH). Этот депонированный залог затем используется для предоставления кредита другим пользователям. Как только данный залог имеет потенциальный риск того, что он будет не обеспечивать займ (риск параметры этого определяются DAO сообществом заранее), то любой пользователь сети может ликвидировать долг, забрав себе обеспечение. При этом, например, долг может составлять $80k, а его обеспечение $100k, тем самым ликвидатор получает моментальный профит.

NFT MEV. Имея доступ к общей информации входящих транзакций, можно так же обнаруживать завершение аукционов NFT или их дропы, что открывает возможности для извлечения из этого профита. Например, если есть популярный дроп NFT, и серчер хочет определенный NFT или набор NFT, он может поставить свою транзакцию таким образом, чтобы он был первым в очереди на покупку NFT, или он может купить весь набор NFT за один раз.

Инфраструктура

Большую роль в развитии MEV ифраструктуры сыграли flashbots community. Они предложили инфраструктуру mev-boost — по сути улучшенный клиент geth (то есть клиент узла ноды Ethereum). В данной статье будем рассматривать именно эту инфраструктуру, так как на данный момент все билдеры в сети эфира используют именно её. Однако преобладание Flashbots Builder сильно упала в производстве блоков, хотя на пике они собирали почти 80% всех блоков эфира.

Вкратце пройдёмся по процессу «майнинга» в Ethereum 2.0 после мержа. Теперь за создание блоков отвечает 3 агента: билдер, релэй (ретранслятор) и валидатор.

Билдер блоков получает транзакции от серчеров и пользователей, которые, в дополнение к плате за газ, выражают свою предпочтительную позицию в блоке, делая ставку с закрытой ценой. Задача билдера состоит в том, чтобы построить наиболее прибыльный блок, используя различные стратегии.

Ретранслятор — это агент, отвечающий за проверку блоков перед их передачей валидаторам. Реле защищает валидаторов от спама, проверяя блоки билдера на достоверность и оценивая значение каждого блока, связанное с MEV.

Валидатор в архитектуре mev-boost — это участник Beacon Chain, выбранный для предложения блока для определенного слота. Валидатор связывается с ретранслятором, чтобы получить наиболее прибыльный заголовок блока, который он подтверждает, подписывая его своим открытым ключом через escrow.

Mev-boost chart. Источник: https://ethresear.ch/t/mev-boost-merge-ready-flashbots-architecture/11177

Mev-boost chart. Источник: https://ethresear.ch/t/mev-boost-merge-ready-flashbots-architecture/11177

Таким образом, пользователи сети могут напрямую влиять на сбор блоков через mev-boost инфраструктуру. Для упорядочивания транзакций используются связки или бандлы, которые представляют из себя упорядоченный набор транзакций, который серчер отправляет билдеру через API.

Для примера посмотрим данную ликвидационную транзакцию, которая была исполнена через билдера flashbots. Посмотрим её позицию в блоке и увидим, что она стоит второй в блоке сразу после публичной транзакции Transmit, которая обновляет ончейн цену актива. В данном примере транзакции 0xcc101. и 0xba0c4. являются атомарной связкой.

Пример использования

Mev-boost клиент имеет универсальные REST API методы, который можно найти, например, в документации flashbots. Рассмотрим пример отправки бандлы через go:

«Темный лес» Ethereum: что такое MEV

Cyber Academy

Во время того, как массовое внедрение DeFi набирает обороты и количество транзакций растет, сообщество Ethereum обсуждает лучший способ решить проблему извлекаемой ценности майнеров (Miner Extractable Value или MEV).

Почему это проблема? Рынок DeFi увеличивается экспоненциально, начиная с 2021 года сфера выросла на 246%. Но с ростом ценности увеличилось и желание эксплуатации системы и попыток получить прибыль при помощи различных уловок. MEV стал такой уловкой для получения прибыли майнерами. С января 2020 года майнеры добыли MEV на $730.9 миллионов. По сути, майнеры собирают невидимый налог с пользователей во время каждой транзакции. Но это не только про высокие комиссии, но также невидимые войны майнеров и торговых ботов за бОльшую прибыль в мемпулах. Одна операция может принести миллионы долларов. В настоящий момент около 60% блоков содержат следы MEV-манипуляций.

Разбираемся, какие риски влечет за собой концепция MEV для представителей мира децентрализованных финансов, что это вообще такое и как работает. Приятного чтения! ✨

Что такое MEV

Miner Extractable Value или MEV — индикатор прибыли, которую может получить майнер или нода-валидатор за способность добавлять и исключать транзакции или изменять их порядок в блоках.

Мы знаем, что блокчейн Ethereum — неизменяем, и майнеры постоянно генерируют последовательно связанные блоки с транзакциями. Но это не значит, что транзакции внутри блока находятся в фиксированном положении. Майнеры могут менять их порядок. Они обычно выстраивают приоритетность валидации транзакций в зависимости от цены газа, чтобы обеспечить более высокие комиссии. Этот дополнительный доход от изменения положения транзакций в блоке и называется Miner Extractable Value.

Как появился MEV

Термин MEV появился в статье Flash Boys 2.0, написанной исследователями из Корнеллского технологического института, для описания таких эксплойтов. Концепт был предложен Филом Дайаном и популяризирован его коллегами Дэном Робинсоном, Георгиосом Константопулосом и samczsun в статьях «Ethereum-темный лес» и «Побег из темного леса». MEV стал базовой концепцией в криптоэкономике.

В посте Дэн Робинсон и Георгиос Константополус описали попытку украсть активы на $12 000. Бот был настолько продвинутым, что смог отследить ценностную транзакцию в пуле Ethereum и заклеймить ценность с помощью фронтраннинга.

«Темный лес»: как именно это работает

Извлечение MEV, выполняемое майнерами является обычным явлением из-за конструкции мемпула виртуальной машины Ethereum. Перед включением в блокчейн, все транзакции сети Ethereum попадают в публичный мемпул для ожидания подтверждения от валидаторов. Но что именно происходит с транзакциями — скрыто от пользователей. Это явление получило название «темный лес».

Каждая транзакция в Ethereum, отправляемая в цепочку, отслеживается, чтобы проверить, есть ли возможность заработать что-то на ней. Обычно в мемпуле орудуют MEV-боты, которые отслеживают шансы получения прибыли от различных операций, вроде ликвидации займов или арбитражных транзакций. Майнеры могут захватывать и цензурировать транзакции, чтобы копировать их и получать прибыль. Иногда вмешиваются другие боты и начинается аукцион газа за приоритет — боты предлагают цены за комиссии все выше, чтобы перехватить транзакцию. Это приводит к «газовым войнам».

Стратегии MEV

Майнеры используют свое положение валидаторов с выгодой и используют различные сценарии получения дополнительной прибыли. Например, майнер может увидеть, что кто-то купил большое количество ETH, а значит, цена актива вырастет после завершения транзакции. Он может выгодно купить активы перед этой транзакцией, чтобы потом продать по более высокой цене. Такой способ называется фронтраннинг. При этом, бэкраннинг — это когда майнеры рассчитывают цену газа так, чтобы одна транзакция специально размещалась сразу после той, которую атакуют. Боты используют этот метод, чтобы опередить атакующего и конкурентов. Комбинация двух методов называется сэндвичем. Атака time-bandit — агрессивная атака, в которой майнеры добиваются валидации более длинной цепи.

Боты-арбитражники используют разницу в цене на активы на разных децентрализованных биржах. Разница в цене появляется из-за краткосрочных движений рынка или низкой ликвидности. Они, по классике, покупают, где дешевле, и продают подороже в другом месте.

Появились также специализированные боты. Например, майнеры пула Ethermine запустили бота, который минимизировал потери из-за активации EIP-1559 в хардфорке London.

В чем заключаются основные проблемы

«Темный лес» MEV порождает две взаимосвязанные проблемы. Майнеры пребывают в более выгодном положении, чем другие участники рынка, потому что они первые обнаруживают блоки. Пользователи DeFi вынуждены постоянно страдать от различных стратегий MEV, которые в конечном итоге приводят к сбою транзакций пользователей, даже если они заплатили за их выполнение. Сделки исполняются по неоптимальному обменному курсу, что увеличивает издержки при использовании бирж, накладывая на пользователей «невидимый налог».

По мере развития DeFi и увеличения маркеткапа, увеличивается количество арбитражных стратегий, что ведет к ужесточению войны ставок и битве торговых-ботов, растет и конкуренция майнеров. В целом, конкуренция хороша для традиционных рынков, но в децентрализованной среде эгоизм одних участников ведет к неадекватно высоким транзакциям для всех участников сети.

Возможные решения проблем

Есть несколько способов, с помощью которых децентрализованные приложения или пользователи могут бороться с MEV. Например, с помощью пакетной стратегии ставок. Это когда книга заказов биржи обрабатывает заказы в течение определенного временного диапазона с целью одновременного выполнения всех сделок в пакете. Это служит механизмом определения цены для правильной оценки пар токенов с одинаковой клиринговой ценой для каждого блока. На традиционных рынках пакетные аукционы используются во время открытия рынка для обработки всех заказов, размещенных в нерыночные часы. В DeFi пакетные аукционы полезны для одновременного выполнения множества транзакций в одном и том же блоке.

Еще одним решением может стать активное использование решений второго уровня. L2 в Ethereum может разгрузить основной блокчейн и предотвратить MEV-манипуляции. В основной блокчейн будет записан лишь минимальный объем информации, необходимый для выявления мошенничества. В результате участники сети получают высокую скорость и пропускную способность, сохраняя безопасность сети базового уровня. Dapp могут использовать в своих смарт-контрактах больше шаблонов, устойчивых к MEV. Временное шифрование, SGX или пороговое шифрование могут использоваться для сокрытия транзакций от злоумышленников.

Как проекты пытаются решить проблему

В настоящий момент в сообществе DeFi ведутся споры, как лучше решить проблему MEV. Одна из самых активных команд, работающих над этим, — ребята из проекта Flashbots. Это научно-исследовательская команда, которая пытается снизить риски для пользователей, связанные с Miner Extractable Value. Они придумали бота Flashbot Alpha, который создает закрытый аукцион для приоритезации транзакций.

Есть несколько приватных виртуальных мемпулов. Например, Hiding Book. Протокол KeeperDAO извлекает MEV из транзакций при помощи арбитража или ликвидаций. Пользователи не платят за газ и защищены от проскальзываний и сэндвич-атак.

Есть проекты, которые позиционируют себя как неуязвимые перед фронраннингом и другими MEV-стратегиями. Например, Secret Swap использует зашифрованные «секретные контракты». BackRunMe, TaiChi Network, ArcherSwap — протоколы для совершения конфиденциальных транзакций, устойчивых к фронтраннингу и «сэндвич-атакам». Команда Chainlink создала решение Fair Sequencing Services, использующее децентрализованных оракулов для справедливого упорядочения транзакций.

Полезные ссылки:

Cyber Academy — образовательная платформа для блокчейн-разработчиков. Присоединяйтесь к нам

Поддержите нас на Gitcoin ✨

Что такое MEV в Ethereum и как он изменится после перехода на PoS

Как известно, записанные в блокчейн блоки являются неизменной информацией и не могут быть переписаны. Однако майнеры или валидаторы могут включать, исключать и менять порядок транзакции в будущем блоке на свое усмотрение до того, как тот будут подтвержден.

Каждая неподтвержденная транзакция сначала попадает в общедоступный мемпул. Далее майнеры выбирают, какие именно транзакции они добавят в блок из мемпула. Так майнеры формируют для себя наиболее выгодную комбинацию пользовательских транзакций.

Это приводит к злоупотреблениям. Майнеры (а после перехода Ethereum на PoS — валидаторы) отдают предпочтение транзакциям наибольшего размера, выстраивая приоритет от большего к меньшему, и добавляют их в будущий блок, который будет записан в блокчейн.

Эта особенность привела к созданию механизма извлечения выгоды посредством подстановки транзакций в нужном порядке. Такая практика получила название максимально извлекаемой стоимости, или MEV.

Стратегия MEV заключается в поиске валидаторами спекулятивных операций на основе имеющихся неподтвержденных транзакций и повышении фактических комиссий за их исполнение.

Разберем пример, когда пользователь Ethereum решил обменять 10 000 USDC на ETH по цене $2 000 за монету на DEX в пуле ликвидности USDC/ETH. Вот что происходит после размещения заявки на обмен:

  1. В мемпуле работают специальные боты, которые отслеживают неподтвержденные транзакции и собирают различные данные из DeFi-приложений, включая цену и объемы ликвидности.
  2. Заметив намерение пользователя о покупке ETH, боты инициируют операцию, которая повысит цену прямо перед исполнением транзакции пользователя. Например, бот может добавить в пул ликвидности USDC/ETH больше USDC,чтобы повысить цену ETH.
  3. Таким образом, ожидаемая цена в $2000 за монету ETH, на которую рассчитывал пользователь, изменится на условные $2500 за монету ETH. Транзакция будет выполнена: вместо 5 ETH пользователь получит всего 4 ETH. Прибыль инициатора этой MEV-операции составит 1 ETH за вычетом расходов на комиссии.

Поскольку MEV приводит к увеличению комиссий для пользователя, его также называют «невидимым налогом», который характерен не только для Ethereum.

Когда появился «невидимый налог» MEV

Впервые проблему «подмены» пользовательских транзакций, называемой сегодня MEV, поднял в Reddit алгоритмический трейдер и аналитик Pmcgoohan в 2014 году, еще до запуска мейннета Ethereum. Он предположил, что майнеры, не нарушая никаких правил консенсуса, могут манипулировать транзакциями пользователей для своих корыстных целей.

Термин MEV был выдвинут только в 2019 году в работе «Flash Boys 2.0», которая стала первой общедоступной публикацией, исследовавшей серьезность проблемы, описанной Pmcgoohan.

О масштабах и серьезности проблемы заговорили только в 2020 году в таких статьях как «Ethereum is a dark forest» и «Escaping the Dark Forest», написанных Дэном Робинсоном, Георгиосом Константопулосом и криптоинвестором Samczsun. Эти публикации были направлены на информирование пользователей Ethereum о «невидимом налоге», собираемом с пользователей.

Разновидности MEV

Развитие сектора децентрализованных финансов (DeFi) и отдельных элементов экосистемы Ethereum, в частности ценовых оракулов, ликвидных токенов и кроссчейн-мостов, привело к появлению различных MEV-стратегий.

Фронтраннинг

Самая распространенная стратегия, где MEV-транзакцию пытаются поставить перед оригинальной транзакцией. Специальные боты могут отслеживать потенциально выгодные операции, просто копируя транзакции пользователей, действуя на опережение.

Бэкраннинг

Выставление транзакции вследствие какого-либо события. Например, сразу после появления нового пула на Uniswap эксплуататор может выкупить значительную часть токенов и занять первое место в очереди, опустошив пул. После этого он позволяет остальным участникам осуществить продажу и продает сам по более выгодной цене.

Сэндвич-атака

Комбинация двух предыдущих схем. Если бот находит в мемпуле крупный ордер на покупку, то выставляет перед ним свою заявку, чтобы приобрести токены по более низкой цене с помощью фронтраннинга. Исполняется крупный ордер, двигая цену вверх. Затем, применяя бэкраннинг, монеты продают с прибылью раньше остальных пользователей.

Ликвидация

Стратегия, направленная на получение валидатором прибыли за счет выкупа залоговой позиции в протоколе кредитования сразу после ее ликвидации. Пользователь видит, что в следующем блоке позиция может быть ликвидирована, и отправляет транзакцию для выкупа залога.

«Атака дяди-бандита» (Uncle bandit attack)

Сложный вид MEV-стратегии, основанный на спекулятивной цепочке транзакций, обнаруженных в конкурирующем блоке. Бывают моменты, когда майнеры находят два блока одновременно. В этот момент майнеры могут использовать данные из «соседнего» блока в своих интересах.

«Атака временнòго бандита» (Time bandit attack)

Предполагает процесс реорганизации предыдущих блоков, где майнеры специально предлагают конкурирующие блоки, содержащие другие транзакции. Приводит к исчезновению транзакций и включения их в совершенно другой блок.

Способы защиты от MEV и флеш-боты (Flashbots)

MEV характерен не только для Ethereum. По мере развития сектора DeFi-приложений и ужесточения конкуренции боты переместились в EVM-совместимые блокчейны, такие как Polygon и BNB Chain. Однако именно Ethereum стала наиболее продвинутой сетью с точки зрения борьбы с этой проблемой.

Согласно данным за 2021 год, Ethereum-майнеры заработали $730 млн в виде наград за извлечение MEV — 4,3% от общегодовой выручки. Это указывает на рост «нечестных рынков» и ведет к ухудшению пользовательского опыта за счет роста комиссий и отсутствия предсказуемости в процессе исполнения транзакций.

В качестве решения в 2020 году появилась централизованная система Flashbots, финансируемая венчурной компаний Paradigm. Она не стремится ликвидировать проблему, а скорее взять ее под контроль путем создания открытого рынка через разрабку публичного аукциона ETH-транзакций.

Решение быстро набрало популярность. По информации исследовательского подразделения криптобиржи BitMEX, в мае 2022 года более 90% майнеров в сети Ethereum были подключены к серверу Flashbots. Исследователи отметили, что 63% вознаграждений за MEV-транзакции получили операторы, а оставшиеся 37% отошли майнерам.

Что изменится после перехода Ethereum на PoS

Эксперты полагают, что смена алгоритма консенсуса в Ethereum не изменит основные принципы создания блоков в сети. Как и в случае с майнингом, у валидаторов остается способность «компоновать» блоки из транзакций на свое усмотрение.

В то же время, по оценкам компании Blocknative, в Ethereum появится много непрофессиональных операторов нод. Это может привести к возникновению в Ethereum отдельной категории участников из числа валидаторов под названием «Строители блоков» (Block Builders). Они будут предоставлять услугу наиболее выгодной группировки блоков, способствуя максимизации прибыли и оптимизации сети.

В результате в Ethereum появятся разные типы блоков в зависимости от потребностей валидаторов:

  • Блоки с максимальным количеством MEV-транзакций;
  • Блоки с MEV только для благотворительных целей;
  • Блоки с определенными ценами на газ;
  • Блоки, упорядоченные по времени;
  • Блоки, выставленные на аукцион;
  • Блоки с цензурой;
  • Блоки без цензуры.

Также ожидается, что из-за специфики работы «эпохи» (процедуры отбора валидаторов и создания нового блока) операторы MEV будут заранее знать, какие валидаторы предложат следующий блок. Это может привести к созданию совершенно новых, долгосрочных MEV-стратегий.

Разработчик Элиас Симос, изучивший первые 24 500 блоков после The Merge, пришел к выводу, что 18% из них были добыты с использованием модифицированного механизма под названием MEV-Boost. В итоге PoS-валидаторы смогли получить на 122% больше прибыли, а сформированные ими блоки содержали на 41,4% больше транзакций.

Несмотря на результаты использования MEV валидаторами, все еще затруднительно оценить экономические и другие возможные последствия использования MEV-стратегий относительно обычных пользователей.

Maximal extractable value (MEV)

Maximal extractable value (MEV) refers to the maximum value that can be extracted from block production in excess of the standard block reward and gas fees by including, excluding, and changing the order of transactions in a block.

Miner extractable value

Maximal extractable value was first applied in the context of proof-of-work, and initially referred to as "miner extractable value". This is because in proof-of-work, miners control transaction inclusion, exclusion, and ordering. However, since the transition to proof-of-stake via The Merge validators have been responsible for these roles, and mining is no longer part of the Ethereum protocol. The value extraction methods still exist, though, so the term "Maximal extractable value" is now used instead.

Make sure you're familiar with transactions, blocks, proof-of-stake and gas. Familiarity with dapps and DeFi is helpful as well.

In theory MEV accrues entirely to validators because they are the only party that can guarantee the execution of a profitable MEV opportunity. In practice, however, a large portion of MEV is extracted by independent network participants referred to as "searchers." Searchers run complex algorithms on blockchain data to detect profitable MEV opportunities and have bots to automatically submit those profitable transactions to the network.

Validators do get a portion of the full MEV amount anyway because searchers are willing to pay high gas fees (which go to the validator) in exchange for higher likelihood of inclusion of their profitable transactions in a block. Assuming searchers are economically rational, the gas fee that a searcher is willing to pay will be an amount up to 100% of the searcher's MEV (because if the gas fee was higher, the searcher would lose money).

With that, for some highly competitive MEV opportunities, such as DEX arbitrage, searchers may have to pay 90% or even more of their total MEV revenue in gas fees to the validator because so many people want to run the same profitable arbitrage trade. This is because the only way to guarantee that their arbitrage transaction runs is if they submit the transaction with the highest gas price.

This dynamic has made being good at "gas golfing" — programming transactions so that they use the least amount of gas — a competitive advantage, because it allows searchers to set a higher gas price while keeping their total gas fees constant (since gas fees = gas price * gas used).

A few well-known gas golf techniques include: using addresses that start with a long string of zeroes (e.g. 0x0000000000C521824EaFf97Eac7B73B084ef9306 (opens in a new tab) ↗ ) since they take less space (and hence gas) to store; and leaving small ERC-20 token balances in contracts, since it costs more gas to initialize a storage slot (the case if the balance is 0) than to update a storage slot. Finding more techniques to reduce gas usage is an active area of research among searchers.

Rather than programming complex algorithms to detect profitable MEV opportunities, some searchers run generalized frontrunners. Generalized frontrunners are bots that watch the mempool to detect profitable transactions. The frontrunner will copy the potentially profitable transaction's code, replace addresses with the frontrunner's address, and run the transaction locally to double-check that the modified transaction results in a profit to the frontrunner's address. If the transaction is indeed profitable, the frontrunner will submit the modified transaction with the replaced address and a higher gas price, "frontrunning" the original transaction and getting the original searcher's MEV.

Flashbots is an independent project which extends execution clients with a service that allows searchers to submit MEV transactions to validators without revealing them to the public mempool. This prevents transactions from being frontrun by generalized frontrunners.

MEV emerges on the blockchain in a few ways.

(DEX) arbitrage is the simplest and most well-known MEV opportunity. As a result, it is also the most competitive.

It works like this: if two DEXes are offering a token at two different prices, someone can buy the token on the lower-priced DEX and sell it on the higher-priced DEX in a single, atomic transaction. Thanks to the mechanics of the blockchain, this is true, riskless arbitrage.

Here's an example (opens in a new tab) ↗ of a profitable arbitrage transaction where a searcher turned 1,000 ETH into 1,045 ETH by taking advantage of different pricing of the ETH/DAI pair on Uniswap vs. Sushiswap.

Lending protocol liquidations present another well-known MEV opportunity.

Lending protocols like Maker and Aave require users to deposit some collateral (e.g. ETH). This deposited collateral is then used to then lend out to other users.

Users can then borrow assets and tokens from others depending on what they need (e.g. you might borrow MKR if you want to vote in a MakerDAO governance proposal) up to a certain percentage of their deposited collateral. For example, if the borrowing amount is a maximum of 30%, a user who deposits 100 DAI into the protocol can borrow up to 30 DAI worth of another asset. The protocol determines the exact borrowing power percentage.

As the value of a borrower's collateral fluctuates, so too does their borrowing power. If, due to market fluctuations, the value of borrowed assets exceeds say, 30% of the value of their collateral (again, the exact percentage is determined by the protocol), the protocol typically allows anyone to liquidate the collateral, instantly paying off the lenders (this is similar to how margin calls (opens in a new tab) ↗ work in traditional finance). If liquidated, the borrower usually has to pay a hefty liquidation fee, some of which goes to the liquidator — which is where the MEV opportunity comes in.

Searchers compete to parse blockchain data as fast as possible to determine which borrowers can be liquidated and be the first to submit a liquidation transaction and collect the liquidation fee for themselves.

Sandwich trading is another common method of MEV extraction.

To sandwich, a searcher will watch the mempool for large DEX trades. For instance, suppose someone wants to buy 10,000 UNI with DAI on Uniswap. A trade of this magnitude will have a meaningful effect on the UNI/DAI pair, potentially significantly raising the price of UNI relative to DAI.

A searcher can calculate the approximate price effect of this large trade on the UNI/DAI pair and execute an optimal buy order immediately before the large trade, buying UNI cheaply, then execute a sell order immediately after the large trade, selling it for the higher price caused by the large order.

Sandwiching, however, is riskier as it isn't atomic (unlike DEX arbitrage, as described above) and is prone to a salmonella attack (opens in a new tab) ↗ .

MEV in the NFT space is an emergent phenomenon, and isn't necessarily profitable.

However, since NFT transactions happen on the same blockchain shared by all other Ethereum transactions, searchers can use similar techniques as those used in traditional MEV opportunities in the NFT market too.

For example, if there's a popular NFT drop and a searcher wants a certain NFT or set of NFTs, they can program a transaction such that they are the first in line to buy the NFT, or they can buy the entire set of NFTs in a single transaction. Or if an NFT is mistakenly listed at a low price (opens in a new tab) ↗ , a searcher can frontrun other purchasers and snap it up for cheap.

One prominent example of NFT MEV occurred when a searcher spent $7 million to buy (opens in a new tab) ↗ every single Cryptopunk at the price floor. A blockchain researcher explained on Twitter (opens in a new tab) ↗ how the buyer worked with an MEV provider to keep their purchase secret.

DEX arbitrage, liquidations, and sandwich trading are all very well-known MEV opportunities and are unlikely to be profitable for new searchers. However, there is a long tail of lesser known MEV opportunities (NFT MEV is arguably one such opportunity).

Searchers who are just getting started may be able to find more success by searching for MEV in this longer tail. Flashbot's MEV job board (opens in a new tab) ↗ lists some emerging opportunities.

MEV is not all bad — there are both positive and negative consequences to MEV on Ethereum.

Many DeFi projects rely on economically rational actors to ensure the usefulness and stability of their protocols. For instance, DEX arbitrage ensures that users get the best, most correct prices for their tokens, and lending protocols rely on speedy liquidations when borrowers fall below collateralization ratios to ensure lenders get paid back.

Without rational searchers seeking and fixing economic inefficiencies and taking advantage of protocols' economic incentives, DeFi protocols and dapps in general may not be as robust as they are today.

At the application layer, some forms of MEV, like sandwich trading, result in an unequivocally worse experience for users. Users who are sandwiched face increased slippage and worse execution on their trades.

At the network layer, generalized frontrunners and the gas-price auctions they often engage in (when two or more frontrunners compete for their transaction to be included in the next block by progressively raising their own transactions' gas price) result in network congestion and high gas prices for everyone else trying to run regular transactions.

Beyond what's happening within blocks, MEV can have deleterious effects between blocks. If the MEV available in a block significantly exceeds the standard block reward, validators may be incentivized to reorg blocks and capture the MEV for themselves, causing blockchain re-organization and consensus instability.

This possibility of blockchain re-organization has been previously explored on the Bitcoin blockchain (opens in a new tab) ↗ . As Bitcoin's block reward halves and transaction fees make up a greater and greater portion of the block reward, situations arise where it becomes economically rational for miners to give up the next block's reward and instead remine past blocks with higher fees. With the growth of MEV, the same sort of situation could occur in Ethereum, threatening the integrity of the blockchain.

MEV extraction ballooned in early 2021, resulting in extremely high gas prices in the first few months of the year. The emergence of Flashbots's MEV relay has reduced the effectiveness of generalized frontrunners and has taken gas price auctions off-chain, lowering gas prices for ordinary users.

While many searchers are still making good money from MEV, as opportunities become more well-known and more and more searchers compete for the same opportunity, validators will capture more and more total MEV revenue (because the same sort of gas auctions as originally described above also occur in Flashbots, albeit privately, and validators will capture the resulting gas revenue). MEV is also not unique to Ethereum, and as opportunities become more competitive on Ethereum, searchers are moving to alternate blockchains like Binance Smart Chain, where similar MEV opportunities as those on Ethereum exist with less competition.

On the other hand, the transition from proof-of-work to proof-of-stake and the ongoing effort to scale Ethereum using rollups all change the MEV landscape in ways that are still somewhat unclear. It is not yet well known how having guaranteed block-proposers known slightly in advance changes the dynamics of MEV extraction compared to the probabilistic model in proof-of-work or how this will be disrupted when single secret leader election (opens in a new tab) ↗ and distributed validator technology get implemented. Similarly, it remains to be seen what MEV opportunities exist when most user activity is ported away from Ethereum and onto its layer 2 rollups and shards.

MEV in Ethereum Proof-of-Stake (PoS)

As explained, MEV has negative implications for overall user experience and consensus-layer security. But Ethereum’s transition to a proof-of-stake consensus (dubbed “The Merge”) potentially introduces new MEV-related risks:

In post-Merge Ethereum, validators (having made security deposits of 32 ETH) come to consensus on the validity of blocks added to the Beacon Chain. Since 32 ETH may be out of the reach of many, joining a staking pool may be a more feasible option. Nevertheless, a healthy distribution of solo stakers is ideal, as it mitigates the centralization of validators and improves Ethereum’s security.

However, MEV extraction is believed to be capable of accelerating validator centralization. This is partly because, as validators earn less for proposing blocks than miners currently do, MEV extraction may greatly influence validator earnings (opens in a new tab) ↗ after The Merge.

Larger staking pools will likely have more resources to invest in necessary optimizations to capture MEV opportunities. The more MEV these pools extract, the more resources they have to improve their MEV-extraction capabilities (and increase overall revenue), essentially creating economies of scale (opens in a new tab) ↗ .

With fewer resources at their disposal, solo stakers may be unable to profit from MEV opportunities. This may increase the pressure on independent validators to join powerful staking pools to boost their earnings, reducing decentralization in Ethereum.

In response to sandwiching and frontrunning attacks, traders may start conducting off-chain deals with validators for transaction privacy. Instead of sending a potential MEV transaction to the public mempool, the trader sends it directly to the validator, who includes it in a block and splits profits with the trader.

“Dark pools” are a larger version of this arrangement and function as permissioned, access-only mempools open to users willing to pay certain fees. This trend would diminish Ethereum’s permissionlessness and trustlessness and potentially transform the blockchain into a “pay-to-play” mechanism that favors the highest bidder.

Permissioned mempools would also accelerate the centralization risks described in the previous section. Large pools running multiple validators will likely benefit from offering transaction privacy to traders and users, increasing their MEV revenues.

Combating these MEV-related problems in post-Merge Ethereum is a core area of research. To date, two solutions proposed to reduce the negative impact of MEV on Ethereum’s decentralization and security after The Merge are Proposer-Builder Separation (PBS) and the Builder API.

In both proof-of-work and proof-of-stake, a node that builds a block proposes it for addition to the chain to other nodes participating in consensus. A new block becomes part of the canonical chain after another miner builds on top of it (in PoW) or it receives attestations from the majority of validators (in Pos).

The combination of block producer and block proposer roles is what introduces most of the MEV-related problems described previously. For example, consensus nodes are incentivized to trigger chain reorganizations in time-bandit attacks to maximize MEV earnings.

Proposer-builder separation (opens in a new tab) ↗ (PBS) is designed to mitigate the impact of MEV, especially at the consensus layer. PBS’ major feature is the separation of block producer and block proposer rules. Validators are still responsible for proposing and voting on blocks, but a new class of specialized entities, called block builders, are tasked with ordering transactions and building blocks.

Under PBS, a block builder creates a transaction bundle and places a bid for its inclusion in a Beacon Chain block (as the “execution payload”). The validator selected to propose the next block then checks the different bids and chooses the bundle with the highest fee. PBS essentially creates an auction market, where builders negotiate with validators selling blockspace.

Current PBS designs use a commit-reveal scheme (opens in a new tab) ↗ in which builders only publish a cryptographic commitment to a block’s contents (block header) along with their bids. After accepting the winning bid, the proposer creates a signed block proposal that includes the block header. The block builder is expected to publish the full block body after seeing the signed block proposal, and it must also receive enough attestations

from validators before it is finalized.

How does proposer-builder separation mitigate MEV’s impact?

In-protocol proposer-builder separation reduces MEV’s effect on consensus by removing MEV extraction from the purview of validators. Instead, block builders running specialized hardware will capture MEV opportunities going forward.

This doesn’t exclude validators totally from MEV-related income, though, as builders must bid high to get their blocks accepted by validators. Nevertheless, with validators no longer directly focused on optimizing MEV income, the threat of time-bandit attacks reduces.

Proposer-builder separation also reduces MEV’s centralization risks. For instance, the use of a commit-reveal scheme removes the need for builders to trust validators not to steal the MEV opportunity or expose it to other builders. This lowers the barrier for solo stakers to benefit from MEV, otherwise, builders would trend towards favoring large pools with off-chain reputation and conducting off-chain deals with them.

Similarly, validators don’t have to trust builders not to withhold block bodies or publish invalid blocks because payment is unconditional. The validator’s fee still processes even if the proposed block is unavailable or declared invalid by other validators. In the latter case, the block is simply discarded, forcing the block builder to lose all transaction fees and MEV revenue.

While proposer-builder separation promises to reduce the effects of MEV extraction, implementing it requires changes to the consensus protocol. Specifically, the fork choice rule on the Beacon Chain would need to be updated. The Builder API (opens in a new tab) ↗ is a temporary solution aimed at providing a working implementation of proposer-builder separation, albeit with higher trust assumptions.

The Builder API is a modified version of the Engine API (opens in a new tab) ↗ used by consensus layer clients to request execution payloads from execution layer clients. As outlined in the honest validator specification (opens in a new tab) ↗ , validators selected for block proposing duties request a transaction bundle from a connected execution client, which they include in the proposed Beacon Chain block.

The Builder API also acts as a middleware between validators and execution-layer clients; but it is different because it allows validators on the Beacon Chain to source blocks from external entities (instead of building a block locally using an execution client).

Below is an overview of how the Builder API works:

The Builder API connects the validator to a network of block builders running execution layer clients. Like in PBS, builders are specialized parties that invest in resource-intensive block-building and use different strategies to maximize revenue earned from MEV + priority tips.

A validator (running a consensus layer client) requests execution payloads along with bids from the network of builders. Bids from builders will contain the execution payload header—a cryptographic commitment to the payload's contents—and a fee to be paid to the validator.

The validator reviews the incoming bids and picks the execution payload with the highest fee. Using the Builder API, the validator creates a "blinded" Beacon block proposal that includes only their signature and the execution payload header and sends it to the builder.

The builder running the Builder API is expected to respond with the full execution payload upon seeing the blinded block proposal. This allows the validator to create a "signed" Beacon block, which they propagate throughout the network.

A validator using the Builder API is still expected to build a block locally in case the block builder fails to respond promptly, so they don't miss out on block proposal rewards. However, validator cannot create another block using either the now-revealed transactions or another set, as it would amount to equivocation (signing two blocks within the same slot), which is a slashable offense.

An example implementation of the Builder API is MEV Boost (opens in a new tab) ↗ , an improvement on the Flashbots auction mechanism (opens in a new tab) ↗ designed to curb the negative externalities of MEV on Ethereum. Flashbots auction allows miners in proof-of-work to outsource the work of building profitable blocks to specialized parties called searchers.

Searchers look for lucrative MEV opportunities and send transaction bundles to miners along with a sealed-price bid (opens in a new tab) ↗ for inclusion in the block. The miner running mev-geth, a forked version of the go-ethereum (Geth) client only has to choose the bundle with the most profit and mine it as part of the new block. To protect miners from spam and invalid transactions, transaction bundles pass through relayers for validation before getting to miners.

MEV Boost retains the same workings of the original Flashbots auction, albeit with new features designed for Ethereum’s switch to proof-of-stake. Searchers still find profitable MEV transactions for inclusion in blocks, but a new class of specialized parties, called builders, are responsible for aggregating transactions and bundles into blocks. A builder accepts sealed-price bids from searchers and runs optimizations to find the most profitable ordering.

The relayer is still responsible for validating transaction bundles before passing them to the proposer. However, MEV Boost introduces escrows responsible for providing data availability by storing block bodies sent by builders and block headers sent by validators. Here, a validator connected to a relay asks for available execution payloads and uses MEV Boost’s ordering algorithm to select the payload header with the highest bid + MEV tips.

How does the Builder API mitigate MEV’s impact?

The core benefit of the Builder API is its potential to democratize access to MEV opportunities. Using commit-reveal schemes eliminates trust assumptions and reduces entry barriers for validators seeking to benefit from MEV. This should reduce the pressure on solo stakers to integrate with large staking pools in order to boost MEV profits.

Widespread implementation of the Builder API will encourage greater competition among block builders, which increases censorship resistance. As validators review bids from multiple builders, a builder intent on censoring one or more user transactions must outbid all other non-censoring builders to be successful. This dramatically increases the cost of censoring users and discourages the practice.

Some projects, such as MEV Boost, use the Builder API as part of an overall structure designed to provide transaction privacy to certain parties, such as traders trying to avoid frontrunning/sandwiching attacks. This is achieved by providing a private communication channel between users and block builders. Unlike the permissioned mempools described earlier, this approach is beneficial for the following reasons:

The existence of multiple builders on the market makes censoring impractical, which benefits users. In contrast, the existence of centralized and trust-based dark pools would concentrate power in the hands of a few block builders and increase the possibility of censoring.

The Builder API software is open-source, which allows anyone to offer block-builder services. This means users aren’t forced into using any particular block builder and improves Ethereum’s neutrality and permissionlessness. Moreover, MEV-seeking traders won’t inadvertently contribute to centralization by using private transaction channels.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

From $34/Day — Car Rental HPN With Zero Terminal Shuttle