This commit is contained in:
mvonsteinkirch 2023-02-08 09:08:45 -08:00
parent bf818f2682
commit d3a292bfd1
133 changed files with 26 additions and 40 deletions

View file

@ -0,0 +1,50 @@
## arbitrage
<br>
### tl;dr
<br>
* since **liquidity on-chain is fragmented** (thousands of pools don't communicate with each other, each providing quotes for swapping assets in real-time), it creates an opportunity to buy low and sell high across different pools. for example, two DEXes offer a token at two different prices so that a token can be bought at the lower-priced DEX and sold on the higher-priced DEX in a single atomic transaction.
* due to the nature of the evm's atomic execution, **atomic arbitrages** are possible (as opposed to tradefi): smart contracts allow the packaging a sequential execution of txs, for a set of conditions. if the conditions are not met, the execution can fail, undoing all the on-chain interactions that just occurred.
##### [arbitrage types:](https://mirror.xyz/0xc19565163aFdEe3783FC970E4Bd0275B11848d34/a_v8f9yRqRFAvmOaEltTkPJSt1geSAwQdDps2Avb-DA)
* spatial (exchanges are located in different locations)
* triangular (profit from trading loops)
* statistical (rely on mathematical models for high-frequency arbs)
* cross-exchange
* sandwich
<br>
<img width="350" src="https://user-images.githubusercontent.com/1130416/217386455-c829a750-3bf1-4786-899d-adcb7d816573.png">
<br>
----
### in this dir
<br>
* [arbitrage patterns](patterns)
* [cool arb txs in the wild](mev_bots_wild)
<br>
----
### resources
<br>
* [anatomy of arber bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/arbers.md)

View file

@ -0,0 +1,15 @@
## interesting mev arb found in the wild
<br>
### 2022
* [arbitrageur begins with 1,000 Wrapped Ether (WETH), and ends up with 1,045](https://etherscan.io/tx/0x5e1657ef0e9be9bc72efefe59a2528d0d730d478cfc9e6cdd09af9f997bb3ef4)
* https://etherscan.io/tx/0x46bf75f983f72ab1e7d391b9b618634d5452d2979bd13e95d7ed83c39b621cae
* https://etherscan.io/tx/0x6ab410a68c9dbc1f4bb9ecf4e63aebbcef1fd6e4f58b1961b5e58fc76093b91c
* https://etherscan.io/tx/0x76e5fb10ce1cf21846839a35eca09d8da5a53512292986e887a705bf4cdec349
* https://etherscan.io/tx/0x565d1b25538e7b8f385d4656e9f3d3e4570eade3af747e49d0464c08db68d1a7
* https://etherscan.io/tx/0xda8ee92d0796af8889f1fc1a71a7072dfeeb5694692f163b77b302bf34393ff8
* https://etherscan.io/tx/0x299c020e03d93caa937e43f21093a4f3e6457efdc27c174495fc2cc1f293e9b2
* https://etherscan.io/tx/0xc649f14593613f93a3ef5dbfba55d50e5b4888ae25e277bba99c6884ffdda86b

View file

@ -0,0 +1,30 @@
## arbitrage patterns
<br>
### tl; dr
<br>
* spatial arbitrage involving one uniswap v3 pool and other venue seems to be the most common in 2022, followed by triangle arbitrage with one or two uniswap v3 pools.
<br>
----
### in this dir
<br>
* [spatial arb](spatial.md)
* [triangle arb](triangle.md)
* [taxed tokens](taxed.md)
<br>
---
### resources

View file

@ -0,0 +1,11 @@
## spatial patterns
### tl; dr
* also known as geographical arbitrage, it occurs when an arbitrageur looks for price differences between geographically separate markets.
<br>
---
### resources

View file

@ -0,0 +1 @@
## taxed tokens

View file

@ -0,0 +1 @@
## triangle pattern

View file

@ -0,0 +1,27 @@
## backrunning (tailgating)
<br>
### tl; dr
<br>
* backrunners predict trade opportunities that will be included into a future block based on the outcome of another user's trade, so that their tx is ordered immediately after some unconfirmed 'target tx'.
* a typical backrunner will send many identical txs, with gas price identical to that of the target tx, sometimes from different accounts, in order to increase the chances that one of their txs is ordered after the target but before any competitor (snipping).
* example of strategy: a buy tx immediately behind the initial liquidity. the bot swoops in and buys as many tokens as possible and waits for the price to go up and other traders buy the token from uniswap and proceeds to sell back the tokens at a higher price.
<br>
---
### resources
<br>
* [anatomy of backrunner bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/backrunners.md)
* [intro to backrunning on ethereum](https://www.youtube.com/watch?v=ApAJ1afUbBI)
* [dune for Portion of Daily Gas Used by Backrunning Bot Contracts](https://dune.com/phabc/backrunning-bots-gas-consumption)
* [backrunning study for bZx IDO](https://amanusk.medium.com/the-fastest-draw-on-the-blockchain-bzrx-example-6bd19fabdbe1)
* [ef discussion on random ordering of equally-priced txs](https://github.com/ethereum/go-ethereum/issues/21350)

View file

@ -0,0 +1,40 @@
## frontrunning
<br>
### tl, dr
<br>
* frontrunning is the process by which an adversary observes txs on the network layer and then acts upon this information by, for instance, issuing a competing tx, with the hope that this tx is mined before a victim's tx.
* **strategy example**: transaction A is broadcasted with a higher gas price than an already pending transaction B so that A gets mined before B.
* **generalized frontrunners** are bots that watch the mempool to detect profitable transactions, copy their code, replace addresses with theirs, then submit the modified tx with a higher gas price.
* **specialized frontrunners**, also known as longtails, are covered [here](https://github.com/go-outside-labs/mev-toolkit/tree/main/longtails)
<br>
---
### resources
<br>
* [anatomy of frontrunner bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/frontrunners.md)
* [shutter frontrunning protection](https://github.com/shutter-network/shutter)
##### cool txs and stories
* [generalized frontrunner copied the exploiter's 4 tx on past 50 blocks](https://twitter.com/bertcmiller/status/1613257826654392320)
##### some history
* [improving frontrunning of x*y=k mm, by vitalik](https://ethresear.ch/t/improving-front-running-resistance-of-x-y-k-market-makers/1281)
* [on cryptokitties `giveBirth()` frontrunning](https://maven11.substack.com/p/modular-mev-part-1the-introduction)
* [bancor ico frontrunning](https://hackingdistributed.com/2017/06/19/bancor-is-flawed/?ref=hackernoon.com)
* [150 lines of python frontrunning bancor](https://hackernoon.com/front-running-bancor-in-150-lines-of-python-with-ethereum-api-d5e2bfd0d798)

View file

@ -0,0 +1,39 @@
## liquidation
<br>
### tl, dr
<br>
* **lending protocol** work by requiring users to deposit some collateral. users can then borrow different assets and tokens from others depending on what they need, up to a certain amount of their deposited collateral. as the value of a borrower's collateral fluctuates, if the value of the borrowed assets exceeds the value of the collateral, the protocol allows anyone to liquidate the collateral (similar to margin calls in traditional finance).
* **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.
* **example of strategy**: bot detects a liquidation opportunity at a block and issues a liquidation tx, which is expected to be included in the next block. to compete with other liquidators, the bot sets high tx fees for their liquidation tx.
* **another strategy**: bot observes a tx that will create a liquidation opportunity (e.g., an oracle price update tx rendering a collateralized debit to be liquidated), then backruns this tx with a liquidation tx to avoid the fee bidding competition.
<br>
---
### in this dir
<br>
* [flashloans](flashloans)
* [compound](compound.md)
* [liquity](liquity.md)
* [aave](aave.md)
<br>
---
## resources
<br>
* [anatomy of liquidator bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/liquidators.md)
* [liquidation dashboard, by eigenphi](https://eigenphi.io/mev/ethereum/liquidation)
* [understanding compound's liquidation, by zengo](https://zengo.com/understanding-compounds-liquidation/)
* [nahtan worsley's liquidation strategies, by forbes](https://www.forbes.com/sites/jeffkauflin/2022/10/11/the-secretive-world-of-mev-where-crypto-bots-scalp-investors-for-big-profits/?sh=25489eda2d8d)
* [cycle of liquidations in the CRV pool](https://twitter.com/AaveAave/status/1595168982541209611)

View file

@ -0,0 +1,37 @@
## aave protocol
<br>
### tl; dr
<br>
* decentralized lending protocol that lets users lend or borrow crypto assets or real-world assets (RWAs) without going to a centralized intermediary.
* users deposit digital assets into liquidity pools, which become funds so that the protocol can lend out.
<br>
### tl; dr aave v3
<br>
* **portal**: allows flow of liquidity between aave v3 markets across different networks (governance-approved bridges can burn atokens while minting them on the destination network)
* **emode**: the high-efficiency mode allows borrowers to extract the highest borrowing power out of their collateral when supplied + borrowed assets are price-correlated (e.g. both are derivatives of the same underlying asset).
* **isolation mode**: new assets can be listed as isolated so borrowers cannot supply other assets as collateral (but can capture yield) but only approved stablecoins.
* **siloed borrowing** allows assets with risky manipulatable oracles to be listed as a single borrow asset.
* **multiple rewards** per token.
* **chains**: avalanche, pptimism, polygon, fantom, harmony and arbitrum.
<br>
---
### resources
<br>
* [liquidations, by aave protocol](https://docs.aave.com/developers/guides/liquidations)
* [aave v2 whitepaper](https://github.com/aave/protocol-v2/blob/master/aave-v2-whitepaper.pdf)
* [aave v3 docs](https://docs.aave.com/developers/getting-started/readme)

View file

@ -0,0 +1,22 @@
## compound
<br>
### tl; dr
<br>
* decentralized protocol that establishes markets with algorithmically set interest rates, based on supply and demand, and allowing users to frictionlessly
exchange the time value of crypto assets.
<br>
---
### resources
<br>
* [compound docs](https://docs.compound.finance/)
* [compound whitepaper](https://compound.finance/documents/Compound.Whitepaper.pdf)

View file

@ -0,0 +1,40 @@
## flashloans
<br>
### tl; dr
<br>
* flashloans allow the borrowing of any available amount of assets without any collateral, as long as the liquidity is returned to the protocol within one block tx.
* flashloans can be requested through smart contracts that execute the steps to borrow nad pay the loan (+ interest fees) withing the same tx.
<br>
---
### in this dir
<br>
* [smart contracts](smart_contracts)
<br>
---
### resources
<br>
* [flashloans dashboard, by eigeinphi](https://eigenphi.io/mev/ethereum/flashloan)
* [flashloans from dYdX margin trading, by eigenphi](https://medium.com/coinmonks/get-everything-for-nothing-how-to-use-flash-loans-to-launch-an-arbitrage-d8520827cbfe)
* [kollateral aggregator](https://www.kollateral.co/)
* [taking undercollaterized loans, by samczsun](https://samczsun.com/taking-undercollateralized-loans-for-fun-and-for-profit/)
* [tfusd flashloan writeup](https://github.com/Jonah246/tfusd-flashloan-attack-write-up)
* [defi hacks: flashloans](https://wooded-meter-1d8.notion.site/0e85e02c5ed34df3855ea9f3ca40f53b?v=22e5e2c506ef4caeb40b4f78e23517ee)
* [flashloan-rs rust crate](https://crates.io/crates/flashloan-rs)
* [flashloan monitor](https://tools.blocksec.com/flashloan/eth)
* [code for flashmint arb](https://github.com/fifikobayashi/FlashMintArbitrage)

View file

@ -0,0 +1,16 @@
## flashloans smart contracts
<br>
### code
<br>
* [sugardad (aave v2)](https://github.com/fifikobayashi/SugarDaddyFlashloan)
* [dydx and aave aggregate](https://github.com/fifikobayashi/Aggregated-Flashloan)
<br>
---
### resources

View file

@ -0,0 +1,61 @@
function callFunction(address sender, Account.Info memory accountInfo, bytes memory data) external {
// Use chi tokens
uint256 gasStart = gasleft();
// Let the executor or the dYdX contract call this function
// probably fine to restrict to dYdX
require(msg.sender == executor || msg.sender == address(soloMargin));
// Decode the passed variables from the data object
(
address[] memory sUSDAddresses,
uint256[] memory sUSDLoanIDs,
uint256 wethEstimate,
uint256 usdcEstimate,
uint256 ethToCoinbase
)
= abi.decode(data,
(
address[],
uint256[],
uint256,
uint256,
uint256
));
// Swap WETH for USDC on uniswap v3
uniswapRouter.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams(
address(WETH), // address tokenIn;
usdcTokenAddress, // address tokenOut;
3000, // uint24 fee;
address(this), // address recipient;
10**18, // uint256 deadline;
usdcEstimate, // uint256 amountOut;
wethEstimate, // uint256 amountInMaximum;
0 // uint160 sqrtPriceLimitX96;
)
);
// Swap USDC for sUSD on Curve
curvePoolSUSD.exchange_underlying(
1, // usdc
3, // sUSD
usdcEstimate, // usdc input
1); // min sUSD, generally not advisible to make a trade with a min amount out of 1, but its fine here I think because the overall risk of getting rekt is low
// Liquidate the loans
for (uint256 i = 0; i < sUSDAddresses.length; i++) {
sUSDLoansAddress.liquidateUnclosedLoan(sUSDAddresses[i], sUSDLoanIDs[i]);
}
// We got back ETH but must pay dYdX in WETH, so deposit our whole balance sans what is paid to miners
WETH.deposit{value: address(this).balance - ethToCoinbase}();
// Pay the miner
block.coinbase.transfer(ethToCoinbase);
// Use for chi tokens
uint256 gasSpent = 21000 + gasStart - gasleft() + (16 * msg.data.length);
CHI.freeFromUpTo(owner, (gasSpent + 14154) / 41947);
}

View file

@ -0,0 +1,19 @@
## [liquity](https://www.liquity.org/)
<br>
### tl; dr
<br>
* decentralized borrowing protocol that allows drawing interest-free loans against ether used as collateral
<br>
---
### resources
<br>
* [liquity docs](https://docs.liquity.org/)

View file

@ -0,0 +1,18 @@
## longtails
<br>
### tl, dr
<br>
* every other mev strategy is already dominated by experienced searchers, so longtails are the **best bet for newcomers**.
* it encloses all other forms of MEV (undiscovered MEV): on **less known protocols / economic mechanisms or event-based strategies**.
<br>
---
### resources
* [anatomy of longtailor bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/longtailors.md)

View file

@ -0,0 +1,30 @@
## oracles
<br>
### tl;dr
<br>
* price oracles are any defi tool showing an asset's price. they can either on or off chain.
* oracles should provide a trustless way of getting extrinsic (off-chain) information, and some key functions such as: collecting data from an off-chain source, transfering the data on-chain with a signed message, and making the data available by putting it in a smart contracts storage.
* oracle exploitation can generate profit opportunities (e.g., through arbitrage or liquidation, multi-block)
<br>
---
### in this repo
* [TWAP](twap.md)
* [TWAMM](twamm.md)
* [chainlink](chainlink.md)
---
### resources

View file

@ -0,0 +1,20 @@
## chainlink
<br>
### tl; dr
<br>
* a decentralized oracle network consisting of three key smart contracts:
* a reputation contract: keep track of data providers' performance.
* an order-matching contract: selects bids from oracles using the reputation contract.
* an aggregation contract—and an off-chain registry of data providers.
* one of the main challenges with such a decentralized approach is the formulation of the aggregation function.
* chainlink proposes calculating a weighted response, allowing a validity score to be reported for each oracle response.
<br>
---
### resources

View file

@ -0,0 +1,21 @@
## twamm designs
<br>
### tl; dr
* a new type of automated market maker, or AMM, that helps traders on Ethereum efficiently execute large orders.
* time weighted amm designs prevent sandwich attacks by executing transactions lazily.
* in twamm, orders are executed as if they were placed between blocks. this way, an attcker would need to straddle blocks in order to take advantage of the victim's slippage tolernace (which is riskier than simply including txs around the victim's).
<br>
---
### resources
* [twamm by paradigm](https://www.paradigm.xyz/2021/07/twamm)
* [twamm reference implementation in python](https://github.com/para-dave/twamm)
* [some properties of twamm](https://github.com/pcaversaccio/reentrancy-attacks)

View file

@ -0,0 +1,37 @@
## TWAP oracles
### tl; dr
<br>
* an assets time-weighted average price (TWAP) is the measure of an assets average price over a predetermined period of time (any specified duration).
* TWAP trading algorithms seek to optimize average price while executing over a specified time period.
* generally used to execute large orders that are expected to have significant market impact.
<br>
---
### tl; dr oracle attacks
<br>
* on pos ethereum, block builder building successive block might be able to manipulate oracles for multi-block MEV extraction, as proposers know one epoch (32 blocks or 6 minutes and 24 seconds) ahead if they are the next block proposer.
* with mev-boost, an attacker could observe the set of upcoming proposers. if they finds two successive proposers that have both been proposing blocks, then the attacker can anticipate the attack.
* a potential attack vector is on lending protocols, where an attacker can borrow assets that are immediately undercollateralized.
<img width="791" src="https://user-images.githubusercontent.com/1130416/209031792-52d7671e-480e-497b-9736-4e22e1810fab.png">
<br>
___
### resources
* [multi- block MEV by flashbots](https://collective.flashbots.net/t/multi-block-mev/457/2?u=nerolation)
* [statistical analysis on ethereum k-consecutive block proposal](https://alrevuelta.github.io/posts/ethereum-mev-multiblock)
* [uniswap v3 twap oracles](https://uniswap.org/blog/uniswap-v3-oracles)
* [multi-block mev, by chainsecurity](https://chainsecurity.com/oracle-manipulation-after-merge/)

View file

@ -0,0 +1,40 @@
## sandwiching
<br>
### tl, dr
* sandwiching occurs when a searcher identifies a profitable trade in the mempool that will cause an impact on the price of an asset.
* a searcher buys or sells a calculated amount directly before the large trade is executed and then immediately exits their position after the large order has taken place, banking a profit.
* the main theme of sandwich attacks is the deterministic price slippage caused by available liquidity in the pool, which is deterministic . slipage is the change in the price of an asset during a trade.
* sandwiches (and most frontruns) are often labelled **toxic mev** because the tx that is frontrun either executes at worse conditions or fails to execute.
* a softer side of sandwich is on the lens of economic efficiency, on which an order can create a consumer surplus and the absence of a [nash equilibrium](https://en.wikipedia.org/wiki/Nash_equilibrium). the bot operator would love the economic system back.
<br>
---
### in this dir
* [interesting txs in the wild](interesting_examples.md)
<br>
---
### resources
* [anatomy of sandwichor bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/sandwichors.md)
* [sandwich attacks on uniswap v2](https://www.defi-sandwi.ch/)
* [sandwich overview, by eigenphi](https://eigenphi.io/mev/ethereum/sandwich)
* [modern mev sandwich attacks on ethereum routers, by totlsota.eth](https://mirror.xyz/totlsota.eth/9JaNkZ1XQfQD6Y79aLYHC_kb_dSBoJ2JYiag5BuGGM8)
* [demystify the dark forest: sandwich attack, by coinmonks](https://medium.com/coinmonks/demystify-the-dark-forest-on-ethereum-sandwich-attacks-5a3aec9fa33e)
* [analysing execution quality in osmosis, by meka.tech](https://meka.tech/writing/analysing-execution-quality-in-osmosis--e9dd8394-0d09-4d92-a0c7-27629d321af0)

View file

@ -0,0 +1,11 @@
## interesting examples in the wild
<br>
#### 2022
* https://etherscan.io/tx/0x90f2f133fcfe8e1870b69323ea0b46193b9443a701b4cef81a14c727a1df648f
* [MEV bot sandwich attacked this tx](https://etherscan.io/tx/0xa79dfb5d4442a4ff04768c638bf306b75340ac325e86c34653904ab7f7429ac5)
* [bot spent $18,583.13, to make $19,182.43](https://etherscan.io/tx/0x206203f5d62b8027fc8ad0c88be2b6d7b8e9c6b5b81a49c9a8d1c227d6027018)
* [$APE sandwiches analysis, by eigenphi](https://mirror.xyz/0xc19565163aFdEe3783FC970E4Bd0275B11848d34/G1uzYCDIR6TjWzNDFNKEhdawGJXXGJxISBS5hM2eROc)

View file

@ -0,0 +1,34 @@
## sniping
<br>
### tl; dr
<br>
* **liquidity sniping** happens when searchers compete to purchase an asset immediately after the creation of a liquidity pool.
* tokens are then not off-loaded in the same block, but instead sold over the next minutes or hours.
* profits for a sniper are not guaranteed.
<br>
### tricks
<br>
#### cex
* craw relays by requesting through a network of proxies to not get ratelimited (for example, by cloudflare ~5 seconds).
* maintain an in-memory list of endpoints that are predicted to be cached, so only use the ones that are predicted to be uncached.
* [proxymesh: rotating anonynous http proxy servers](https://proxymesh.com/)
<br>
---
### resources
<br>
* [anatomy of snipor bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/snipers.md)

View file

@ -0,0 +1,19 @@
## statistical strategies
<br>
### tl; dr
<br>
---
### resources
<br>
* [anatomy of stat bots](https://github.com/go-outside-labs/mev-toolkit/blob/main/anatomy_of_mev_bots/bots/stat-arbers.md)