Starter Guide: Crypto Currency Arbitrage with Flashloan vol.1

Yuya Sugano
10 min readJul 16, 2022

First things first, since I released the first arbitrage code in github there has been a lot of issues and questions in both github and Medium comments. I’m glad to see people’s reaction and how people are keen on the emerging tech space such as blockchain, ethereum and DeFi. This trend looks not fugitive but inevitable to me as a lot of authorities and retail investors started looking into these areas.

Unfortunately I haven’t been able to find juicy arbitrage opportunity yet. This might be because of the market conditions (less volatile, pool size, DEX conditions, other predetors work in mempool what I have no idea at all now) or my set-up wasn’t so good in latency, the smart contract point of view. Some people would have found tremendous opportunities definitely and they must have had luclative results.

To me, I’m more interested in & inclined to educate people and democratize this decentralization movement which will be the next gen foundation in the human world to replace publicity, the government, the companies, the countries, any centralized authorities who still want to keep their power in control. I hope crossing the chasm is close to some point for crypto and blockchain in our society.

Here is for who wants to see the repo and play with it: repo

Disclaimer

This article is not either an investment advice or a recommendation or solicitation to buy or sell any investment and should not be used in the evaluation of the merits of making any investment decision. It should not be relied upon for accounting, legal or tax advice or investment recommendations. The contents reflected herein are subject to change without being updated.

Image by Kai Pilger from Pixabay

In this guide, I’d like to prevent people from getting mazed. I’d like to go through step by step to explain ideas before delving into the smart contract code and how to set up your local environment. If you did not understand what you’re doing in the middle, you will be lost where you are completely, you will lose your purpose and where you need to head to. You’ll be wrecked.

First things first, this is the guide “Crypto Currency Arbitrage with Flashloan” volume 1. In the volume 1, we’ll look through what an arbitrage and what this means “doing arbitrage in blochchain (DeFi)” throughly. In a later volume 2, we’ll learn the Flashloan smart contract and how to set up your local environment to run the smart contract code and Node.js script to find arbitrage opportunities. I’ll try to keep writings concise.

3 things are important to understand in this guide volume 1:

  1. What is arbitrage?
  2. Arbitrage in DeFi
  3. Arbitrage with Flashloan

What is arbitrage?

Investopia explains: [2]

Arbitrage is the simultaneous purchase and sale of the same asset in different markets in order to profit from tiny differences in the asset’s listed price.

You may notice that this definition does not limit any markets and goods Arbitrage opportunity falls under. You can think of arbitrage for commodity, stock, bonds and any other goods at the same time as long as your target asset can be traded in different markets(exchanges) even physically or virtually.

Investopia explains difficulties of arbitrage:

Arbitrage provides a mechanism to ensure that prices do not deviate substantially from fair value for long periods of time. Any inefficient pricing setups are usually acted upon quickly, and the opportunity is eliminated, often in a matter of seconds.

These days most of traders (not only pro but also amateur) have computerized trading systems set to monitor such price fluctuations and set a program or code to fire her/his strategy immediately in their systems. Flash boy 2.0 exists in real and they are amazingly fast and quick. [3]

Let’s take the Investopia simpler arbitrage example.

The stock of Company X is trading at $20 on the New York Stock Exchange (NYSE) while, at the same moment, it is trading for $20.05 on the London Stock Exchange (LSE). A trader can buy the stock on the NYSE and immediately sell the same shares on the LSE, earning a profit of 5 cents per share.

Let’s think what difficult points are in this trade… these difficulties can apply to any markets you can think of.

  1. When you notice this opportunity and you try to buy the asset, the asset liquidity might be depleted due to some reasons. You can’t buy what you want always when you want in the market.
  2. While you send your asset from the exchange A to the exchange B (in this case NYSE to LSE), the price discrepancy of those exchanges might be gone. Moving your asset takes time even it’s digitalized.
  3. It is 100% sure that other people have the same idea and rush in buying the asset in the exchange A and selling the asset in the exchange B. With rapid buy & sell trades at both ends, this opportunity gets eliminated quickly.

Takeaways:

  1. You need to recognize arbirage opportunities as fast as possible
  2. You should be able to move your assets between the markets as fast as possible
  3. You need to process a transaction as fast as possible in both markets

So we can conclude that we must digitize our arbitrage strategy for the sake of profits and pursue a low latency environment to send a transaction if it is in a digitalized market (off course DeFi included).

Arbitrage in DeFi

Wikipedia page explains: [4]

Decentralized finance (DeFi) offers financial instruments without relying on intermediaries such as brokerages, exchanges, or banks by using smart contracts on a blockchain. DeFi platforms allow people to lend or borrow funds from others, speculate on price movements on assets using derivatives, trade cryptocurrencies, insure against risks, and earn interest in savings-like accounts.

In a simple word, DeFi is a set of autonomous finance features built on blockchain in the underlying internet communications. It does not rely on any people, and the authorities but only code. “Code is Law”: code was ultimately the architecture of the internet but that code exchanged only IP packets. On top of it, we must have created web or applications to express the things.

Now we can embed a form of value and functions in the underlying blockchain network. Financial feature such as lending, borrowing can be embedded into blockchain by means of smart contracts. Here’s the reason why DEXs plays an important and imparative role in DeFi world. When you need to access to finance, you need only the internet and your wallet.

What is DEX now? Dex is a place you can exchange your crypto currency assets in DeFi world. DEXs are non-custodial and leverage the functionality of self-executing smart contracts for peer-to-peer trading, while users retain control of their private keys and funds. While traditional finance trasactions are processed via intermediaries such as banks, brokers, payment processors, or other institutions, transactions in DEXs are directly made between participants, mediated by smart contract programs. [5]

The swift growth of DEX spot volume. (Source)

Why is this democratization important? In our traditional finance world, printing money is the symbol of power of central banks i.e. the jurisdiction of the country. Now people can invent their money (as an exchange of medium or for other purposes) and give confidence to money by them. When you bought assets, or transfer your money to your family, banks or security companies took fee for you to process a transaction. Now you don’t need to pay for such companies or authorities. We should pay for miners and people who helps to process your transaction directly. You’ll see the beauty of it from birds eye view how the things work in the decentralized manner and authoritative power can be diminishing.

Now let’s focus on arbitrage in DeFi. We looked through what arbitrage is already in general. We should know differences between arbitrage in general market and arbitrage in DeFi in this paragraph. The first thing you must understand is AMM(Automated Market Makers) that the most of DEX protocols adopted for their exchange systems (Uniswap invented AMM and coined the terminology). AMM is the place we play arbitrage startegy in this article.

Rather than using a centralized exchange to fill orders, AMM DEXs pay users to form liquidity pools in exchange for a percentage of the fees that traders earn by swapping tokens in and out of the liquidity pools. Market makerts usually take profits from the spread — the gap between the highest buy offer and lowest sell offer. AMM in DeFi world provides liquidity as same as traditional market makers but not put order in order book. They provide their assets in liquidity pool for users.

You can check Chainlink’s writing for more details. [6]

There is no spread under this AMM model as we looked through. Let’s say arbitrage in DeFi is “to take profits between DEXs by looking for inefficiencies of the prices of the assets”. Here are some problems you may encounter if you’d like to achieve profitable arbitrage:

  1. Low Capital Efficiency — AMM requires large amounts of liquidity to achieve the same level of price impact as an order book-based exchange. You have to avoid underutilized and poorly providioned liquidity pools. But I think that the minor liquidity pairs tend to have more chance of larger deviation from its fair value due to this nature.
  2. Price Slippage — Under AMM(the constant product AMM), the price impact will be huge the larger deal you have. This is significant for larger deals and/or smaller liquidity pools. You may need to control your capital how much assets you exchange at the exchange A and sell it back at the exchange B for profits. Large trades do not mean it is good always.
  3. Front running — There are some front runners in a mempool when some participant seeing an upcoming trading transaction puts his own transaction ahead(playing with a transaction fee for example), making the initial transaction less profitable or even reverted. MEV searchers can also pay expensive fee for her/his transaction bundle to be included in a block. [7]

We can conclude that we have to research and watch liquidity pool health status, control our capital how much we exchange for less price slippage, and then avoid or mitigate front running to some degree. I don’t have any means to deal with 3) Front running in BSC because I haven’t heard of that Flashbots or similar projects to exist in BSC network yet. You may pay a little higher gas fee in BSC network and hope the miner nodes pick your transaction at higher priority.

Arbitrage with Flashloan

As we concluded in the previous paragraph, 1) we need a fast transaction and transfer of assets scheme between exchanges, 2) control the amount of asset and avoid or mitigate front running. This is the reason we need to take into account Flashloan that part of DEXs implemented. Flashlaon can resolve some of the problems that we have seen beautifully and elegantly.

First of all, what is Flashloan?

Flashloan allows us to borrow a vast amount of liquidity from lending pools or AMM-based pools at a moment and we can get capable of doing whatever(arbitrage, collateral swap, self-liquidation, and unwinding leveraged positions) we want in a single atomic transaction. If this transaction fails for some reasons then the transaction gets reverted as if nothing had happend. You will recognize that the aforementioned two problems can be settled with this magical nature of Flashloan.

Flash Loans are special uncollateralised loans that allow the borrowing of an asset, as long as the borrowed amount (and a fee) is returned before the end of the transaction. There is no real world analogy to Flash Loans.

Within a flashloan transaction, all your operations such as buying and selling tokens, and transferring in various exchanges can be executed orderly if the miners incude your transaction in a block. You don’t need to send exchanged tokens from A to B, B to C. Your logic can be embedded in a smart contract and the Flashloan contract calls your logic back when you borrow capital without any collateral.

As much as either lending pools or liquidity pools allow your logic to borrow, there will be limitless liquidity to use. It can be borrowed without any collateral, no KYC because of nature of DeFi(non-custodial and no centralized authorities to facilitate the transfer and custody of funds). Code is Law and Law is Code. Now you get control how much you want to use for your arbitrage strategy.

We have come to the plateau and now see the magnificent view how beauty and elegant it is. The last piece I want to cover in this guide vol.1 is the different Flashloan implementations. Aave protocol coined the terminology “Flashloan” and invented it in their protocol. It is the patriarch. Also Uniswap implemented Flashswap that is a callback behind the swap operation.

Aave based protocols have an idea “Lending pools” that are reserves of liquidity for suppliers and borrowers. Suppliers provide liquidity to a market and can earn interest on the crypto assets provided, while borrowers are able to borrow in an overcollateralized fashion. Aave V3 introduced multiple reserve call feature that allows us to borrow multiple assets from the lending pools in a single transaction.

On the other hand, Uniswap and Uniswap-forked protocols implemented the feature “Flashswap” that is equivalent to Flashloan. If you looked through Uniswap document, you can get an idea Flashswap that can be deemed as a normal swap operation. “all swaps are actually flash swaps!” This means that pair contracts send output tokens to the recipient before enforcing that enough input tokens have been received.

Here’s a nice reference for you to understand the differences between Flashloan implementations. [9]

Congrats. If you read the article and went through the references, you must have perceived how Flashloan is unique and good for arbitrage in DeFi. Flashloan is meant to be an arbitrage driver in non-custodial and no centralized authorities financial world in blockchain.

In the next article vol.2 we will look into the details of Flashswap and smart contract, also how to set up a local environment to deploy a smart contract with hardhat and run a monitor script in node.js. If you’re curious about the smart contract codes and the script beforehand, here’s the repo. Thanks for reading.

--

--

Yuya Sugano

Cloud Architect and Blockchain Enthusiast, techflare.blog, Vinyl DJ, Backpacker. ブロックチェーン・クラウド(AWS/Azure)関連の記事をパブリッシュ。バックパッカーとしてユーラシア大陸を陸路横断するなど旅が趣味。