Flash Loans, The Graph, and Triangular Arbitrage : Your Quick Guide to Profit In Decentralized Markets

Brennan Skinner
Coinmonks
6 min readFeb 28, 2023

--

Seeking to profit from the world of Defi? Look no further than the combination of Flash Loans and The Graph! By using these decentralized market tools, you can unlock the lucrative world of triangular arbitrage in just a few clicks. But where to start? Here, of course! We will explore the ins and outs of this strategy and provide enough material for you to get started.

The Plan

  • Use The Graph to index the Ethereum mainnet for decentralized market data
  • Build an algorithm to find and vet triangular arbitrage opportunities
  • Build a Smart Contract utilizing flash loans to execute a trade on a profitable triangular arbitrage opportunity.

Prerequisites

  • Web3 terminology (liquidity pools, DEXs, AMMs etc.)
  • Uniswaps CFMM (constant function market maker)
  • Knowledge of The Graph
  • Knowledge of Smart Contracts and Flash Loans

If you have a firm grasp with the above prerequisites you can skip over this next part. If you need a quick refresher we will go over a few of the basics before we jump into building our algorithm.

What exactly is triangular arbitrage?

Triangular arbitrage is the result of a price discrepancy, which occurs when three currency exchange rates do not match. With regard to Defi (decentralized finance), these discrepancies can be found between three separate liquidity pools (LPs) held on DEXs (decentralized exchanges). We will be focusing on three separate DEXs exclusively, which will broaden our net and ability to find larger discrepancies across the Defi market.

Our markets we will be focusing on

Uniswap V2, Uniswap V3, and Sushiswap are all DEXs that are similar in many ways, however there are three reasons why they will benefit us in the long run.

What type of CFMM are we working with?

Let’s do a quick recap of Uniswaps CFMM. According to Uniswaps white-paper, the following formula sets the prices automatically within an LP given a trade.

CFMM
  • Ra is Token A reserve amount
  • Rb is Token B reserve amount
  • Δb is the input amount (what you own)
  • Δa is the output amount (what you are receiving)
  • r is the fee included (every LP has a trading fee, typically 3%), in this case r is denoted
    as r — 3%
  • Finally, k can be found as the product of both reserves : Ra * Rb = k

By keeping the overall reserves at a constant we can easily break down this formula and determine how many tokens we will receive in a trade. Pop Quiz !

Assume a liquidity pool with the token reserves of token A at 5 and the token reserves of token B at 20. If trader Ryan wants to swap his 1 token A for token B how many tokens will Ryan receive ?

Breaking down the above equation we can replace the following:

Next, we can simplify the equation and solve for Δb to get our final amount. But first, let’s remove the swapping fee from Ryan’s amount, which will put Ryan’s amount at .997.

Finally, Ryans will receive 3.324996 of token B leaving the liquidity pool with new token reserve amounts. If we were to reapply the CFMM formula we find that the result is unchanged. That is why it is called a constant function market maker.

So now that we have reviewed how to calculate the amount of tokens we will receive in a given trade all we need is the liquidity pools data.

How do we get data?

Introducing The Graph, an open-sourced and decentralized indexing protocol for blockchain data. Developers can build and publish various APIs called “subgraphs” that perform queries over GraphQL. Currently, most DEXs do not support traditional API requests. Instead, most DEXs have subgraphs designed to query for data found on its platform with a standard GraphQL API.

To set this up take the following Axios post request to Uniswap V3’s subgraph,

async function uniswapSubgraph_V3_Api(query) {
try {
const url = '-- end point here --’;

const { data } = await axios.post(url, query);

return data;

} catch (error) {
console.error('there was an issue calling uniswap_v3 subGraph', error);
}
}

The parameter will take a GraphQL query to index blockchain data from Uniswap V3s subgraph. Don’t worry you won’t have to build these queries entirely on your own. You can jump to the DEXs playground and test your own queries. Take the following Uniswap V3 subgraph query.

{
poolHourDatas(first: 1000, orderBy: txCount, orderDirection: desc, where: {periodStartUnix_gte: ${---time stamp --}}){
pool {
id
feeTier
token0Price
token1Price
liquidity
tick
sqrtPrice
token0 {
symbol
decimals
id
derivedETH
}
token1 {
symbol
decimals
id
derivedETH
}
}
}
}

This indexes Uniswap V3s protocol for 1000 liquidity pools. The resulting response would be an array of n objects Ordered by the amount of transactions each pool has had within a given time frame (please note some liquidity pools may not have had a transaction).

What are Flash loans?

Similar to traditional loans, Flash loans are borrowed funds expected to be paid back eventually. However, they operate in a different capacity:

  • They are unsecured loans
  • They operate through smart contracts
  • They are instantaneous

I. Flash Loans as Unsecured Loans

Unlike a traditional loan, a flash loan is an unsecured loan meaning no collateral is needed. Since flash loans are unsecured, they carry a high risk for lenders. However, flash loans have a strict set of rules within a smart contract. These strict rules are the security provided, which in short reverts the transaction if any issue arises.

II. Flash Loans in Smart Contracts
In essence, smart contracts can be defined as a self-executing electronic script contingent on an event if a specified scenario occurs.

Unlike building a Smart Contract, however, where you have the ability to set terms for yourself, flash loans have predefined rules. One rule is that the borrower is required to repay the full amount of the loan before the completion of the transaction. For example, when a transaction is mapped out, if the funds are not returned in full to the initial lender at the end of the loan period, the loan is rendered null and the transaction is reverted. The down side to this outcome would be the transaction fees (gas fees) and trading fees (swap fees) incurred.

III. Flash Loans Are Instantaneous

Getting a traditional loan approved is usually a long process. A borrower must submit documents, wait for approval, and pay the loan back that may run into days, months or years.

A flash loan is executed instantaneously. The loan’s smart contract must be fulfilled during the transaction for which its lent out. Therefore, the borrower is required to call on other smart contracts, using the loaned capital to perform instant trades.

What’s next?

Let’s move forward now that we’ve reviewed the essentials. Our guide will be divided into several articles, each of which will explain how we discover triangular arbitrage opportunities, determine their profitability, and execute the trades (coming soon).

In these articles, we’ll break down simple methods and provide detailed explanations of how decentralized tools like the Graph and Flash Loans can be useful in this process.

Sources and Further Reading:

New to trading? Try crypto trading bots or copy trading on best crypto exchanges

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

Also, Read

--

--

Brennan Skinner
Coinmonks

Tech enthusiast constantly exploring new ideas & tech to create innovative solutions for every project.