Quantitative Crypto Insight: an analysis of triangular arbitrage transactions in Uniswap v2

By Indra Rustandi, Nabil Benbada, Yao Ma

Arbitrage defined

In traditional finance, an arbitrage is an opportunity to make a positive gain with virtually no risk involved by taking advantage of pricing discrepancies that are present in the markets. These pricing discrepancies are an indication that some inefficiencies are present in the markets.

Arbitrageurs will exploit these opportunities to make a profit and thus remove the pricing discrepancies, bringing back the markets to a more efficient state.

Triangular arbitrage in TradFi

In FX markets, a typical arbitrage trade is the triangular arbitrage which involves at least 3 currencies:

This arbitrage would take advantage of any deviation in price between the above three pairs.

Here, in an efficient market, we should always have:

In this example:

Here, any deviation from this equilibrium will lead to an arbitrage opportunity. For example, if Euro was cheaper relative to USD.

Triangular arbitrage DeFi: Uniswap

Uniswap is a decentralized exchange venue that allows two kinds of activities:

  1. Provide liquidity of a given pair of ERC-20 tokens
  2. Swap one ERC-20 token for another ERC-20 token

For the remainder of the post, we will focus on the second version of Uniswap (Uniswap v2), first deployed in May 2020. And since we are interested in triangular arbitrage, let us first explain how a swap is priced.

Uniswap belongs to the category of “constant-product market”. In this category, the product of the liquidities of the two ERC-20 tokens in the pair of interest is constant:

For illustration purposes, say token A is WETH while token B is USDC, and we have in the WETH-USDC pool 1,000 WETH and 3,000,000 USDC. Then,

Assume now that we want to swap 1 WETH to USDC, how much USDC can we obtain? Our trade would increase the liquidity for WETH to 1,001 WETH. In order to maintain the constant product, we have:

So the amount of USDC that we receive in the swap is:

So in our swap, we receive an effective WETH/USDC rate of 2,997.

A few things to note here:

  • This example doesn’t include fees to focus on the pricing.
  • The effective WETH/USDC rate can change when we swap a different amount of WETH. This is called slippage. In this example, the effective price “slipped” by 3 USDC or 0.1%.
  • Our WETH/USDC rate is purely determined by the liquidities available in the venue and is not dependent on how WETH/USDC is quoted on other venues. This is yet another possible source of arbitrage, albeit one that is beyond the scope of this post.

Triangular arbitrage opportunities in Uniswap v2

Based on the discussion so far on both triangular arbitrage and Uniswap, a natural question is how prevalent triangular arbitrage opportunities are in Uniswap v2. We try to answer this question indirectly by analyzing Uniswap v2 swap trades that take advantage of triangular arbitrage opportunities. More specifically, we focus on the following characteristics:

  • All the trades are executed in the same transaction to reduce the risk of prices moving and affecting the arbitrage opportunities.
  • All the trades involve only Uniswap v2. With this, we miss triangular arbitrage trades that involve multiple venues (e.g. simultaneous swaps on Uniswap and Sushiswap).
  • All the tokens involved in the trades offset except for one token: the gain token, for which the sender will gain more at the end of the trade series.

After analyzing over 68 million Uniswap v2 swaps since Uniswap v2 was deployed until the end of 2021, we found 1,371,122 swaps grouped in 429,315 transactions taking advantage of triangular arbitrage opportunities in Uniswap v2.

On a monthly basis, we see a pronounced peak in October 2020, while the number of trades taking advantage of triangular arbitrage opportunities have been decreasing since. There are many factors that might have caused this (rise of competing DEXes, arbitrage opportunities mechanically decreasing due to the market becoming more efficient…). We are currently exploring these leads to try and explain this behavior.

Next, we see which tokens are most often used as gain tokens. WETH is the clear front runner here with 417,229 trades. 2nd-4th place are occupied by stablecoins: USDC, USDT, DAI. In total, we identified 123 distinct tokens used as gain tokens, but the top four tokens account for more than 99% of the trades.

How many legs were typically used to trade these opportunities? A majority of these trades were done using three legs. Quite a significant number also involved up to 6 legs.

How profitable are these trades? For WETH, a high proportion of the 417,229 trades involving WETH are profitable (about 94% when accounting for gas). The most profitable trade gained around 280 WETH, but the average and median gas-adjusted gains are much smaller (average: 0.08 WETH, median: 0.012 WETH).

For USDC, the trade with the most gain accumulated more than 14,000 USDC, but on average, the gain was around 97 USDC, while the median gain was almost 28 USDC.

Let us now consider the individual addresses (without revealing any specific ones) behind these trades. We found that these trades were initiated by 4,784 unique addresses, the most active of which initiated more than 16,000 trades. In total, 94 unique addresses initiated more than 1,000 trades each. When using WETH as the gain token, the most profitable address managed to accumulate more than 1,100 WETH as a result of its trades; in the case of USDC as the gain token, the most profitable address accumulated almost 35,000 in USDC.

Arbitrage trade execution

Last but not least, let us now discuss at a high level how these triangular arbitrage opportunities are detected and how the corresponding trades are executed.

We need to monitor the prices, likely using an automated process, in the Uniswap v2 pools. Given the prices for various pairs, an algorithm can run a search to see which combinations of pairs give rise to triangular arbitrage opportunities, potentially also incorporating opportunities identified from pending transactions in the mempool.

Once opportunities are identified, then we move to the execution aspect. One key consideration is minimizing slippage, and it naturally leads toward having the swaps being executed within a single transaction. Another consideration is avoiding front-running or sandwich attacks, for which Flashbots Auction can be beneficial.

Future directions

Here, we have just scratched the surface in terms of understanding and maximizing the potential of decentralized finance. We, as part of the Data Science Quantitative Research team, aim to get a good holistic understanding of this space from a quantitative perspective that can be used to drive new Coinbase products. We are looking for people that are passionate in this effort, so if you are interested in Data Science and in particular Quantitative Research in crypto, come join us.

The analysis makes use of the Uniswap v2 subgraph made available through the Graph Protocol. Thanks to Luke Youngblood and Xavier Lu for their contribution and feedback.

Quantitative Crypto Insight: an analysis of triangular arbitrage transactions in Uniswap v2 was originally published in The Coinbase Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Scaling Content at Coinbase

By Clay Kohut, Senior Software Engineer

TLDR: Over the past year, Coinbase has invested in tooling to eliminate static content across our web frontend. This is the story of how we did it and why it’s important.

Coinbase Learn(ed)

The Coinbase educational portal, Coinbase Learn, launched in late 2020. Learn contains hundreds of beginner guides, practical tutorials, and market updates and is maintained by a dedicated team of content editors.

Our engineers explored various options for powering Learn. Ideally, we wanted a solution that would allow us to seamlessly integrate content into the Coinbase logged out experience.

Hosted options for blog-like content such as Medium provided too little flexibility.

The Wordpress framework was too opinionated and directly tied to the UI.

We ended up opting for a headless CMS, specifically Contentful. Contentful is a content platform that delivers a headless approach to content as well as backend extensibility to integrate with our preferred tools and ways of working. Being “headless” means the CMS is UI agnostic — it separates the content from the experience, simply providing structured JSON to the frontend, which allows for us to totally control the frontend experience.

Integrating with Contentful was simply a matter of creating data structures representing different types of content (via the Contentful UI) and then mapping those data structures to React components (which handled actually rendering the data)

Our initial CMS architecture

Donning the Flightsuit

With Coinbase Learn under our belt and the Coinbase Direct Public Offering (DPO) on the horizon, a cohesion initiative kicked off (deemed Project Flightsuit). Project Flightsuit sought to bring a cohesive look and feel across Coinbase logged out properties as well as enforcing design standards across newly created landing pages.

While investigating the state of the Coinbase product landing pages, we uncovered 40 product surfaces spread across 15 different repositories / frontend applications. The various frontends were built using a variety of technologies — everything from React with Typescript (our current standard) to legacy Ruby on Rails templates, to static HTML.

A peek of our “Page Architecture” overview document

Leveraging the Contentful integration initially set up for Coinbase Learn, we began to create a set of “blocks” which could be used to standardize landing page layouts (while aligning around our new brand guidelines).

“Blocks,” also known as content types, are high-level components which combine to create landing pages. For example, a “Hero” block might contain a “Title”, “Subtitle” and “CTA Button” in the CMS, which corresponds to a React component on the frontend.

A “Hero Block” data structure (left) and the corresponding React component (right)

By creating a thoughtful “Block-based system” (and reworking our existing landing pages to use this system), we were able to efficiently migrate nearly all landing pages to a single frontend application, powered by React, and integrated with Contentful.

Once the block system was in place, migrating pages was a relatively simple task of dragging / dropping various blocks via the Contentful UI, and redirecting the old page routes to the new, CMS-driven alternative.

1, 2, Automate

Post-Project Flightsuit, our team focused on improving the usability and resiliency of the CMS. A few lessons learned:

  1. Making the CMS easy-to-use for non-technical team members is extremely important. With our first pass at CMS landing pages, we had created some data structures with advanced features (such as generic layout creation) which were mostly only understood and serviceable by Engineers (thus defeating the main value prop of the CMS). We countered this by favoring editor experience above all else. By automating advanced features within Contentful wherever possible (such as automatically determining which layout would best suit a set of content), we could allow editors to focus on editing rather than building.
  2. By integrating with Contentful (a third party), our frontends became dependent upon Contentful’s uptime. Contentful has a very consistent track record of nearly 100% uptime, but this reliance was challenged when Contentful experienced two outages due to some widespread DNS issues. (To be fair to Contentful, these outages were also experienced by some of the world’s largest websites and were the only instances we’ve seen where Contentful was unavailable). To ensure availability of our higher visibility pages (such as our homepage), we determined the best path forward was to introduce a reverse API proxy which leverages the stale-if-error, in order for our CDN to serve cached content if the upstream call happens to fail. This allows us to stay up even if the CMS goes down (for X number of days).
Above: Our CMS architecture before and after adding the cached reverse proxy

3. Training new engineering teams on working with and extending the CMS was a primary focus. My team had become the sole source of knowledge of an increasingly-used system and were often sourced to onboard new engineers to the system on a one-off basis. To better spread the knowledge of the framework, we developed the CMS Ambassador Program, which aimed to train and bring together subject matter experts for the CMS throughout the company. The program begins with a 1.5 hour structured workshop where attendees learn the ins and outs of integrating with the CMS. While this program is currently driven in real-time and onboarding sessions are held as-needed, we are currently in the process of converting this to a self-service course via an internal training tool.

A snapshot of our internal CMS Ambassador workshop

Key Results

As 2021 comes to a close, we’re proud to look back at how far we’ve come over the past year. Here is the progress we’ve seen after successfully implementing our company-wide CMS:

  • Landing page creation time reduced from an average of 2 weeks to less than one day.
  • Content change turnaround time reduced from an hour-long process of code change/review/merge/deploy to under 10 mins, and without engineering involvement.
  • By the end of year, 90% of all top level surfaces will be covered. This means that nearly all top-level, logged out product surfaces on Coinbase will be powered via Contentful by end of year.

These efficiency gains have been achieved thanks largely to our leadership’s investment in infra and developer tooling. Coinbase truly cares about engineering excellence, developer experience, and automating routine processes.

We also couldn’t have achieved this without the hard work of some astoundingly thoughtful, talented individuals (each of whom I’m incredibly proud to work with):

  • Leon Haggarty, Askat Bakyev, João Melo, Stephen Lee, Wilhelm Willie, Bryant Gallardo, Guiherme Luersen, Raymond Sohn (Eng)
  • Bobby Rasmusson (Product)
  • Ananth Chandrasekharan, Goutham Buchi, Manish Gupta (EVP of Eng)

We’re all excited to enter 2022 with a shiny, unified frontend and minimal one-off content change requests on the horizon. If you’re interested in joining Coinbase, check out our Careers page here. Here’s to a happy new year!

Scaling Content at Coinbase was originally published in The Coinbase Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Meet Kryptology: Coinbase’s Open Source Cryptography Library

We’re excited to announce the open sourcing of Kryptology. Kryptology is a cryptographic library for the Crypto community that will enable and empower developers to create novel crypto innovations with state-of-the-art cryptography.

At Coinbase, cryptography is a first-class citizen. We’re passionate about cryptography as a driver for innovation in crypto. It is the most important mechanism for delivering delightful user experiences, and it enables privacy solutions that will change the security paradigm.

Why do we believe this?

Crypto is founded on cryptographic innovation. As described in Bitcoin’s academic pedigree, Bitcoin used existing, but not-yet-production, academic cryptography (hashcash, Chaum’s E-cash, Merkle trees) with economic game-theory to solve the Byzantine Generals problem.

Crypto changes cryptography. The feedback loop is running at warp speed. Cryptographers created private transactions with zero-knowledge techniques in ZCash, The Internet Computer is built on new cryptographic breakthroughs, Monero uses ring signatures to gain confidentiality, skale is using BLS to create roll-ups to improve scale and reduce storage on-chain, and Mina and ZCash use Halo 2 and Pasta.

Coinbase also strives to bring near-future cryptography into production. zkSNARKS and Cryptographic Accumulators, FROST, and Threshold Signing.

While enabling further innovation is our primary goal, we also aim for Kryptology to elevate the standard for what is considered to be a robust, usable cryptographic library. The library provides developers with a toolbox of secure, audited, and easy-to-use APIs. Kryptology is designed to be misuse-resistant (i.e., “hard to screw up”), so developers can focus on what they do best. We hope this translates to more projects that build and grow the crypto ecosystem.

A guide to Kryptology, including full documentation, can be found in the repository. This includes common development issues and lessons learned from our years of experience with cryptographic implementations. We hope these learnings will be uniquely valuable for others that want to support developers and build great user experiences. Over time, our goal is to support a thriving ecosystem of new and working cryptography for many more applications. Check out our open source guidelines or get started here.

If you are interested in cutting-edge cryptography, Coinbase is hiring!

Meet Kryptology: Coinbase’s Open Source Cryptography Library was originally published in The Coinbase Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.

Bitcoin & cryptocurrency news

Nearly one year in: Leading the herd at Coinbase

By Aaron Henshaw, Head of Coinbase Cloud Engineering

It’s no secret that crypto is gaining mainstream appeal, with the global crypto market cap reaching an all-time high of $3 trillion for the first time, the total value locked in DeFi reaching $250 billion, and 16% of Americans investing in, trading, or otherwise using cryptocurrency in the past year. A growing number of the world’s largest companies are looking to integrate crypto into their applications. Recently, we’ve seen Stripe, Square, Reddit, the NBA and others introducing crypto into their product lines with no signs of this trend slowing down. They all have one thing in common: a need for infrastructure and tools to operate and participate in the ecosystem.

Coinbase Cloud is committed to empowering current and future builders of the cryptoeconomy. Part of this will be building a platform that allows developers to access a suite of primitives like trading, storing, blockchain data access, and staking services. Our vision is to unleash a wave of innovation by offering turnkey solutions, enabling the innovators of tomorrow to do what they do best: build.

Joining Forces

In January 2021, Coinbase welcomed Bison Trails to become the foundational team and platform of Coinbase Cloud. By joining forces, we could accelerate our combined mission of creating a platform for the next wave of blockchain developers and provide a space to learn, participate, and build for the future of crypto.

As the founders of Bison Trails, Joe Lallouz and I saw this as an opportunity to build something bigger than Bison Trails and more expansive for Coinbase. Coinbase’s commitment to being crypto-first undoubtedly contributed to a seamless transition for our team.

The successful transition was also made possible by the support of the Coinbase leadership team, which has been committed to bringing blockchain infrastructure to the masses, as well as making this a great place for founders like Joe and I to continue building and realizing the vision that we set out to accomplish.

As crypto becomes ubiquitous, the products and services of the Web3 era will need to be powered by reliable and secure infrastructure. Coinbase sees this opportunity and is deeply committed to both our success and the growth of the crypto ecosystem.

The Momentum

Crypto infrastructure has been the bread and butter of Bison Trails since its founding. Its infrastructure platform and products are now the foundation of the Coinbase Cloud platform and suite of developer offerings, to equip the next generation of builders with even more powerful solutions.

We power some of the world’s top custodians, exchanges, funds, dapps and token holders. We are building an industry-leading platform for anyone to participate in blockchains (e.g. Celo Validators Groups, Polkadot Validators, eth2 Validators, including helping power Coinbase’s eth2 staking). We also provide reliable infrastructure for read/write data access, empowering the developers of tomorrow to build innovative crypto products and services, scale across blockchains, gain insights into network trends, and more. This frees our customers from having to invest time and resources into developing the necessary engineering, protocol, DevOps, or security competencies to do so reliably in-house.

We are also taking network participation to the next level by engaging deeply with protocol teams. For example, we’ve worked with Solana Foundation and the NEAR council, and supported the Keanu merger, among others.

Let’s take a look at our progress so far:

  • $30B+ in assets on platform¹ staked across more than 25 protocols as of November 2021
  • 60,000+ nodes across our Participate, Delegate, and Query & Transact products
  • Doubling the team size, including expanding our dedicated security team
  • 30+ protocols supported for our read/write infrastructure product, Query & Transact. This includes adding support for global distribution across three cloud providers, and multi-user API key management with rate-limiting options to our customers.
  • Powering features and cross-platform integrations for highly scaled Coinbase products, such as custody integrations for Institutional and eth2 staking for Retail

These metrics are crucial. They measure our impact on the communities we support. Unlike passive custody, assets that are staked are actively used to secure the underlying protocols, making Coinbase Cloud the largest protector of stake-based protocols.

Given the role we play across 30+ protocols, we’ve invested in the security and operational excellence of both our platform and the broader ecosystem. For example, our double-signing protection capability for eth2 has greatly reduced the risk to our platform users of any equivocation or double signing events. It’s for these reasons that companies and ecosystem players like a16z, Current, and Turner Sports have chosen to work with Coinbase Cloud.

Trevor Marshall, CTO of Current, says “the secure, reliable infrastructure and network expertise Bison Trails (Coinbase Cloud) provides has been invaluable to making it possible for Current to be an early, active participant in Polkadot, Karura and Acala and build hybrid financial products that have the potential to improve the financial outcomes of even more people.”

Up Next

We are now preparing for the next phase. We see a future world where every developer, whether part of an early stage project or a leading financial institution, is in some way touching crypto networks. Coinbase Cloud will provide the tools and the platform they need to do that. Our mission is to empower the innovators and help accelerate the Web3 evolution. This is where the world of software is going and we’re excited to lead the herd.

¹The Bison Trails platform is non-custodial.

Nearly one year in: Leading the herd at Coinbase was originally published in The Coinbase Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.