<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nacho Grayeb on Medium]]></title>
        <description><![CDATA[Stories by Nacho Grayeb on Medium]]></description>
        <link>https://medium.com/@nachograyeb_98844?source=rss-866a7e3c5013------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CH6h11C4tcY3yenXTitd3Q.jpeg</url>
            <title>Stories by Nacho Grayeb on Medium</title>
            <link>https://medium.com/@nachograyeb_98844?source=rss-866a7e3c5013------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:46:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nachograyeb_98844/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Engineer’s Path to Blockchain: Building and Testing Flash Loan Arbitrage Smart Contracts]]></title>
            <link>https://medium.com/@nachograyeb_98844/the-engineers-path-to-blockchain-building-and-testing-flash-loan-arbitrage-smart-contracts-ddd487ba55cf?source=rss-866a7e3c5013------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddd487ba55cf</guid>
            <category><![CDATA[flash-loan]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[arbitrage-trading]]></category>
            <dc:creator><![CDATA[Nacho Grayeb]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 15:02:34 GMT</pubDate>
            <atom:updated>2025-04-08T15:12:21.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THy7cTBbDtcWkIKcieh8Iw.jpeg" /></figure><h4>Table of contents</h4><ol><li><a href="#712c">Intro</a></li><li><a href="#0a02">My background</a></li><li><a href="#4d74">Overview</a></li><li><a href="#0744">What is arbitrage trading?</a></li><li><a href="#e06b">What is a flash loan?</a></li><li><a href="#af5e">The mechanics of flash loan arbitrage</a></li><li><a href="#9eb0">Arbitrage opportunity finder script/bot</a></li><li><a href="#0fb7">Potential pitfalls and challenges</a></li><li><a href="#2132">MEV: Maximal Extractable Value</a></li><li><a href="#f214">Flashbots: transaction bundles</a></li><li><a href="#5827">Scoping the practical example</a></li><li><a href="#ad5b">Flash Loan and Flash Loan Receiver smart contracts</a></li><li><a href="#8dc9">Receiving a flash loan from Balancer</a></li><li><a href="#ac0a">Arbitrage implementation</a></li><li><a href="#ce6f">Tests with mocked dependencies</a></li><li><a href="#2ccb">Testing with real-world blockchain data: Polygon fork</a></li><li><a href="#6522">Manipulating token prices with wallet impersonation</a></li><li><a href="#ada5">Differences between DEXs</a></li><li><a href="#d76f">Successful arbitrage test cases</a></li><li><a href="#f850">Bonus round: another flash loan experiment</a></li><li><a href="#3eea">Conclusion</a></li></ol><h4>Intro</h4><p>Hey, everyone! In this article I’ll be diving into a fascinating topic that I just recently came across: flash loan arbitrage trading. This is a DeFi trading strategy that takes advantage of brief windows of opportunity created by natural market inconsistencies, powered by uncollateralized loans to potentially yield significant profits, without needing to invest large amounts of capital.</p><p>OK, this may sound like a bunch of cool words put together right now, but I’ll explain it step-by-step and show you how I implemented my own smart contracts and how I tested them in environments with mock data and with actual data from the blockchain.</p><p>But first, let me tell you a little bit about myself and my motivations for doing this.</p><h4>My background</h4><p>My name is Ignacio Grayeb, better known as Nacho, I’m a software engineer with around 6.5 years in the industry at the time of writing. I have an Electronics Engineering degree, which is where I acquired my coding foundations (among many other things). Since graduation, I mostly focused on Backend development with a variety of tech stacks, Node.js being the most prominent in the past few years.</p><p>My interest in blockchain appeared around September 2020, when I was working at SOUTHWORKS, a software development company that was a huge part of my professional upbringing. I was offered to join a team for an R&amp;D blockchain project within the company. We spent three months developing a PoC applying smart contracts to retail, creating Solidity contracts and building a functional supply chain scenario using Azure cloud services. We made our work public with <a href="https://medium.com/southworks/smart-contracts-in-the-retail-industry-59cb4c985ec1">this article</a>, if you’re interested (also, <a href="https://github.com/southworks/azure-blockchain-supply-chain/tree/master">GitHub repo</a>).</p><p>Though my career then took me elsewhere, blockchain remained an interest. Shortly after, I landed a job at POAP, a significant Web3 company. Although I was not directly working on the blockchain side of things back then (I was Engineering Project Lead mainly in traditional web stacks), understanding the product, business logic and code base, as well as attending a few conferences and events (e.g., ETHDenver and ETH Latam), at least allowed me to get a taste of the environment.</p><p>Then again I took a different path for a brief period, but it wasn’t long until I recognized the importance of specializing in something that genuinely excited me. Despite the value of my latest Technical Lead experience, I realized becoming a blockchain engineer required focused learning time — hard to achieve while managing team deliverables in a fast-paced environment. So, I took the leap of faith and followed my instincts and here I am, building my career as a blockchain engineer.</p><p>But enough about me, let’s get right down to it!</p><h4>Overview</h4><p>So, flash loan arbitrage trading. To understand this strategy, we need to break it down a little bit. There are two main concepts here: flash loans and arbitrage trading. They both combine to make something more powerful than the sum of its parts.</p><p>Let’s start with the basics.</p><h4>What is arbitrage trading?</h4><p>Arbitrage is a trading strategy that takes advantage of temporary market inconsistencies to make a profit. This is something that can happen not only in the crypto/DeFi world, but also in traditional finance. You could buy an asset on a particular exchange and find that on a different exchange, at a very specific moment, its value is slightly higher, so then you sell on the latter and keep the profit.</p><p>The basic idea is as simple as that. So here, what we want to do is buy crypto assets or tokens on one exchange and sell them on another where their price is higher.</p><p>Now, there are centralized exchanges (your typical Binances and Coinbases out there) and decentralized exchanges, known as DEXs. The former consist of centralized entities that take your fiat currency and exchange it for crypto assets in wallets that they hold, giving you the option to withdraw them to an external wallet if you wanted to, exchange them back to fiat, or engage in different crypto investments within the platform. What this means is they operate kind of like a bank or broker, where rather than you actually owning the assets, you’re trusting this entity to manage them in the hope that they will be available whenever you decide to withdraw them or do whatever you like with them. The latter, on the other hand, are platforms that run directly on the blockchain, where you can trade, swap, invest in different crypto assets, while actually being the custodian of your own funds.</p><p>While this type of trading can be done between centralized exchanges (CEXs), here we’ll focus on DEXs, mainly because once we find an arbitrage opportunity, we need to be fast at taking advantage of it before it disappears. With DEXs, you can both access pricing data and execute trades directly on the blockchain through smart contracts, eliminating the multiple layers of overhead present in CEXs. Some critical advantages that DEXs offer in this scenario are:</p><ul><li>Atomic execution — Your entire arbitrage transaction either completely succeeds or completely fails, preventing partial execution risks</li><li>Reduced counterparty risk — No need to pre-fund multiple exchange accounts or worry about withdrawal delays</li><li>Programmable logic — Smart contracts can incorporate complex conditions and execute precisely when opportunities arise</li></ul><p>The “atomic execution” and “programmable logic” items will make even more sense when I explain the second half of our strategy…</p><h4>What is a flash loan?</h4><p>A flash loan is a form of uncollateralized loan that allows users to borrow millions of dollars in crypto, as long as they are returned within the same transaction.</p><p>But, wait… what does that even mean? You’re telling me I can borrow millions of dollars but I have to return them in the same transaction? How would this be of any use? Here’s where the power of blockchain shines. Transactions in the fiat world are usually simple operations, like transferring funds between accounts, exchanging currency, buying or selling stocks. But in the world of blockchain, we have smart contracts, which means we have code that could potentially execute multiple different steps, giving way to complex transactions.</p><p>So here is where it gets interesting. You can take a flash loan, execute a bunch of operations with it (*clears throat* …arbitrage trading, maybe?), reimburse the loan and keep the profits, all within the same transaction. Boom!</p><p>But, hey… what happens if your arbitrage opportunity turns out not profitable for whatever reason when you’re executing it? How are you going to pay the flash loan back? This is where transaction atomicity comes into play.</p><p>Flash loan providers are actually smart contracts. Their logic checks that at the end of the transaction the full amount of the loan has been returned. If that check fails, then the entire transaction is reverted, like nothing ever happened. So if your arbitrage fails or is not profitable in the end, it will be like you never took the flash loan and you never performed the swaps on the involved DEXs, eliminating the risk of you ending up owing amounts you could never afford to pay back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*ZX6Q7jiT3X3VGVSG.gif" /></figure><p>Right? RIGHT?? Well, at least that’s what happened to me when I first heard about this, just a few weeks ago.</p><p>Now, I mentioned the word “uncollateralized” when I defined a flash loan. This means that in order to take a flash loan, you do not need to provide an asset of yours as collateral. If for whatever reason you fail to return the flash loan within the same transaction, it will just revert. Instead of asking for collateral, what some (or most) providers do is they charge a small fee to be paid together with the flash loan reimbursement. So they’ll check that the flash loan amount plus the fee are transferred back to them to determine if the transaction goes through or reverts. We’ll talk about this further down the line.</p><h4>The mechanics of flash loan arbitrage</h4><p>So, hopefully, you get the picture of what we’re trying to do here: executing arbitrage trading, powered by flash loans, to maximize profits without the need of using your own capital (in theory, we’ll see why later).</p><p>So let’s start by focusing on this core idea and seeing how this would work conceptually with smart contracts.</p><p>We should write a smart contract that does the following:</p><ul><li>Take a flash loan for a specific token by interacting with an external smart contract, the flash loan provider</li><li>Use the borrowed tokens to buy a different token from a source DEX</li><li>Take the new tokens that resulted from the source DEX and sell them for the original token on the target DEX</li><li>With the resulting amount of tokens (which should be greater than the flash loan we took), pay back the flash loan (and fee if there is one)</li><li>Keep the profit</li></ul><p>The diagram below will hopefully illustrate this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGKBr3poKfk-t0mRxqv-rw.png" /></figure><p>So what we need to do to replicate this basic setup is create a smart contract that interacts with three other smart contracts: the flash loan provider, the source DEX and the target DEX. Later on, we’ll see how.</p><p>Once we get here, we deploy the smart contract to the blockchain and it’s ready to be used to generate some profit! Well… not so fast. This contract will take as inputs what tokens to trade, in what DEXs and the flash loan amount of an arbitrage opportunity that has already been detected. It will just take the inputs and do what it’s told.</p><p>For the whole thing to be of any use, we need another key component, which brings us to the next section.</p><h4>Arbitrage opportunity finder script/bot</h4><p>What we need now is a script or application that acts as a sort of bot, scanning different DEXs and token pairs to detect price discrepancies, i.e., arbitrage opportunities.</p><p>Once an arbitrage opportunity is found, it should call our smart contract with the relevant data (involved tokens, source and target DEXs) and execute the flash loan and arbitrage logic to generate profit.</p><p>The diagram below shows the basic idea of the system consisting of the arbitrage finder script and the flash loan arbitrage smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*rqURGMc0pkpEB0EkDevLXQ.png" /></figure><p>As we move on, we’ll see that there is more to it, but this is the general idea. You can have this script run 24/7 finding opportunities and generating income through the smart contract.</p><h4>Potential pitfalls and challenges</h4><p>Now, this all sounds great. You create a smart contract and a script and you start making money without putting in any of your own capital. Free money, right? Well…</p><p>If it sounds too good to be true, it kind of is. The truth is that once this all goes live, there are some complex challenges to face, and if they are not considered, this might all be good for nothing, or even make you lose money.</p><ul><li><strong>Transaction fees</strong>: transactions cost gas, which must be paid regardless of whether they succeed or fail. Even if we already have the safeguard that flash loans revert the whole transaction if we’re unable to repay them, we still have to pay gas, which could eat into our profits. So it’s crucial to optimize the smart contract so that it is as gas efficient as possible. Aside from optimizing the code so that transactions are less costly, we can also pick chains with lower transaction costs.</li><li><strong>Competition</strong>: in a context where we’re looking for small windows of opportunity that may quickly vanish, the competition will be fierce. Not only will there be tons of individual developers running their own bots and smart contracts, it will also be crowded with different kinds of actors doing this at a professional level. This means that the script (or bot) and the smart contract will have to be super sharp at finding the opportunities and executing the logic before the opportunities disappear. And they will have to outperform people who really know what they’re doing and have been doing it for a while.</li><li><strong>Flash loan fees: </strong>depending on the source you’re using to take the flash loan, more often than not, you will be charged a small fee to be paid when reimbursing the flash loan. If the arbitrage profit is not enough to cover the fee, the transaction will just revert, so there’s no risk associated with not being able to afford the fee itself. However, if this fee was not considered when detecting profitable arbitrage opportunities, you might end up calling the contract and paying transaction costs for an opportunity that ends up not being profitable because of the flash loan fee. The <a href="https://aave.com/docs/developers/flash-loans">Aave protocol</a>, one of the most widely used, has a base fee of 0.05%. <a href="https://docs-v2.balancer.fi/concepts/vault/#flash-loans">Balancer </a>V2’s fee at the time of writing is valued at 0, although there is an actual variable in the smart contract, which means the fee values could become non-zero at some point.</li><li><strong>Slippage</strong>: depending on the trade size relative to the available liquidity for a given token pair, execution prices might differ significantly from the expected price. For instance, let’s say we pick a DEX and we want to swap USDC for WETH. We might have an expected WETH price of 2000 USDC before the trade, but then we choose to trade 10,000 USDC, expecting to get 5 WETH in return. However, due to limited liquidity, those 10,000 USDC could make the price of WETH go up noticeably. For DEXs with smaller liquidity pools, this price difference could be as much as several times its original value. This brings a challenge when determining whether an opportunity would be profitable and calculating the right parameters for the arbitrage execution. There is a trade-off between the flash loan amount to be used in the trade and the price differences it might in turn generate. It should be large enough to yield significant profit, but not so large that it might create a considerable deviation from the expected price, rendering the final operation unprofitable.</li><li><strong>MEV</strong>: this one deserves its own section in the article (and it will indeed get it). An acronym for <em>Maximal Extractable Value</em> (previously, <em>Miner Extractable Value</em>), it represents the profit that miners, validators and other actors in the blockchain can extract by reordering, including or excluding transactions within a given block. Up next, we’ll dive into a dedicated section to explain why this is a challenge and how it could be mitigated.</li></ul><h4>MEV: Maximal Extractable Value</h4><p>Alright, so I just gave something of a definition for this, but what the heck does that mean?</p><p>Blockchain transactions are public, anyone can see pretty much anything about them. Go to <a href="https://etherscan.io/">Etherscan</a>, for instance, and you’ll find all of the Ethereum transactions, by transaction hash, smart contract address, token address, block number, you name it. But before they’re even added to the blockchain, transactions go through a sort of limbo called the mempool, which is a storage of unconfirmed transactions that have been broadcast to the network, but not yet included in a block. They remain there until they are either included in a block or dropped.</p><p>The mempool is public, which means basically anyone could spot your transaction, see that it will be profitable and just replicate it and place it before yours. They could ensure this by paying a higher gas fee and end up making the profit that you were expecting to make. By the time your transaction goes through, the arbitrage opportunity will very likely not be profitable anymore.</p><p>This is a specific case of an MEV strategy called <em>front-running</em>. Here, the value can be extracted by another participant by ensuring their transaction is processed before the target profitable transaction that they spotted in the mempool.</p><p>The opposite can also be done: placing the transaction right after the profitable transaction. This one is called <em>back-running</em><strong><em>. </em></strong>And one could even combine front-running and back-running to create what is called a <em>sandwich attack</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqL9tXlKwQTsPcVAMbxVuQ.jpeg" /></figure><p>As I mentioned in the previous section, different “actors” in the blockchain can extract value from reordering, including or excluding transactions. Originally, these actors were miners in PoW blockchains. Given that they were the ones building the blocks for inclusion in the blockchain, they could use the reordering, exclusion or inclusion of transactions to their favor. As other consensus mechanisms appeared, such as PoS, plus the fact that blockchain participants other than miners or validators could actually extract MEV, the acronym was switched from <em>Miner Extractable Value </em>to<em> Maximal Extractable Value.</em></p><p>Actually, if you think about it, arbitrage trading <em>is </em>itself a case of MEV, and an example in which you don’t need to be a miner or validator to participate. Also, this is the good kind of MEV. From my description above, it sounds like MEV is always a bad thing, like with front-running and sandwich attacks, but there are kinds that are actually good for the ecosystem. Arbitrage trading helps bring the market into equilibrium, maintaining price consistency across different exchanges and protocols, while also enhancing liquidity by increasing trading volume.</p><p>Now, is there anything we can do about the kind of MEV that will run away with our profits?</p><p>Well, yes, there are ways around it, and here I’ll briefly talk about one of them.</p><h4>Flashbots: transaction bundles</h4><p><a href="https://docs.flashbots.net/">Flashbots</a> is a research and development organization that created a suite of tools to mitigate the negative externalities of MEV extraction, particularly focusing on front-running and transaction reordering issues.</p><p>It allows users to send <em>bundles </em>with the transactions they intend to include in the blockchain directly to block producers, bypassing the public mempool.</p><p>This means that transactions will remain hidden until they’re included in a block, protecting them from MEV attackers. Additionally, it provides a layer of protection for transactions that would either fail or not be profitable. If this were the case, it’ll just not include them in a block, meaning you won’t be paying gas fees for failed attempts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*bB4RLBtu6ytUHHnP" /></figure><p>So with this tool you are protected from front-runners and the like, and you avoid losing gas money for failed transactions. Now, in order for this to work, block producers receive an incentive to include transaction bundles in blocks. This incentive comes in the form of a “tip” that you set when submitting the bundle.</p><p>The good thing about this is that the tip will only be transferred to the block producer if your entire transaction bundle is included. So you won’t be paying for tips nor gas fees unless your transactions go through. If they do, you’ll be paying for both.</p><p>The challenging thing is that now you’re in a position in which your success heavily depends on the amount you’re willing to tip the block producer. And guess what… there are others with more resources than you doing the same thing.</p><p>Hopefully, you’re starting to get the picture of the kind of rabbit hole we’re getting into…</p><p>…which leads me to the centerpiece of the article: the actual practical example.</p><h4>Scoping the practical example</h4><p>Right at the beginning of this article, I said that there would be actual smart contracts and tests and that I’d be showing all of that. Well, that’s all true and the time has come. However, I didn’t want to just jump into it without sharing the context I provided in the previous sections.</p><p>When I first heard about flash loan arbitrage, I wanted to just go ahead, code it and start putting it to the test, but I knew it would have its challenges and I wanted to consider them in my implementation. I realized, however, that going from 0 to 100% in something like this wouldn’t be something realistic to pull off within a few weeks. So I decided to establish a manageable scope and start by sharing it in an academic fashion. In any case, I can always continue to build on top of it and share the progress in stages. And, although the pitfalls and challenges I mentioned will be way out of scope at this stage, I still wanted to share them, because they were part of my thought process and of my motivation for writing this article.</p><p>So, without further ado, my practical example at this stage is limited to the following:</p><ul><li>Flash loan arbitrage smart contract</li><li>Tests using mocked dependencies</li><li>Tests in an environment with real blockchain data</li></ul><p>In the next few sections, I’ll explain how I built the smart contract and these different test environments. When I got to the point of testing with some real-world data, I figured it would be a good moment to draw the line and just share it. Playing around in such an environment gave me a bit of a feel of what it’s like to work with different DEXs, monitor price discrepancies and see how different trade volumes can affect token prices, while creating some “end-to-end” test cases to see how my smart contract behaves.</p><p>All of the code mentioned from here on is available in my <a href="https://github.com/nachograyeb/flash-loan-spike">GitHub repo</a>.</p><h4>Flash Loan and Flash Loan Receiver smart contracts</h4><p>The first thing I did was understand the mechanics associated with taking and reimbursing a flash loan and focus on this alone. If you remember from our introduction to flash loans, our smart contract needs to interact with another smart contract that provides the flash loan. The latter is the one that provides the funds and makes sure the loan is paid back at the end of the transaction.</p><p>But how does it do that? How does our smart contract request the flash loan in the first place? Well, I’ll show you a very basic pair of smart contracts that puts this interaction to the test. I started by following <a href="https://www.youtube.com/watch?v=eoQJ6nFZOcs&amp;t=7988s">this tutorial</a> to get the core concept and see it in action, and then I used that as the foundation for the complete flash loan arbitrage smart contract.</p><p>The diagram below shows the basic idea of how the smart contracts will interact. The FlashLoan smart contract is the flash loan provider, while FlashLoanReceiver is the one that will receive and operate with the flash loan (i.e., the one in which we would take the flash loan and do the arbitrage trading, or whatever we want to do with the money before paying it back).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*SAsxCmULaZ4Plw9zhQPSYw.png" /></figure><p>So, as the diagram shows, FlashLoanReceiver has two main functions: executeFlashLoan() and receiveTokens(). The first one kick starts the process, while the second one executes the logic to operate with the received funds and reimburse the loan. The FlashLoan contract, on the other hand, has a function called flashLoan(), which receives the amount of tokens to borrow, sends the funds to the receiver and checks that the full amount has been reimbursed before the end of the transaction.</p><p>An important piece of this puzzle is the IReceiver interface, which contains a receiveTokens() function signature. This interface is how the FlashLoan smart contract communicates with the receiver. If you think about it, from the receiver’s perspective, you know the exact contract that you will be calling to request a flash loan. It’ll be the liquidity protocol, lending pool or whatever provider you chose. Now, from the provider’s perspective, they have no idea who will be requesting their services, so they establish an interface that users must implement in order to do so. So, if you want to request a flash loan from this provider, your receiver smart contract will have to implement the receiveTokens() function. This way, using <em>msg.sender</em>, the address of the function’s caller, the flashLoan() function from the FlashLoan contract can call the receiveTokens() function from the FlashLoanReceiver contract like so:</p><pre>IReceiver(msg.sender).receiveTokens(...args);</pre><p>So, to sum up:</p><ol><li>executeFlashLoan() calls flashLoan(), sending amount to borrow as argument</li><li>flashLoan() transfers requested amount of tokens to receiver (msg.sender)</li><li>flashLoan() calls receiveTokens() through IReceiver(msg.sender)</li><li>receiveTokens() operates with flash loan</li><li>receiveTokens() transfers flash loan amount back to provider</li><li>flashLoan() verifies the flash loan has been reimbursed</li></ol><p>Now, let’s see some code!</p><p>You can find the FlashLoan smart contract below:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/utils/math/SafeMath.sol&quot;;<br>import &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;<br>import &quot;./Token.sol&quot;;<br><br>interface IReceiver {<br>  function receiveTokens(address _tokenAddress, uint256 _amount) external;<br>}<br><br>contract FlashLoan is ReentrancyGuard {<br>  using SafeMath for uint256;<br><br>  Token public token;<br>  uint256 poolBalance;<br><br>  constructor(address _tokenAddress) {<br>    token = Token(_tokenAddress);<br>  }<br><br>  function depositTokens(uint256 _amount) external nonReentrant {<br>    require(_amount &gt; 0, &quot;Must deposit at least one token&quot;);<br>    token.transferFrom(msg.sender, address(this), _amount);<br>    poolBalance = poolBalance.add(_amount);<br>  }<br><br>  function flashLoan(uint256 _borrowAmount) external nonReentrant {<br>    require(_borrowAmount &gt; 0, &quot;Must borrow at least one token&quot;);<br><br>    uint256 balanceBefore = token.balanceOf(address(this));<br>    require(_borrowAmount &lt;= balanceBefore, &quot;Not enough tokens in pool&quot;);<br><br>    assert(poolBalance == balanceBefore);<br><br>    token.transfer(msg.sender, _borrowAmount);<br><br>    IReceiver(msg.sender).receiveTokens(address(token), _borrowAmount);<br><br>    uint256 balanceAfter = token.balanceOf(address(this));<br>    require(balanceAfter &gt;= balanceBefore, &quot;Flash loan was not paid back&quot;);<br>  }<br>}</pre><p>As you can see, for simplicity, we’re working with a single token to lend. Its contract address is sent via constructor. The Token contract is just an ERC-20 token implementation.</p><p>We have the main flashLoan() function, which receives the amount to borrow and executes the logic I mentioned above: it transfers the tokens to the caller (<em>msg.sender</em><strong><em>) </em></strong>and calls its receiveTokens function (through the IReceiver interface) and checks that the flash loan has been reimbursed (with a very basic balanceAfter ≥ balanceBefore assertion, which works fine for this example).</p><p>You may have noticed that there are other checks aside from this main logic. First, it verifies that the borrow amount is greater than 0, and then, that it’s greater or equal to the available token balance that the contract holds. It also checks that the calculated balance before the transfer matches an internal state variable poolBalance, for consistency.</p><p>Aside from the main flashLoan() function, there’s an additional function, depositTokens(), to provide the contract with funds to test it out.</p><p>SafeMath and ReentrancyGuard were added as rough security measures, to avoid over/underflows and reentrancy attacks, respectively, but we’ll leave that for another time.</p><p>Now, the FlashLoanReceiver smart contract:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;./FlashLoan.sol&quot;;<br><br>contract FlashLoanReceiver is Ownable {<br>  FlashLoan private _flashLoanPool;<br>  address private _owner;<br>  uint256 private _balanceBeforeFlashLoan;<br><br>  event LoanReceived(address _token, uint256 _amount);<br><br>  constructor(address _poolAddress) {<br>    _flashLoanPool = FlashLoan(_poolAddress);<br>    _owner = msg.sender;<br>  }<br><br>  function executeFlashLoan(uint _amount) external onlyOwner {<br>    _balanceBeforeFlashLoan = Token(address(_flashLoanPool.token())).balanceOf(address(this));<br>    _flashLoanPool.flashLoan(_amount);<br>  }<br><br>  function receiveTokens(address _tokenAddress, uint256 _amount) external {<br>    require(msg.sender == address(_flashLoanPool), &quot;Sender must be pool&quot;);<br>    require(Token(_tokenAddress).balanceOf(address(this)) == _balanceBeforeFlashLoan + _amount, &quot;failed to get loan&quot;);<br><br>    emit LoanReceived(_tokenAddress, _amount);<br><br>    // Do stuff with the loan<br><br>    require(Token(_tokenAddress).transfer(msg.sender, _amount), &quot;Flash loan reimbursement transfer failed&quot;);<br>  }<br>}</pre><p>The receiver’s constructor takes the pool address as input argument. This is the flash loan provider’s contract (FlashLoan.sol) address, which is stored as a state variable for use in the receiveTokens() function.</p><p>The receiveTokens() function is the callback function that the FlashLoan contract calls when transferring the tokens. In this case, the function’s contents are very basic: it checks that the caller is actually the flash loan pool (the provider) that it received through the contract’s constructor, and that the token balance is the balance before the flash loan plus the requested amount. Then, it emits an event to indicate that the loan has been received and it returns it (reverting the transaction if the operation is unsuccessful).</p><p>The spot with the “Do stuff with the loan” comment is where the arbitrage logic will be placed. For now, it’s just a generic placeholder for whatever you might want to do with the flash loan before returning it to the provider.</p><p>The executeFlashLoan() function essentially just calls the FlashLoan contract’s flashLoan() function to kick start the process, requesting a specific amount of tokens.</p><p>With this basic pair of contracts, you now hopefully get the gist of it. At least for me, coding them and testing them out helped me engrain the concept in my head and ultimately use it as the foundation for building the main example application.</p><p>Below, you can find some basic tests using chai and hardhat. The latter is used to interact with our contracts, setting up a controlled blockchain environment to run the tests we need.</p><p>The first test just verifies that the initial setup worked as expected, ensuring that the deployer successfully sent token funds (in this case, 1 million units of an ERC-20 token called Nacho Coin) to the FlashLoan contract. The second test verifies that the receiver smart contract borrowed and returned the funds (if the transaction didn’t revert and the LoanReceived event was emitted, then the funds were received and returned by the end of the transaction).</p><pre>const { expect } = require(&quot;chai&quot;);<br>const { ethers } = require(&quot;hardhat&quot;);<br><br>const tokens = (n) =&gt; {<br>  return ethers.parseUnits(n.toString(), &#39;ether&#39;);<br>}<br><br>describe(&#39;FlashLoan&#39;, () =&gt; {<br>  let token, flashLoan, flashLoanReceiver;<br><br>  before(async() =&gt; {<br>    [deployer] = await ethers.getSigners();<br><br>    const FlashLoan = await ethers.getContractFactory(&#39;FlashLoan&#39;);<br>    const FlashLoanReceiver = await ethers.getContractFactory(&#39;FlashLoanReceiver&#39;);<br>    const Token = await ethers.getContractFactory(&#39;Token&#39;);<br><br>    token = await Token.deploy(&#39;Nacho Coin&#39;, &#39;NC&#39;, 1000000);<br>    await token.waitForDeployment();<br><br>    flashLoan = await FlashLoan.deploy(await token.getAddress());<br>    await flashLoan.waitForDeployment();<br><br>    let transaction = await token.connect(deployer).approve(await flashLoan.getAddress(), tokens(1000000));<br>    await transaction.wait();<br><br>    transaction = await flashLoan.connect(deployer).depositTokens(tokens(1000000));<br>    await transaction.wait();<br><br>    flashLoanReceiver = await FlashLoanReceiver.deploy(await flashLoan.getAddress());<br>  });<br><br>  describe(&#39;Deployment&#39;, () =&gt; {<br>    it(&#39;should send tokens to the flash loan pool contract&#39;, async () =&gt; {<br>      expect(await token.balanceOf(await flashLoan.getAddress())).to.equal(tokens(1000000));<br>      expect(await token.balanceOf(await deployer.getAddress())).to.equal(0);<br>    });<br>  });<br><br>  describe(&#39;Borrowing funds&#39;, () =&gt; {<br>    it(&#39;should borrow funds from the pool&#39;, async () =&gt; {<br>      let amount = tokens(100);<br>      let transaction = await flashLoanReceiver.connect(deployer).executeFlashLoan(amount);<br>      await transaction.wait();<br><br>      await expect(transaction).to.emit(flashLoanReceiver, &#39;LoanReceived&#39;).withArgs(await token.getAddress(), amount);<br>    });<br>  });<br>});</pre><h4>Receiving a flash loan from Balancer</h4><p>What I did once I got the picture was to pick an actual platform and build a smart contract that could request and return a real flash loan. I picked Balancer V2 for its simplicity of integration and zero fee (at the time of writing, see <a href="https://docs-v2.balancer.fi/concepts/governance/protocol-fees.html#flash-loan-fees">here</a>).</p><p>The core of Balancer V2 is called the Vault, which is a smart contract that holds and manages all tokens in each of the available pools. The flash loan feature is available through this smart contract.</p><p>Balancer’s documentation provides a <a href="https://docs-v2.balancer.fi/guides/arbitrageurs/flash-loans.html#example-code">simple code snippet</a> that pretty much explains how the receiver should be built.</p><p>Remember that in the previous section we needed an interface for the provider to communicate with the receiver? Well, in this case, this interface is called IFlashLoanRecipient and, in order for a contract to conform to it, it must implement a function called receiveFlashLoan(), with a specific set of arguments. One key difference with the previous core example is that Balancer allows requesting multiple flash loans for different tokens in a single transaction.</p><p>To understand the arguments that our receiveFlashLoan() function must have, we need to go back to how we’re supposed to start the flash loan process with Balancer. We need to call their flashLoan() function, declared in the IVault interface, which expects this set of arguments:</p><ul><li>recipient: an instance of IFlashLoanRecipient, in this case, our own contract</li><li>tokens: an array of ERC-20 tokens, one for each flash loan</li><li>amounts: the flash loan amounts for each of the tokens, ordered to match the tokens array</li><li>userData: a bytes argument that contains the necessary data to operate with the flash loan (in the arbitrage case, it will be stuff like the DEXs in which we will perform the swaps and tokens that will be involved)</li></ul><p>Then, the mechanics from the provider’s perspective will be similar to our previous example, only it will be done in a for loop for each of the requested flash loans. Within the same flashLoan() function, the recipient’s (our contract) receiveFlashLoan() function will be called through the IFlashLoanRecipient instance that we passed as an argument. The list of arguments that receiveFlashLoan() must have in order to conform to the IFlashLoanRecipient interface are:</p><ul><li>tokens: the array with the ERC-20 tokens for each flash loan</li><li>amounts: the flash loan amounts for each of the tokens</li><li>feeAmounts: the fees that will be charged when each flash loan is reimbursed (currently set to zero, but this could change tomorrow)</li><li>userData: the same userData that was passed by the recipient to the flashLoan() function, intact.</li></ul><p>So, once the recipient has received the flash loan(s), it decodes userData to operate with the funds and repays it(them) adding the fee.</p><p>So the FlashLoanRecipient contract looks something like this:</p><pre>contract FlashLoanRecipient is IFlashLoanRecipient, Ownable {<br>  using ArrayUtils for address[];<br>  using ArrayUtils for uint24[];<br>  using ArrayUtils for uint256[];<br><br>  address private _vaultAddress;<br>  event LoanReceived(address _token, uint256 _amount);<br>  uint256[] private _balancesBeforeFlashLoan;<br><br>  struct ArbitrageParams {<br>    // Leaving a placeholder for now<br>  }<br><br>  constructor(address _address) {<br>    _vaultAddress = _address;<br>  }<br><br>  function makeFlashLoan(<br>      IERC20[] memory _tokens,<br>      uint256[] memory _amounts,<br>      bytes memory _userData<br>  ) external onlyOwner {<br>    ArrayUtils._resetArray(_balancesBeforeFlashLoan, _tokens.length);<br>    for (uint i = 0; i &lt; _tokens.length; i++) {<br>      _balancesBeforeFlashLoan[i] = _tokens[i].balanceOf(address(this));<br>    }<br><br>    IVault(_vaultAddress).flashLoan(this, _tokens, _amounts, _userData);<br>  }<br><br>  function receiveFlashLoan(<br>      IERC20[] memory _tokens,<br>      uint256[] memory _amounts,<br>      uint256[] memory _feeAmounts,<br>      bytes memory _userData<br>  ) external override {<br>      require(msg.sender == _vaultAddress, &quot;Only vault can call&quot;);<br><br>      ArbitrageParams[] memory arbitrageParams = new ArbitrageParams[](0);<br><br>      if (_userData.length &gt; 0) {<br>        arbitrageParams = _decodeArbitrageParams(_userData);<br>      }<br><br>      for (uint i = 0; i &lt; _tokens.length; i++) {<br>        require(<br>          _tokens[i].balanceOf(address(this)) == _balancesBeforeFlashLoan[i] + _amounts[i],<br>          &quot;Failed to receive flash loan&quot;<br>        );<br><br>        emit LoanReceived(address(_tokens[i]), _amounts[i]);<br><br>        // Do stuff with the loan (using decoded _userData)<br><br>        require(<br>          _tokens[i].transfer(msg.sender, _amounts[i] + _feeAmounts[i]), <br>          &quot;Not enough funds to repay flash loan&quot;<br>          );<br>      }<br>  }</pre><p>You can see a struct called ArbitrageParams, which for now is just a placeholder. The idea is that we need to decode _userData into an array of ArbitrageParams, one for each flash loan, and that will contain all the data to “do stuff with the loan” (a.k.a., execute the arbitrage trade). The _decodeArbitrageParams function is a custom function, which I haven’t shared yet but I’ll show you in a minute, that takes care of this business.</p><p>Also, the balance checks to ensure the flash loan has been received become a bit more complex purely because of the fact that it’s all turned into arrays, instead of operating with just one flash loan at a time. I also included an ArrayUtils file to handle some array operations.</p><p>Now, if you wanted to replicate the tests from the previous section for this new contract, you would need to either use the actual Balancer Vault contract or create a mock version. The first option would require a special environment to test with real data, so starting with a mocked version would make sense as a more gradual approach. Hey, at least that’s what I did and it enriched the learning experience, since in a way I was sort of implementing my own version of the Balancer Vault.</p><p>The mock Vault ends up being something like this:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@balancer-labs/v2-interfaces/contracts/vault/IFlashLoanRecipient.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/math/SafeMath.sol&quot;;<br>import &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>interface IMinimalVault {<br>  function flashLoan(<br>      IFlashLoanRecipient _recipient,<br>      IERC20[] memory _tokens,<br>      uint256[] memory _amounts,<br>      bytes memory _userData<br>    ) external;<br>}<br><br>contract MockVault is IMinimalVault, ReentrancyGuard, Ownable {<br>  mapping (address =&gt; uint256) private _poolBalances;<br><br>  function depositTokens(IERC20 _token, uint256 _amount) external nonReentrant {<br>    require(_amount &gt; 0, &quot;Must deposit at least one token&quot;);<br>    _token.transferFrom(msg.sender, address(this), _amount);<br>    _poolBalances[address(_token)] += _amount;<br>  }<br><br>  function flashLoan(<br>    IFlashLoanRecipient _recipient,<br>    IERC20[] memory _tokens,<br>    uint256[] memory _amounts,<br>    bytes memory _userData<br>  ) external nonReentrant {<br>    uint256 tokensLength = _tokens.length;<br>    uint256[] memory balancesBefore = new uint256[](tokensLength);<br>    uint256[] memory feeAmounts = new uint256[](tokensLength);<br><br>    for (uint i = 0; i &lt; tokensLength; i++) {<br>      require(_amounts[i] &gt; 0, &quot;Must borrow at least one token&quot;);<br>      feeAmounts[i] = 0;<br><br>      balancesBefore[i] = _tokens[i].balanceOf(address(this));<br>      require(_amounts[i] &lt;= balancesBefore[i], &quot;Not enough tokens in pool&quot;);<br><br>      assert(_poolBalances[address(_tokens[i])] == balancesBefore[i]);<br>      _tokens[i].transfer(msg.sender, _amounts[i]);<br>    }<br><br>    _recipient.receiveFlashLoan(_tokens, _amounts, feeAmounts, _userData);<br><br>    for (uint i = 0; i &lt; tokensLength; i++) {<br>      uint256 balanceAfter = _tokens[i].balanceOf(address(this));<br>      require(balanceAfter &gt;= balancesBefore[i], &quot;Flash loan was not paid back&quot;);<br>    }<br>  }<br>}</pre><p>Here, I defined an interface called IMinimalVault, just to make it clear that I only need to implement the one flashLoan() function, and not the entire IVault interface from Balancer.</p><h4>Arbitrage implementation</h4><p>Now, let’s jump to the juicy part: the actual arbitrage trade! After all, this is what will give us profit, otherwise we’re just borrowing money to return it the next second.</p><p>We need to add code to our smart contract to integrate with a source DEX and a target DEX, so that we can buy cheap on the former and sell a bit higher on the latter.</p><p>There are all kinds of DEXs out there, but an approach that will make our lives simpler is picking those that follow the <a href="https://app.uniswap.org/">Uniswap</a> standard. Uniswap is one of the most prominent DeFi protocols out there and a lot of the available DEXs are based off of it.</p><p>In particular, the swap operations are done via a contract called the <a href="https://docs.uniswap.org/contracts/v3/reference/periphery/SwapRouter">SwapRouter</a>, which implements the ISwapRouter interface. Other DEXs, such as <a href="https://quickswap.exchange/#/">QuickSwap</a> and <a href="https://pancakeswap.finance/">PancakeSwap</a>, also have their own implementations of the same interface. What this means for us is that we can build something generic, where we have a source DEX and a target DEX that are instances of ISwapRouter. Then, we can receive the actual contract addresses as input and execute the swaps, without our contract actually knowing which specific DEXs we’re using. In this implementation, I used the <a href="https://blog.uniswap.org/uniswap-v3">Uniswap V3</a> protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NHkTTVZNilYANQiK.png" /></figure><p>These DEX addresses are part of what will be included in the ArbitrageParams struct and sent in its ABI-encoded form as _userData.</p><pre>struct ArbitrageParams {<br>    address sourceRouter;<br>    address targetRouter;<br>    address[] sourceTokens;<br>    address[] targetTokens;<br>    uint24[] sourceFees;<br>    uint24[] targetFees;<br>    uint256 amountIn;<br>  }</pre><p>As I mentioned, sourceRouter and targetRouter are the addresses for the source and target DEX contracts, both implementing ISwapRouter, respectively.</p><p>Now, sourceTokens and targetTokens are arrays that contain the tokens that will be traded, in the order in which we intend to do so. This is sometimes referred to as the <em>path</em>, and it can have multiple steps or <em>hops</em>. For instance, let’s say we want to buy WETH with USDC and then swap the WETH we obtained for DAI, then the array will be:</p><p>[USDC, WETH, DAI]</p><p>The arrays sourceFees and targetFees represent the swap fees charged by the DEX between each token pair. So let’s say that to swap USDC for WETH there is a 0.01 fee, while the fee to swap WETH for DAI is 0.02, then the fees array will be:</p><p>[0.01, 0.02]</p><p>Finally, amountIn is the amount of input tokens to start the whole process, so it’s the amount of the first token in the source path, which must equal the amount of tokens we’re borrowing (the flash loan amount).</p><p>Using the Uniswap V3 documentation for implementing a swap, I chose <a href="https://docs.uniswap.org/contracts/v3/guides/swaps/multihop-swaps">multi-hop swaps</a>, so that the contract could handle more complex arbitrage paths, instead of just swapping one token for another.</p><p>The key function to perform a swap is exactInput() and its input arguments are:</p><ul><li>path: a sequence of (tokenAddress - fee - tokenAddress), that indicates which tokens will be part of the swap path and the fees between each token pair. A correctly built path will have N token addresses and N-1 fees.</li><li>recipient: the destination address, in our case, our smart contract.</li><li>deadline: the unix time after which a transaction will be reverted, to protect against long delays and the increased chance of large price swings therein.</li><li>amountIn: the amount of the inbound asset, the first token in the path.</li><li>amountOutMin: the minimum amount of the outbound asset, less than which will cause the transaction to revert. As suggested in the documentation, for simplicity we will set it to 0, but we can enhance our solution by calculating this value using a quoter or an on-chain price oracle to get an expected price.</li></ul><p>You can find more info about this <a href="https://docs.uniswap.org/contracts/v3/guides/swaps/multihop-swaps#input-parameters">here</a>.</p><p>So now, let’s implement a function to execute the arbitrage:</p><pre>function _executeArbitrage(IERC20 _token, ArbitrageParams memory _arbitrageParams) internal {<br>    require(<br>      _arbitrageParams.sourceTokens[0] == address(_token),<br>      &quot;First token in source path must be equal to initial token to trade&quot;<br>    );<br><br>    address sourceOutputToken = _arbitrageParams.sourceTokens[_arbitrageParams.sourceTokens.length -1];<br>    address targetOutputToken = _arbitrageParams.targetTokens[_arbitrageParams.targetTokens.length -1];<br><br>    require(<br>      sourceOutputToken == _arbitrageParams.targetTokens[0],<br>      &quot;Last token in source path must equal first token in target path&quot;<br>    );<br>    require(<br>      targetOutputToken == _arbitrageParams.sourceTokens[0],<br>      &quot;Last token in target path must equal first token in source path&quot;<br>    );<br><br>    _token.approve(_arbitrageParams.sourceRouter, _arbitrageParams.amountIn);<br><br>    ISwapRouter.ExactInputParams memory sourceSwapParams = ISwapRouter.ExactInputParams({<br>      path: encodePath(_arbitrageParams.sourceTokens, _arbitrageParams.sourceFees),<br>      recipient: address(this),<br>      deadline: block.timestamp + 300,<br>      amountIn:_arbitrageParams.amountIn,<br>      amountOutMinimum: 0<br>    });<br><br>    uint256 midAmount = ISwapRouter(_arbitrageParams.sourceRouter).exactInput(sourceSwapParams);<br><br>    require(midAmount &gt; 0, &quot;Source swap failed&quot;);<br><br>    IERC20(sourceOutputToken).approve(_arbitrageParams.targetRouter, midAmount);<br><br>    ISwapRouter.ExactInputParams memory targetSwapParams = ISwapRouter.ExactInputParams({<br>      path: encodePath(_arbitrageParams.targetTokens, _arbitrageParams.targetFees),<br>      recipient: address(this),<br>      deadline: block.timestamp + 300,<br>      amountIn: midAmount,<br>      amountOutMinimum: 0<br>    });<br><br>    uint256 amountOut = ISwapRouter(_arbitrageParams.targetRouter).exactInput(targetSwapParams);<br><br>    require(amountOut &gt; _arbitrageParams.amountIn, &quot;Arbitrage not profitable&quot;);<br>    emit ArbitrageExecuted(<br>      address(_token),<br>      _arbitrageParams.amountIn,<br>      amountOut - _arbitrageParams.amountIn<br>    );<br>  }</pre><p>There are some requires here that might not be so obvious, so let’s break them down:</p><pre>require(<br>      _arbitrageParams.sourceTokens[0] == address(_token),<br>      &quot;First token in source path must be equal to initial token to trade&quot;<br>    );</pre><p>This is what I mentioned above: the first token of the source path, must be the one that starts the whole process, i.e., the one we’re requesting as a flash loan.</p><pre>address sourceOutputToken = _arbitrageParams.sourceTokens[_arbitrageParams.sourceTokens.length -1];<br>address targetOutputToken = _arbitrageParams.targetTokens[_arbitrageParams.targetTokens.length -1];<br><br>require(<br>  sourceOutputToken == _arbitrageParams.targetTokens[0],<br>  &quot;Last token in source path must equal first token in target path&quot;<br>);<br>require(<br>  targetOutputToken == _arbitrageParams.sourceTokens[0],<br>  &quot;Last token in target path must equal first token in source path&quot;<br>);</pre><p>Now, in this portion, we’re making sure that the source and target paths tie together. So, the last token in the source path must equal the first one in the target path, so that you can start a swap in the target DEX with the tokens you obtained from the source DEX. The other check makes sure that the final token that results from the target DEX swap path matches the input token, so that we can reimburse the flash loan at the end of the transaction and keep the profit in the same currency.</p><p>Another part of the code that is worth noting is that we must approve token transfers done by the DEX on our behalf, in order to initiate a swap path. That’s why we have:</p><pre>_token.approve(_arbitrageParams.sourceRouter, _arbitrageParams.amountIn);</pre><p>and</p><pre>IERC20(sourceOutputToken).approve(_arbitrageParams.targetRouter, midAmount);</pre><p>before each swap.</p><p>To construct the path parameter for the swap, as described in Uniswap V3’s documentation, we need to provide a sequence of (tokenAddress - fee - tokenAddress). For example, if the swap path is:</p><p>USDC → WETH → DAI</p><p>the path sequence will be:</p><p>(USDCAddress, fee[USDC-WETH], WETHAddress, fee[WETH-DAI], DAI).</p><p>This sequence has to be ABI-encoded. I did this with the code below:</p><pre>function encodePath(address[] memory _tokens, uint24[] memory _fees) internal pure returns (bytes memory) {<br>    require(_tokens.length &gt;= 2, &quot;Path too short&quot;);<br>    require(_tokens.length == _fees.length + 1, &quot;Length mismatch&quot;);<br><br>    bytes memory path = abi.encodePacked(_tokens[0]);<br><br>    for (uint i = 0; i &lt; _fees.length; i++) {<br>      path = abi.encodePacked(<br>        path,<br>        _fees[i],<br>        _tokens[i + 1]<br>      );<br>    }<br><br>    return path;<br>  }</pre><p>So, the complete receiveFlashLoan() function, with the arbitrage part included, looks something like this:</p><pre>function receiveFlashLoan(<br>      IERC20[] memory _tokens,<br>      uint256[] memory _amounts,<br>      uint256[] memory _feeAmounts,<br>      bytes memory _userData<br>  ) external override {<br>      require(msg.sender == _vaultAddress, &quot;Only vault can call&quot;);<br><br>      ArbitrageParams[] memory arbitrageParams = new ArbitrageParams[](0);<br>      bool canExecuteArbitrage = false;<br><br>      if (_userData.length &gt; 0) {<br>        arbitrageParams = _decodeArbitrageParams(_userData);<br>        canExecuteArbitrage = arbitrageParams.length == _tokens.length;<br>      }<br><br>      for (uint i = 0; i &lt; _tokens.length; i++) {<br>        require(<br>          _tokens[i].balanceOf(address(this)) == _balancesBeforeFlashLoan[i] + _amounts[i],<br>          &quot;Failed to receive flash loan&quot;<br>        );<br><br>        emit LoanReceived(address(_tokens[i]), _amounts[i]);<br><br>        if (canExecuteArbitrage) {<br>          _executeArbitrage(_tokens[i], arbitrageParams[i]);<br>        }<br><br>        require(<br>          _tokens[i].transfer(msg.sender, _amounts[i] + _feeAmounts[i]), <br>          &quot;Not enough funds to repay flash loan&quot;<br>          );<br>      }<br>  }</pre><p>To integrate this to our tests, we now need to mock another dependency: the SwapRouter.</p><p>I’m not gonna go into too much detail for this one, but what I’m basically doing is keeping a mapping with exchange rates for different token pairs and then, for any path I receive, I transfer the input token from the caller’s address to this contract, calculate the compound exchange rate of the full path and transfer the final output token back to the caller. I’m assuming tokens use 18 decimals, which is pretty common, just for the purposes of these tests.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/IERC20.sol&quot;;<br><br>interface IMinimalRouter {<br>  struct ExactInputParams {<br>    bytes path;<br>    address recipient;<br>    uint256 deadline;<br>    uint256 amountIn;<br>    uint256 amountOutMinimum;<br>  }<br><br>  function exactInput(ExactInputParams calldata _params) external payable returns (uint256 amountOut);<br>}<br>contract MockSwapRouter is IMinimalRouter {<br><br>  mapping(address =&gt; mapping(address =&gt; uint256)) public exchangeRates;<br><br>  function setExchangeRate(address inputToken, address outputToken, uint256 rate) external {<br>        exchangeRates[inputToken][outputToken] = rate;<br>  }<br><br>  function exactInput(ExactInputParams calldata _params) external payable returns (uint256) {<br>    require(_params.amountIn &gt; 0, &quot;Not enough funds to initiate swap&quot;);<br><br>    (address[] memory tokens,) = decodePath(_params.path);<br>    <br>    address firstToken = tokens[0];<br>    address finalToken = tokens[tokens.length - 1];<br><br>    uint256 amountOut = _params.amountIn;<br><br>    for (uint i = 0; i &lt; tokens.length - 1; i++) {<br>      address inputToken = tokens[i];<br>      address outputToken = tokens[i + 1];<br><br>      uint256 rate = exchangeRates[inputToken][outputToken];<br>      if (rate == 0) {<br>        rate = 1e18;<br>      }<br><br>      amountOut = amountOut*rate/1e18;<br>    }<br><br>    IERC20(firstToken).transferFrom(msg.sender, address(this), _params.amountIn);<br><br>    if (amountOut &gt; 0) {<br>      IERC20(finalToken).transfer(_params.recipient, amountOut);<br>    }<br><br>    return amountOut;<br>  }<br><br>  function decodePath(bytes memory path) internal pure returns (address[] memory tokens, uint24[] memory fees) {<br>    require(path.length &gt;= 20, &quot;Invalid path: too short&quot;);<br>    <br>    // Calculate how many tokens and fees we have<br>    // We have tokens at positions 0, 24, 48, etc. (every 24 bytes)<br>    // Each token is 20 bytes, each fee is 3 bytes, followed by a token again<br>    uint256 numFees = (path.length - 20) / 23; // (path.length - 1 address) / (1 fee + 1 address)<br>    uint256 numTokens = numFees + 1;<br>    <br>    tokens = new address[](numTokens);<br>    fees = new uint24[](numFees);<br>    <br>    // Extract the first token (always at the beginning)<br>    tokens[0] = toAddress(path, 0);<br>    <br>    // Extract each fee and subsequent token<br>    uint256 offset = 20; // Start after the first token<br>    for (uint256 i = 0; i &lt; numFees; i++) {<br>        fees[i] = toUint24(path, offset);<br>        offset += 3; // Move past the fee (3 bytes)<br>        tokens[i + 1] = toAddress(path, offset);<br>        offset += 20; // Move past the token (20 bytes)<br>    }<br>    <br>    return (tokens, fees);<br>}<br><br>  // Helper function to extract an address from bytes at a specific offset<br>  function toAddress(bytes memory data, uint256 offset) internal pure returns (address result) {<br>    require(offset + 20 &lt;= data.length, &quot;toAddress: Out of bounds&quot;);<br>    bytes20 addressBytes;<br>    assembly {<br>        addressBytes := mload(add(add(data, 0x20), offset))<br>    }<br>    return address(addressBytes);<br>  }<br><br>  // Helper function to extract a uint24 from bytes at a specific offset<br>  function toUint24(bytes memory data, uint256 offset) internal pure returns (uint24 result) {<br>    require(offset + 3 &lt;= data.length, &quot;toUint24: Out of bounds&quot;);<br>    <br>    result = 0;<br>    for (uint i = 0; i &lt; 3; i++) {<br>        result = result + uint24(uint8(data[offset + i])) * uint24(uint256(2)**(8 * (2 - i)));<br>    }<br>    return result;<br>  }<br>}</pre><h4>Tests with mocked dependencies</h4><p>Now, going back to the tests, we can create a setup with the mocked versions of the Vault and the SwapRouter, fund the Vault with a bunch of ERC-20 tokens and test the flash loan logic, the arbitrage logic and the end-to-end flash loan arbitrage case.</p><p>The setup below gets the first default Hardhat network account (owner) and deploys the involved contracts: MockVault, MockSwapRouter, FlashLoanRecipient and Token.</p><p>Then, it deploys three different (mock) ERC-20 tokens: DAI, Wrapped ETH and Wrapped LIBRA (healthy dose of dark humor…), and funds the MockVault contract with only DAI. It then transfers fixed quantities of all three tokens to the MockSwapRouter contract.</p><pre>beforeEach(async () =&gt; {<br>  [owner] = await ethers.getSigners();<br>  ownerAddress = await owner.getAddress();<br><br>  const MockVault = await ethers.getContractFactory(&quot;MockVault&quot;);<br>  const MockRouter = await ethers.getContractFactory(&quot;MockSwapRouter&quot;);<br>  const FlashLoanRecipient = await ethers.getContractFactory(&quot;FlashLoanRecipient&quot;);<br>  const Token = await ethers.getContractFactory(&#39;Token&#39;);<br><br>  mockVault = await MockVault.deploy();<br>  await mockVault.waitForDeployment();<br>  mockVaultAddress = await mockVault.getAddress();<br><br>  mockRouter = await MockRouter.deploy();<br>  await mockRouter.waitForDeployment();<br>  mockRouterAddress = await mockRouter.getAddress();<br><br>  flashLoanRecipient = await FlashLoanRecipient.deploy(mockVaultAddress);<br>  flashLoanRecipientAddress = await flashLoanRecipient.getAddress();<br>  await flashLoanRecipient.waitForDeployment();<br><br>  dai = await Token.deploy(&#39;Mock DAI&#39;, &#39;DAI&#39;, 2000000);<br>  daiAddress = await dai.getAddress();<br>  await dai.waitForDeployment();<br><br>  weth = await Token.deploy(&#39;Mock WETH&#39;, &#39;WETH&#39;, 2000000);<br>  wethAddress = await weth.getAddress();<br>  await weth.waitForDeployment();<br><br>  wLibra = await Token.deploy(&#39;Mock shtcn&#39;, &#39;WLIBRA&#39;, 2000000);<br>  wLibraAddress = await wLibra.getAddress();<br>  await wLibra.waitForDeployment();<br><br>  transaction = await dai.connect(owner).approve(mockVaultAddress, tokens(1000000));<br>  await transaction.wait();<br><br>  transaction = await mockVault.connect(owner).depositTokens(dai, tokens(1000000));<br>  await transaction.wait();<br><br>  transaction = await dai.connect(owner).transfer(mockRouterAddress, tokens(1000000));<br>  transaction = await weth.connect(owner).transfer(mockRouterAddress, tokens(1000000));<br>  transaction = await wLibra.connect(owner).transfer(mockRouterAddress, tokens(1000000));<br>});</pre><p>The first set of tests focuses on the flash loan logic. It tests successful flash loan cases, one with a single token (DAI) and one with two tokens (DAI and WETH), and an unsuccessful case where a flash loan is requested for a token that is not present in the Vault (WETH, in this case).</p><pre>describe(&#39;Borrowing funds&#39;, () =&gt; {<br>  it(&#39;should borrow mock dai from the pool and then return it&#39;, async () =&gt; {<br>    let amounts = [tokens(100)];<br>    const userData = &quot;0x&quot;;<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData)<br>    ).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(daiAddress, amounts[0]);<br>    expect(await dai.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>  });<br><br>  it(&#39;should revert because the vault contract has no weth to lend&#39;, async () =&gt; {<br>    let amounts = [tokens(100), tokens(150)];<br>    const userData = &quot;0x&quot;;<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([dai, weth], amounts, userData)<br>    ).to.be.revertedWith(&#39;Not enough tokens in pool&#39;);<br>  });<br><br>  it(&#39;should borrow mock dai and weth from the pool and then return both, after having deposited weth&#39;, async () =&gt; {<br>    transaction = await weth.connect(owner).approve(mockVaultAddress, tokens(1000000));<br>    await transaction.wait();<br><br>    transaction = await mockVault.connect(owner).depositTokens(weth, tokens(1000000));<br>    await transaction.wait();<br><br>    let amounts = [tokens(100), tokens(150)];<br>    const userData = &quot;0x&quot;;<br>    transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([dai, weth], amounts, userData);<br>    await transaction.wait();<br><br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(daiAddress, amounts[0]);<br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(wethAddress, amounts[1]);<br>    expect(await dai.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>    expect(await weth.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>  });<br>});</pre><p>The second set of tests focuses on the arbitrage logic in isolation. It tests successful cases with 2-token and 3-token paths, and different failure cases: arbitrage not profitable and zero-valued swap amounts.</p><pre>describe(&#39;Testing isolated arbitrage logic&#39;, async () =&gt; {<br>  it(&#39;should execute profitable arbitrage with 2-token path&#39;, async () =&gt; {<br>    const daiAmountInt = 10;<br>    const daiAmountIn = tokens(daiAmountInt);<br><br>    const arbitrageParams = {<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [3000],<br>      targetFees: [500],<br>      amountIn: daiAmountIn,<br>    };<br><br>    const wethBuyPriceInDai = 2000;<br>    const wethSellPriceInDai = 2200;<br><br>    await mockRouter.setExchangeRate(daiAddress, wethAddress, tokens(1/wethBuyPriceInDai));<br>    await mockRouter.setExchangeRate(wethAddress, daiAddress, tokens(wethSellPriceInDai));<br><br>    // simulate flash loan<br>    await mockVault.connect(owner).transferTokens(dai, flashLoanRecipientAddress, daiAmountIn);<br><br>    transaction = await flashLoanRecipient.connect(owner).testExecuteArbitrage(dai, arbitrageParams);<br>    await transaction.wait();<br><br>  await expect(transaction).to.emit(flashLoanRecipient, &#39;ArbitrageExecuted&#39;).withArgs(daiAddress, daiAmountIn, tokens((wethSellPriceInDai/wethBuyPriceInDai)*daiAmountInt) - daiAmountIn);<br>  });<br><br>  it(&#39;should execute profitable arbitrage with 3-token path&#39;, async () =&gt; {<br>    const daiAmountInt = 10;<br>    const daiAmountIn = tokens(daiAmountInt);<br><br>    const arbitrageParams = {<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wLibraAddress, wethAddress],<br>      targetTokens: [wethAddress, wLibraAddress, daiAddress],<br>      sourceFees: [3000, 2000],<br>      targetFees: [500, 1000],<br>      amountIn: daiAmountIn,<br>    };<br><br>    const wLibraBuyPriceInDai = 1;<br>    const wethBuyPriceInWLibra = 2000;<br>    const wethSellPriceInWLibra = 2200;<br>    const wLibraSellPriceInDai = 1.1;<br><br>    const totalExchangeRate = (wLibraSellPriceInDai*wethSellPriceInWLibra)/(wLibraBuyPriceInDai*wethBuyPriceInWLibra);<br><br>    await mockRouter.setExchangeRate(daiAddress, wLibraAddress, tokens(1/wLibraBuyPriceInDai));<br>    await mockRouter.setExchangeRate(wLibraAddress, wethAddress, tokens(1/wethBuyPriceInWLibra));<br>    await mockRouter.setExchangeRate(wethAddress, wLibraAddress, tokens(wethSellPriceInWLibra));<br>    await mockRouter.setExchangeRate(wLibraAddress, daiAddress, tokens(wLibraSellPriceInDai));<br><br>    // simulate flash loan<br>    await mockVault.connect(owner).transferTokens(dai, flashLoanRecipientAddress, daiAmountIn);<br><br>    transaction = await flashLoanRecipient.connect(owner).testExecuteArbitrage(dai, arbitrageParams);<br>    await transaction.wait();<br><br>  await expect(transaction).to.emit(flashLoanRecipient, &#39;ArbitrageExecuted&#39;).withArgs(daiAddress, daiAmountIn, tokens(daiAmountInt*totalExchangeRate) - daiAmountIn);<br>  });<br><br>  it(&#39;should revert because arbitrage is not profitable&#39;, async () =&gt; {<br>    const daiAmountInt = 10;<br>    const daiAmountIn = tokens(daiAmountInt);<br><br>    const arbitrageParams = {<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [3000],<br>      targetFees: [500],<br>      amountIn: daiAmountIn,<br>    };<br><br>    const wethBuyPriceInDai = 2000;<br>    const wethSellPriceInDai = 1900;<br><br>    await mockRouter.setExchangeRate(daiAddress, wethAddress, tokens(1/wethBuyPriceInDai));<br>    await mockRouter.setExchangeRate(wethAddress, daiAddress, tokens(wethSellPriceInDai));<br><br>    // simulate flash loan<br>    await mockVault.connect(owner).transferTokens(dai, flashLoanRecipientAddress, daiAmountIn);<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).testExecuteArbitrage(dai, arbitrageParams)<br>    ).to.be.revertedWith(&#39;Arbitrage not profitable&#39;);<br>  });<br><br>  it(&#39;should revert because mid amount is 0&#39;, async () =&gt; {<br>    const daiAmountFloat = 0.5;<br>    const daiAmountIn = tokens(daiAmountFloat);<br><br>    const arbitrageParams = {<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [3000],<br>      targetFees: [500],<br>      amountIn: daiAmountIn,<br>    };<br><br>    const wethSellPriceInDai = 1900;<br><br>    await mockRouter.setExchangeRate(daiAddress, wethAddress, 1n);<br>    await mockRouter.setExchangeRate(wethAddress, daiAddress, tokens(wethSellPriceInDai));<br><br>    // simulate flash loan<br>    await mockVault.connect(owner).transferTokens(dai, flashLoanRecipientAddress, daiAmountIn);<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).testExecuteArbitrage(dai, arbitrageParams)<br>    ).to.be.revertedWith(&#39;Source swap failed&#39;);<br>  });<br><br>  it(&#39;should revert because swap input amount is 0&#39;, async () =&gt; {<br>    const daiAmountInt = 0;<br>    const daiAmountIn = tokens(daiAmountInt);<br><br>    const arbitrageParams = {<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [3000],<br>      targetFees: [500],<br>      amountIn: daiAmountIn,<br>    };<br><br>    const wethBuyPriceInDai = 2000;<br>    const wethSellPriceInDai = 1900;<br><br>    await mockRouter.setExchangeRate(daiAddress, wethAddress, tokens(1/wethBuyPriceInDai));<br>    await mockRouter.setExchangeRate(wethAddress, daiAddress, tokens(wethSellPriceInDai));<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).testExecuteArbitrage(dai, arbitrageParams)<br>    ).to.be.revertedWith(&#39;Not enough funds to initiate swap&#39;);<br>  });<br>});</pre><p>Finally, there’s a simple end-to-end flash loan arbitrage case with two tokens: DAI and WETH.</p><pre>describe(&#39;Arbitrage with flash loan end-to-end&#39;, async () =&gt; {<br>  it(&#39;should execute profitable arbitrage with flash loan&#39;, async () =&gt; {<br>    const daiAmountInt = 10;<br>    const daiAmountIn = tokens(daiAmountInt);<br><br>    const arbitrageParams = [{<br>      sourceRouter: mockRouterAddress,<br>      targetRouter: mockRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [3000],<br>      targetFees: [500],<br>      amountIn: daiAmountIn,<br>    }];<br><br>    const userData = encodeArbitrageParams(arbitrageParams);<br>    const wethBuyPriceInDai = 2000;<br>    const wethSellPriceInDai = 2200;<br><br>    await mockRouter.setExchangeRate(daiAddress, wethAddress, tokens(1/wethBuyPriceInDai));<br>    await mockRouter.setExchangeRate(wethAddress, daiAddress, tokens(wethSellPriceInDai));<br><br>    const amounts = [daiAmountIn];<br><br>    transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData);<br>    await transaction.wait();<br><br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;ArbitrageExecuted&#39;).withArgs(daiAddress, daiAmountIn, tokens((wethSellPriceInDai/wethBuyPriceInDai)*daiAmountInt) - daiAmountIn);<br>  });<br>});</pre><h4>Testing with real-world blockchain data: Polygon fork</h4><p>Now that we have some test cases in a controlled environment with mocked dependencies, we can move on and see if we can start playing around with some real data!</p><p>There are a few things I’d been thinking about before materializing this. So, one of the challenges was the fierce competition there would be and the potentially high gas prices on Ethereum Mainnet. One of the first things that came to mind then was “Hey, but what if I chose a lower-profile chain with cheaper gas?”. And yeah, that’s one of the first things new arbitrageurs consider when starting out. I thought I should pick one that has these properties to some extent but that is popular enough to be listed in compatible DEXs and, of course, that is EVM-compatible. So I thought Polygon was a no-brainer here.</p><p>This Layer-2 solution provides a lot of the benefits of working with Ethereum, while having lower transaction fees and potentially less competition. So I thought, if I ever actually make this live, this could be a good starting point. The truth is, the challenges I mentioned in the intro are still there, but it kind of seems more manageable in a way. So, if I already had this in mind, I might as well just create my tests in a Polygon fork.</p><p>In order to do this, I added a dedicated hardhat.config file for these tests. I still wanted to keep the standard tests in my project and be able to run them independently, so I split the tests into two separate folders and created two separate hardhat.config files.</p><p>For the standard (mocked dependencies) tests:</p><pre>require(&quot;@nomicfoundation/hardhat-toolbox&quot;);<br>require(&#39;dotenv&#39;).config();<br><br>/** @type import(&#39;hardhat/config&#39;).HardhatUserConfig */<br>module.exports = {<br>  solidity: &quot;0.8.17&quot;,<br>  networks: {<br>    hardhat: {<br>      chainId: 31337,<br>    },<br>  },<br>  paths: {<br>    tests: &quot;./test/standard&quot;,<br>  }<br>};</pre><p>For the Polygon fork tests:</p><pre>require(&quot;@nomicfoundation/hardhat-toolbox&quot;);<br>require(&#39;dotenv&#39;).config();<br><br>/** @type import(&#39;hardhat/config&#39;).HardhatUserConfig */<br>module.exports = {<br>  solidity: &quot;0.8.17&quot;,<br>  networks: {<br>    hardhat: {<br>      chainId: 137,<br>      forking: {<br>        url: `https://polygon-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,<br>        blockNumber: 69325838<br>      },<br>    },<br>  },<br>  paths: {<br>    tests: &quot;./test/polygon&quot;<br>  }<br>};</pre><p>For the fork to work, you need an <a href="https://docs.polygon.technology/pos/reference/rpc-endpoints/">RPC endpoint for Polygon mainnet</a>. I used <a href="https://www.alchemy.com/">Alchemy</a> as infrastructure provider and created an API key there for this purpose. I also chose a specific blockNumber to make sure I was working with relatively recent data (this is optional, though, but I recommend it).</p><p>So, once this is done, the main setup for the tests is actually simpler: we just need the Polygon addresses for the dependencies, pick a few tokens and that’s it!</p><pre>before(async () =&gt; {<br>    if (!network.config.forking) {<br>      this.skip();<br>    }<br><br>    [owner] = await ethers.getSigners();<br>    ownerAddress = await owner.getAddress();<br><br>    const FlashLoanRecipient = await ethers.getContractFactory(&quot;FlashLoanRecipient&quot;);<br><br>    flashLoanRecipient = await FlashLoanRecipient.deploy(vaultAddress);<br>    flashLoanRecipientAddress = await flashLoanRecipient.getAddress();<br>    await flashLoanRecipient.waitForDeployment();<br><br>    dai = await ethers.getContractAt(&quot;IERC20Extended&quot;, daiAddress);<br>    weth = await ethers.getContractAt(&quot;IERC20Extended&quot;, wethAddress);<br>    uni = await ethers.getContractAt(&quot;IERC20Extended&quot;, uniAddress);<br><br>    vaultDaiBalanceBefore = await dai.balanceOf(vaultAddress);<br>    vaultWethBalanceBefore = await weth.balanceOf(vaultAddress);<br>  });</pre><p>And the contract addresses if you’re wondering…</p><pre>const daiAddress = &quot;0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063&quot;;<br>const wethAddress = &quot;0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619&quot;;<br>const uniAddress = &quot;0xb33EaAd8d922B1083446DC23f610c2567fB5180f&quot;;<br>const vaultAddress = &quot;0xBA12222222228d8Ba445958a75a0704d566BF2C8&quot;;<br>const uniswapRouterAddress = &quot;0xE592427A0AEce92De3Edee1F18E0157C05861564&quot;;<br>const quickSwapRouterAddress = &quot;0xf5b509bB0909a69B1c207E495f687a596C168E12&quot;;</pre><p>Now, this does require a bit of playing around to see what tokens and DEXs to pick, based on available balances and such. I picked Uniswap and QuickSwap as my DEXs and DAI, WETH and UNI as ERC-20 tokens to trade.</p><p>The tests for the flash loan logic are basically the same as the ones from the mock dependency environment. The main difference is that the actual Balancer Vault has its own error codes for cases in which the transactions revert.</p><pre>describe(&#39;Borrowing funds&#39;, () =&gt; {<br>  it(&#39;should borrow dai from the pool and then return it&#39;, async () =&gt; {<br>    let amounts = [tokens(100)];<br>    const userData = &quot;0x&quot;;<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData)<br>    ).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(daiAddress, amounts[0]);<br>    expect(await dai.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>  });<br><br>  it(&#39;should revert because the vault contract does not have enough weth to lend (error: BAL#528)&#39;, async () =&gt; {<br>    let amounts = [vaultWethBalanceBefore + tokens(1), tokens(100)];<br>    const userData = &quot;0x&quot;;<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([weth, dai], amounts, userData)<br>    ).to.be.revertedWith(&#39;BAL#528&#39;);<br>  });<br><br>  it(&#39;should borrow dai and weth from the pool and then return both, after having deposited weth&#39;, async () =&gt; {  <br>    let amounts = [tokens(150), tokens(100)];<br><br>    const userData = &quot;0x&quot;;<br>    transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([weth, dai], amounts, userData);<br>    await transaction.wait();<br><br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(wethAddress, amounts[0]);<br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;LoanReceived&#39;).withArgs(daiAddress, amounts[1]);<br>    expect(await dai.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>    expect(await weth.balanceOf(flashLoanRecipientAddress)).to.equal(0);<br>  });<br><br>  it(&#39;should revert with unsorted tokens error (BAL#102)&#39;, async () =&gt; {  <br>    let amounts = [tokens(100), tokens(100)];<br><br>    const userData = &quot;0x&quot;;<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([dai, weth], amounts, userData)<br>    ).to.be.revertedWith(&#39;BAL#102&#39;);<br>  });<br>});</pre><p>Now, to test the actual arbitrage part, I had to come up with something. The crucial part of this whole thing is actually finding the arbitrage opportunities. It’s not like you’ll randomly pick some tokens and DEXs and you’ll make a profit.</p><p>So I thought “hmm… maybe it’s time to start thinking about building the actual arbitrage finder bot and implement a basic version for these tests”.</p><p>While it would’ve been a great exercise, it would’ve been like killing a fly with a bazooka at this stage, and it would’ve taken a far longer time. So I decided to go with a different approach, for the time being.</p><h4>Manipulating token prices with wallet impersonation</h4><p>The idea with this approach is to execute a large swap on one exchange to artificially create a significant price discrepancy with other exchanges. So, if you made the price of an asset go up on one exchange, you can buy at the regular price on another exchange and then immediately sell on the first one, generating considerable profit.</p><p>To perform this large swap, we need the funds. Hardhat’s impersonateAccount function allows developers to simulate transactions from any address without having its private key. This means we can pick an existing wallet address that we know has a significant balance of a specific token and impersonate it, so we can use its funds within our test environment. Such wallets can be found by searching for a particular token in a particular chain explorer, listing wallets that hold this token and picking among the ones with the largest amounts of it. These accounts are commonly referred to as whales.</p><p>The following function takes care of impersonating an account, using Hardhat’s network:</p><pre>async function impersonateAndFund(token, sender, recipient, amount) {<br>  await network.provider.request({<br>    method: &quot;hardhat_impersonateAccount&quot;,<br>    params: [sender],<br>  });<br><br>  await fundERC20(token, sender, recipient, amount);<br><br>  await network.provider.request({<br>    method: &quot;hardhat_stopImpersonatingAccount&quot;,<br>    params: [sender],<br>  });<br>}</pre><p>where fundERC20() is defined as follows:</p><pre>async function fundERC20(token, sender, recipient, amount) {<br>  const whale = await ethers.getSigner(sender);<br><br>  await token.connect(whale).transfer(recipient, amount);<br>}</pre><p>With this setup, we can now fund our owner wallet with significant funds to perform a particular swap.</p><p>My approach to come up with a profitable arbitrage example that I could use in my tests was to first start playing around with this technique within my Polygon fork environment. So I created a separate test suite to try things out until I got something I could work with.</p><h4>Differences between DEXs</h4><p>So, I took the two DEXs that I’d picked, Uniswap and QuickSwap, and found a way to get an estimation of the price of a token. So I calculated this before and after a significant swap to get an idea of the kind of price movement it generated.</p><p>When working with the specifics, I found that, even if both DEXs implement the same ISwapRouter interface, some other aspects of their implementation are slightly different.</p><p>The basic idea to get this token price estimation is basically the same, but the data to perform the calculations is structured differently and you have to look in different places to find what you need. Each DEX will have a factory smart contract, from which you can get the pool address for any token pair, if available. So let’s say you want to swap DAI for WETH, if there is a pool for this token pair, you’ll get a pool address from the factory, and with the smart contract that corresponds to that pool address, you get a price estimation.</p><p>Usually, this price estimation is returned as the sqrt(token1/token0) in its Q64.96 value (a fixed-point number format, with 64 bits for the integer part and 96 for the fractional part). Which token is token1 and which is token0 depends on what the pool contract does internally, but it’s usually just sorting the token addresses in ascending order. So, depending on which token is which, you can alter the calculations accordingly if you want the price of token0 expressed in units of token1 or the other way around.</p><p>I’m calling this a price estimation because it’s calculated for an infinitesimally small swap. The larger the swap, the more it will deviate from this price.</p><p>I implemented two separate functions, one for Uniswap and one for QuickSwap to get this price:</p><pre>async function getTokenPairPriceQuickSwap(params) {<br>  const quickSwapFactory = await ethers.getContractAt(IAlgebraFactory.abi, &quot;0x411b0fAcC3489691f28ad58c47006AF5E3Ab3A28&quot;);<br><br>  const poolAddressQuickSwap = await quickSwapFactory.poolByPair(params.tokenA, params.tokenB);<br>  const algebraPool = await ethers.getContractAt(IAlgebraPool.abi, poolAddressQuickSwap);<br><br>  const token0 = await algebraPool.token0();<br><br>  const globalState = await algebraPool.globalState();<br>  const sqrtPriceBigInt = await globalState.price;<br><br>  const token0PriceInToken1 = calculateToken0PriceInToken1(sqrtPriceBigInt, params.decimalsA, params.decimalsB);<br><br>  if (params.tokenA === token0) {<br>    return token0PriceInToken1;<br>  }<br><br>  return 1/token0PriceInToken1;<br>}<br><br>async function getTokenPairPriceUniswap(params) {<br>  const uniswapFactory = await ethers.getContractAt(IUniswapV3Factory.abi, &quot;0x1F98431c8aD98523631AE4a59f267346ea31F984&quot;);<br><br>  const poolAddressUniswap = await uniswapFactory.getPool(params.tokenA, params.tokenB, params.feeTier);<br>  const uniswapPool = await ethers.getContractAt(IUniswapV3Pool.abi, poolAddressUniswap);<br><br>  const token0 = await uniswapPool.token0();<br><br>  const [sqrtPriceX96] = await uniswapPool.slot0();<br><br>  const token0PriceInToken1 = calculateToken0PriceInToken1(sqrtPriceX96, params.decimalsA, params.decimalsB);<br><br>  if (params.tokenA === token0) {<br>    return token0PriceInToken1;<br>  }<br><br>  return 1/token0PriceInToken1;<br>}<br><br>function calculateToken0PriceInToken1(sqrtPrice, decimals0, decimals1) {<br>  const priceX192 = sqrtPrice * sqrtPrice;<br><br>  const decimals0Num = Number(decimals0);<br>  const decimals1Num = Number(decimals1);<br>  const decimalsDiff = decimals1Num - decimals0Num;<br><br>  const pow192 = 2n ** 192n;<br><br>  return Number(priceX192)/Number((pow192 * BigInt(10 ** decimalsDiff))); <br>}</pre><p>Another difference I came across was when executing the swap. Uniswap lets you choose between different fee tiers, that depend basically on volatility and trading characteristics of the token pairs. When calling the swap function, you specify which fee tier you want to use. QuickSwap, on the other hand, doesn’t expect this as an input argument, it internally calculates them within the swap logic.</p><p>Remember the multi-hop swaps, where we had to send a path sequence (tokenA — feeAB — tokenB — feeBC — tokenC…)? Well, QuickSwap doesn’t expect the fees to be in the sequence, so it should be just the tokens (tokenA, tokenB, tokenC…). There’s not a whole lot of documentation that specifies this, so I had to browse through the <a href="https://polygonscan.com/address/0xf5b509bb0909a69b1c207e495f687a596c168e12#code">contracts</a> and try it out.</p><p>This actually led me to add a patch to my FlashLoanRecipient smart contract that I’m not so proud of:</p><pre>function encodePath(address[] memory _tokens, uint24[] memory _fees) internal pure returns (bytes memory) {<br>  require(_tokens.length &gt;= 2, &quot;Path too short&quot;);<br><br>  // TODO: for empty fees array this doesn&#39;t apply. Review check below.<br>  // require(_tokens.length == _fees.length + 1, &quot;Length mismatch&quot;);<br><br>  bytes memory path = abi.encodePacked(_tokens[0]);<br><br>  // TODO: Quickswap doesn&#39;t expect fees in the path, only tokens. <br>  // Instead of adding this, it would be better to have the encoded path be included in userData, <br>  // calculating it off-chain<br><br>  // DEXs without fees<br>  if (_fees.length == 0) {<br>    for (uint i = 1; i &lt; _tokens.length; i++) {<br>      path = abi.encodePacked(<br>        path,<br>        _tokens[i]<br>      );<br>    }<br><br>    return path;<br>  }<br><br>  // DEXs with fees<br>  for (uint i = 0; i &lt; _fees.length; i++) {<br>    path = abi.encodePacked(<br>      path,<br>      _fees[i],<br>      _tokens[i + 1]<br>    );<br>  }<br><br>  return path;<br>}</pre><p>I temporarily added an alternate logic for paths without fees. But this all just made me think that I should just send the encoded path from outside of the contract. And actually this is the kind of thing that will save some gas, which is crucial.</p><h4>Successful arbitrage test cases</h4><p>Going back to my arbitrage-finding playground, I gradually came up with a scenario that I could leverage for my tests:</p><pre>const daiWhaleAddress = &quot;0x91F1D2c2165B17a1eD2dC3B73Ae77224E6e1410E&quot;;<br>console.log(&quot;Dai balance whale&quot;, Number(await dai.balanceOf(daiWhaleAddress))/(10**18));<br><br>// Amounts for test funding (from impersonated whale address) and flash loan arbitrage<br>const whaleFundAmount = 1000000;<br>const flashLoanAmountForArbitrage = 1000;<br><br>// Fund owner wallet to start the process<br>await impersonateAndFund(dai, daiWhaleAddress, ownerAddress, tokens(whaleFundAmount));<br>console.log(&quot;Dai balance transferred to owner:&quot;, Number(await dai.balanceOf(owner))/(10**18));<br><br>const decimalsWeth = Number(await weth.decimals());<br>const decimalsDai = Number(await dai.decimals());<br><br>// Check market conditions on QuickSwap and Uniswap for the WETH-DAI pair<br>const wethPriceInDaiQuickSwap = await getTokenPairPriceQuickSwap({<br>  tokenA: wethAddress,<br>  tokenB: daiAddress,<br>  decimalsA: decimalsWeth,<br>  decimalsB: decimalsDai,<br>});<br>const wethPriceInDaiUniswap = await getTokenPairPriceUniswap({<br>  tokenA: wethAddress,<br>  tokenB: daiAddress,<br>  decimalsA: decimalsWeth,<br>  decimalsB: decimalsDai,<br>  feeTier: 3000,<br>});<br><br>console.log(&#39;wETH price in DAI QuickSwap&#39;, wethPriceInDaiQuickSwap);<br>console.log(&#39;wETH price in DAI Uniswap&#39;, wethPriceInDaiUniswap);<br><br>// Manipulate WETH price by performing a very large swap<br>await dai.connect(owner).approve(uniswapRouterAddress, tokens(whaleFundAmount));<br>const uniswapRouter = await ethers.getContractAt(ISwapRouter.abi, uniswapRouterAddress);<br>await swapTokensUniswap(uniswapRouter, ownerAddress, tokens(whaleFundAmount), daiAddress, wethAddress);<br><br>const wethPriceInDaiUniswapAfter = await getTokenPairPriceUniswap({<br>  tokenA: wethAddress,<br>  tokenB: daiAddress,<br>  decimalsA: decimalsWeth,<br>  decimalsB: decimalsDai,<br>  feeTier: 3000,<br>});<br><br>console.log(&quot;Manipulated wETH price in Uniswap:&quot;, wethPriceInDaiUniswapAfter);<br><br>// Execute arbitrage with flash loan<br>const daiAmountIn = tokens(flashLoanAmountForArbitrage);<br>const amounts = [daiAmountIn];<br><br>const arbitrageParams = [{<br>  sourceRouter: quickSwapRouterAddress,<br>  targetRouter: uniswapRouterAddress,<br>  sourceTokens: [daiAddress, wethAddress],<br>  targetTokens: [wethAddress, daiAddress],<br>  sourceFees: [],<br>  targetFees: [3000],<br>  amountIn: daiAmountIn,<br>}];<br><br>const userData = encodeArbitrageParams(arbitrageParams);<br><br>transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData);<br>const receipt = await transaction.wait();<br><br>const event = receipt.logs<br>  .map(log =&gt; {<br>    try {<br>      return flashLoanRecipient.interface.parseLog({<br>        topics: log.topics,<br>        data: log.data<br>      });<br>    } catch (e) {<br>      return null;<br>    }<br>  })<br>  .find(parsed =&gt; parsed &amp;&amp; parsed.name === &quot;ArbitrageExecuted&quot;);<br><br>  const profit = Number(event.args[2])/(10**decimalsDai);<br>  console.log(&quot;Arbitrage profit:&quot;, profit);</pre><p>Essentially, what I did here is:</p><ul><li>Impersonate a DAI whale and fund my owner wallet with 1,000,000 DAI.</li><li>Get the price estimates for WETH expressed in DAI for QuickSwap and Uniswap.</li><li>Manipulate the price of WETH on Uniswap by swapping the full 1M DAI for WETH.</li><li>Check the price after the massive swap.</li><li>Execute the flash loan arbitrage logic from the FlashLoanRecipient contract to borrow 1000 DAI, buy WETH on QuickSwap (regular price) and sell extremely high on Uniswap.</li><li>Parse the transaction logs to get the arbitrage profit value.</li></ul><p>With these numbers, this is what I got:</p><pre>Dai balance whale: 7680733.886618517<br>Dai balance transferred to owner: 1000000<br>wETH price in DAI QuickSwap 1951.2610209351246<br>wETH price in DAI Uniswap 1950.4331208257504<br>Manipulated wETH price in Uniswap: 7210029864954.252<br>Arbitrage profit: 990805.6414131385</pre><p>So, clearly, there’s a massive profit here, which means I can use these values in my actual tests without having to run all of this logic.</p><p>Finally, I copied over the same settings and used them to finish my tests:</p><pre>describe(&#39;Arbitrage with flash loan end-to-end&#39;, async () =&gt; {<br>  it(&#39;should revert because arbitrage is not profitable&#39;, async () =&gt; {<br>    const daiAmountIn = tokens(100);<br>    const amounts = [daiAmountIn];<br><br>    const arbitrageParams = [{<br>      sourceRouter: quickSwapRouterAddress,<br>      targetRouter: uniswapRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [],<br>      targetFees: [3000],<br>      amountIn: daiAmountIn,<br>    }];<br><br>    const userData = encodeArbitrageParams(arbitrageParams);<br><br>    await expect(<br>      flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData)<br>    ).to.be.revertedWith(&#39;Arbitrage not profitable&#39;);<br>  });<br><br>  it(&#39;should execute profitable arbitrage&#39;, async () =&gt; {<br>    // Generating a profitable arbitrage scenario (analysis in &#39;Arbitrage-finding playground&#39; test suite)<br>    const daiWhaleAddress = &quot;0x91F1D2c2165B17a1eD2dC3B73Ae77224E6e1410E&quot;;<br><br>    // Amounts for test funding (from impersonated whale address) and flash loan arbitrage<br>    const whaleFundAmount = 10000;<br>    const flashLoanAmountForArbitrage = 1000;<br><br>    // Fund owner wallet to start the process<br>    await impersonateAndFund(dai, daiWhaleAddress, ownerAddress, tokens(whaleFundAmount));<br><br>    // Manipulate WETH price by performing a very large swap<br>    await dai.connect(owner).approve(uniswapRouterAddress, tokens(whaleFundAmount));<br>    const uniswapRouter = await ethers.getContractAt(ISwapRouter.abi, uniswapRouterAddress);<br>    await swapTokensUniswap(uniswapRouter, ownerAddress, tokens(whaleFundAmount), daiAddress, wethAddress);<br><br>    // Execute arbitrage with flash loan<br>    const daiAmountIn = tokens(flashLoanAmountForArbitrage);<br>    const amounts = [daiAmountIn];<br><br>    const arbitrageParams = [{<br>      sourceRouter: quickSwapRouterAddress,<br>      targetRouter: uniswapRouterAddress,<br>      sourceTokens: [daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress],<br>      sourceFees: [],<br>      targetFees: [3000],<br>      amountIn: daiAmountIn,<br>    }];<br><br>    const userData = encodeArbitrageParams(arbitrageParams);<br><br>    transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([dai], amounts, userData);<br>    await transaction.wait();<br><br>    // Assert<br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;ArbitrageExecuted&#39;);<br>  });<br><br>  it(&#39;should execute profitable arbitrage with 3-token path&#39;, async () =&gt; {<br>    // Generating a profitable arbitrage scenario (analysis in &#39;Arbitrage-finding playground&#39; test suite)<br>    const daiWhaleAddress = &quot;0x91F1D2c2165B17a1eD2dC3B73Ae77224E6e1410E&quot;;<br><br>    // Amounts for test funding (from impersonated whale address) and flash loan arbitrage<br>    const whaleFundAmount = 10000;<br>    const flashLoanAmountForArbitrage = 10;<br><br>    // Fund owner wallet to start the process<br>    await impersonateAndFund(dai, daiWhaleAddress, ownerAddress, tokens(whaleFundAmount));<br><br>    // Manipulate WETH price by performing a very large swap<br>    await dai.connect(owner).approve(uniswapRouterAddress, tokens(whaleFundAmount));<br>    const uniswapRouter = await ethers.getContractAt(ISwapRouter.abi, uniswapRouterAddress);<br>    await swapTokensUniswap(uniswapRouter, ownerAddress, tokens(whaleFundAmount), daiAddress, wethAddress);<br><br>    // Execute arbitrage with flash loan<br>    const uniAmountIn = tokens(flashLoanAmountForArbitrage);<br>    const amounts = [uniAmountIn];<br><br>    const arbitrageParams = [{<br>      sourceRouter: quickSwapRouterAddress,<br>      targetRouter: uniswapRouterAddress,<br>      sourceTokens: [uniAddress, daiAddress, wethAddress],<br>      targetTokens: [wethAddress, daiAddress, uniAddress],<br>      sourceFees: [],<br>      targetFees: [3000, 3000],<br>      amountIn: uniAmountIn,<br>    }];<br><br>    const userData = encodeArbitrageParams(arbitrageParams);<br><br>    transaction = await flashLoanRecipient.connect(owner).makeFlashLoan([uni], amounts, userData);<br>    await transaction.wait();<br><br>    // Assert<br>    await expect(transaction).to.emit(flashLoanRecipient, &#39;ArbitrageExecuted&#39;);<br>  });<br>});</pre><p>And that’s it! I was able to tweak my blockchain environment to generate a profitable test case.</p><h4><strong>Bonus round: another flash loan experiment</strong></h4><p>While I was exploring this technique to artificially create a profitable arbitrage case, I had a crazy thought: if I was able to manipulate the price and generate such a profit, wouldn’t there be some sort of hidden arbitrage opportunity in this whole setup?</p><p>What would happen if the impersonated whale amount actually came from a flash loan? If that were the case, I would have to swap the WETH, that I initially obtained from the large swap on Uniswap, back to DAI and hope that that plus the arbitrage profit will be enough to repay the flash loan and still keep some profit.</p><p>To make it clearer, the process would be:</p><ol><li>Take a flash loan for 1,001,000 DAI</li><li>Swap 1 million DAI for WETH on Uniswap, making the price of WETH go up significantly</li><li>Take the remaining 1,000 DAI to buy WETH on QuickSwap at a lower price and sell high on Uniswap (where the price manipulation took place)</li><li>Take the WETH obtained from the initial swap in step 2 and swap them back to DAI on Uniswap, which would make the price of WETH go down again, but probably not as low as the original price</li><li>Take the DAI obtained from both step 3 and step 4, repay the flash loan and keep the profit</li></ol><p>For this to work out, I would have to find the “sweet spot” between the amount I’m allocating to the arbitrage trade and the one I’m using to manipulate the price and still be able to keep some profit.</p><p>Well, if I were able to pull something like this off, I would be incurring in a kind of flash loan attack. Things like this exist, and they’re the BAD kind of MEV, or at least not very ethical. Here, I would be temporarily manipulating market conditions to my favor, potentially making a profit at the expense of the ecosystem.</p><p>Anyway, just to mess with the idea a little bit, I tried different combinations of whaleFundAmount and flashLoanAmountForArbitrage and found that the system tends to get close to the break even point but never actually reaches it.</p><p>For a given whaleFundAmount value, if flashLoanAmountForArbitrage is too high, the arbitrage will not be profitable; too low, and it will asymptotically approach a specific value. The higher the whaleFundAmount value, the farther this asymptote will be from the break even point.</p><p>Adding the following bit of code at the end of the <a href="#54b9">last code snippet</a>, we have the reverse swap, WETH to DAI, and the total profit calculation:</p><pre>const wethBalanceOwner = await weth.balanceOf(ownerAddress);<br>console.log(&quot;wethBalanceOwner&quot;, Number(wethBalanceOwner)/(10**decimalsWeth));<br><br>await weth.connect(owner).approve(uniswapRouterAddress, wethBalanceOwner);<br><br>await swapTokensUniswap(uniswapRouter, ownerAddress, wethBalanceOwner, wethAddress, daiAddress);<br><br>const finalDaiAmount = Number(await dai.balanceOf(ownerAddress))/(10**18);<br><br>console.log(&quot;profit?&quot;, finalDaiAmount + profit - whaleFundAmount);</pre><p>For our current example, with whaleFundAmount = 1000000 and flashLoanAmountForArbitrage = 1000 these are the results:</p><pre>Dai balance whale: 7680733.886618517<br>Dai balance transferred to owner: 1000000<br>wETH price in DAI QuickSwap 1951.2610209351246<br>wETH price in DAI Uniswap 1950.4331208257504<br>Manipulated wETH price in Uniswap: 7210029864954.252<br>Arbitrage profit: 990805.6414131385<br>wethBalanceOwner 1.7896510438750635<br>profit? -3471.190798808937</pre><p>To find this asymptote I’m talking about, we can keep the whaleFundAmount value fixed and bring flashLoanAmountForArbitrage down to a very low value, like 0.0001:</p><pre>Dai balance whale: 7680733.886618517<br>Dai balance transferred to owner: 1000000<br>wETH price in DAI QuickSwap 1951.2610209351246<br>wETH price in DAI Uniswap 1950.4331208257504<br>Manipulated wETH price in Uniswap: 7210029864954.252<br>Arbitrage profit: 267247.71313088655<br>wethBalanceOwner 1.7896510438750635<br>profit? -3010.499332205276</pre><p>This means that best case scenario, you’ll be losing ~3010.499 DAI.</p><p>Following the same logic, I made whaleFundAmount = 10.7 and flashLoanAmountForArbitrage = 0.0001</p><pre>Dai balance whale: 7680733.886618517<br>Dai balance transferred to owner: 10.7<br>wETH price in DAI QuickSwap 1951.2610209351246<br>wETH price in DAI Uniswap 1950.4331208257504<br>Manipulated wETH price in Uniswap: 1960.8687943944399<br>Arbitrage profit: 4.3722773e-11<br>wethBalanceOwner 0.005454922624434023<br>profit? -0.06401917133134383</pre><p>In this case, the loss amount is pretty close to 0, but lowering whaleFundAmount just a tad makes the arbitrage not profitable.</p><p>Serious DEXs will usually implement various mechanisms specifically designed to protect against this type of manipulation, which is why finding that “sweet spot” is so challenging. The DEX algorithms are specifically tuned to make sure that the cost of manipulation generally exceeds the potential arbitrage profit.</p><h4>Conclusion</h4><p>Arbitrage trading powered by flash loans is a great way to extract value, while actually helping the DeFi ecosystem. Learning about it and exploring it has been a very exciting journey, from getting grasp of the general idea, to navigating the many potential pitfalls and challenges.</p><p>Starting out with simple smart contracts to establish the concept and building from the ground up has resulted in a very valuable learning experience. In my case at least, that proved to be a successful way to focus on the many interactions between the smart contracts and gradually shift to an environment that is closer to what can be seen in the real world.</p><p>Even with the limited scope of this proof of concept, I surely had a lot to say about the topic and there are definitely some next steps on the horizon:</p><ul><li>Building the arbitrage finder script. With the Polygon fork “playground” environment experience under my belt, I have an idea of what it’s like to work with actual DEXs, pools and some of the involved components, which should give me something to work with, even if this part is a whole project in itself.</li><li>Analyze the FlashLoanRecipient smart contract more thoroughly for possible vulnerabilities and spot as many gas optimization opportunities, since efficiency is key.</li><li>Integrate with Flashbots or other services to protect against MEV and avoid spending unnecessary fees as much as possible.</li></ul><p>So, this is definitely a “to be continued”, so there’s still a long journey ahead. And, even if chances of substantial success are slim at this point, it’s worth at least approaching this fascinating use case from an academic perspective, gaining some practice along the way.</p><p>If I ever reach a point where this actually becomes massively profitable though, I don’t know if I’ll be sharing my secret 😜</p><p>Jokes aside, I hope you can also take something away from this. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddd487ba55cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>