Compound v2 DeFi Integration Tips

We continue our series of instructive articles with some special recommendations for developers using Compound v2 DeFi integration!

We also intend to discuss the history of the recent Compound III and contrast it with earlier iterations in this article.

Let’s get started!

Greetings dear readers!

In this article, we present tips that we have acquired over the years of auditing similar integrations.

First things first, we would like to express our heartfelt gratitude to the Compound designers, community, everyone who supports it, the authors of all resource materials, and, of course, our in-team auditors who have assisted us by providing much-needed information and breaking the veil of secrecy!

You will also find a list of tools and research for self-study, and we strongly recommend that you read it separately for better understanding!

By the way, here are some vacant slots so if your project needs an audit — feel free to write to us, visit our public reports page here!

Let’s get in touch: gm@pessimistic.io!

Make sure to read the rest of the series:


I - Let's Get Started

Looking at this month’s never-ending hacks, one may wonder why they happen so frequently.

Have audit firms actually gotten worse at what they do???

This, in our opinion, is not the case; yet, the topic is rather tricky because, in certain ways, you can reduce the risks to yourself and your project! By the way, we are working on such a solution within the team and hope to deliver it shortly:

We believe there is no one who doubts that the basis of any secure integration is a special approach to writing code. Consequently, this article will be focused only on those aspects that can be really useful for making your code safe and secure.

Therefore, below you will see not a typical article but a systematization of knowledge (SoK), in which I will rely on authors that I myself trust in this matter and, of course, our pessimistic.io auditors.

This is what we’ll cover in this post about using Compound v2 in your project! In this article, we also plan to go over the background of the most recent Compound III and compare it to earlier iterations!


II - Compound Walkthrough

Founded in 2018 by Robert Leshner, Compound is an algorithmic money market protocol which establishes money markets with algorithmically set interest rates based on supply and demand, allowing users to frictionlessly exchange the time value of supported assets.

Let’s see how the project has improved over time and what the main features of each version are!

Compound VS Compound v2 VS Compound III

The Compound protocol has been reviewed & audited by Trail of Bits and OpenZeppelin. Check out this page.

Compound “v1” had a monolithic structure in which all tokens were stored in a single contract, making it a rigid system, while the Compound v2 architecture was too risky, because one bad asset could theoretically drain the whole protocol, which in turn could turn into a “Black Swan Event” for the protocol — in other words, a death spiral.

More information on the Compound v2 architecture can be found here:

Under the old model, users deposited assets into lending pools, where interest accrued on their positions. In exchange for their deposits, lenders (users) received cTokens, which represented the value of their deposit.

This repo demonstrates the most common interactions with Compound V2. Check out for more info: uncategorized specifications.

Using these cTokens, the lender (user) could borrow up to a certain percentage of the value of their pledged assets in another cryptocurrency.

Compound III

Compound III was publicly announced on June 29, 2022 after releasing their new multi-chain strategy to the public. This strategy is based on the ability for its own Compound Chain to deploy and run the Compound Protocol on all EVM compatible chains.

As Robert Leshner said: ‘Compound III is a streamlined version of the protocol, with an emphasis on security, capital efficiency, and user experience. Complexity wasn’t added — it was removed.’

According to Robert Leshner, the most profound change in Compound III was to move away from a pooled-risk model, where users can borrow any asset. In this model (which Compound pioneered) collateral is constantly rehypothecated. A single bad asset (or oracle update) can drain all assets from the protocol.

Compound III uses a certain number of tokens, so even if one asset goes to zero, there is little risk to the other assets of the protocol users. Compound III is also controlled & owned by the community!

Instead, each deployment of Compound III features a single borrowable asset. When you supply collateral, it remains your property. It can never be withdrawn by other users (except during liquidation). Capital efficiency increases too — collateral is more “useful” when you know which asset is being borrowed ahead of time.

More information on the Compound III current state can be found here:

Comet

The deployment strategy is called comet, and it essentially is a money market protocol for Ethereum and compatible chains. The Comet protocol revolves around a set of smart contracts that implement Comet’s core functionality!

The CometMainInterface.sol interface defines this. An extra set of functions that do not fit within the main Comet.sol contract can be found in the CometExt.sol contract, which Comet.sol delegates via DELEGATECALL for unrecognized function signatures.

Compound III was audited by OpenZeppelin and ChainSecurity, and formally verified in partnership with Certora.

Additionally, Comet comes with a number of configurator and supplementary contracts that let users call multiple functions at once or claim rewards for participating in the protocol.

More information about it’’s specifications can be found here, much thanks to FearsomeLamb789 for an awesome research made!


III - We Recommend

We chose to conduct a thorough analysis of Compound v2 because it is the version of the protocol that integrations use the most frequently, as evidenced by its TVL.

We hope to inform you of the checks pertaining to Compound III integration in the upcoming articles as well!

Following the tips below can significantly improve the security of your project’s integration, so you should always keep them in mind!

Compound v2 Audit Specifications & Integration Tips:

  • There are two types of cToken: cErc20 and cEther (for native Ether). Some functions may have different arguments! For example, for mint function: A) In cEther, amount is passed in msg.value; B) In cErc20 amount is passed in the parameter mintAmount;

  • For cToken, decimals equals 8 — all cTokens have 8 decimals, while the underlying token can vary. It is worth to keep this in mind when performing calculations;

  • Some functions return mantissa (scaled by 1e18), for example: suppyRatePerBlock, you should always check how the function returns the value;

  • In order to calculate the cTokenRate, perform the following:

exchangeRateCurrent = cToken.exchangeRateCurrent() // it is returned as mantissa (scaled by 1e18)
oneCTokenInUnderlying = exchangeRateCurrent / (1 * 10 ^ (18 + underlyingDecimals - cTokenDecimals) // we divide by 1e18 + decimal difference
  • Not every token can be used as a collateral. For some tokens collaterallFactor (you can get it from the comptroller) may be equal to zero. Also, keep in mind that compound admin has the ability to change the collaterallFactor of any token;

  • Compound functions may return errorCode (uint type, 0NO_ERROR). In previous versions, the transaction did not revert, but in the updated v2, it reverts or returns NO_ERROR. But you should always make sure that Compound functions will not fail without reverting!;

  • The cToken can be transferred, but the protocol will not let this happen if after the transfer the accountLiqudity < 0 (the user does not have enough collateral to cover all the loans);

  • When supplying tokens, you have to check if there is an approve given;

  • The number of underLying tokens per сToken may increase over time! Each cToken will increase its value on a (almost) per block basis due to the interests earned. You can use the cToken as collateral to borrow funds. You can also use it in other markets (it is an ERC20 compatible token).

  • TUSD, USDC, USDT — are hardcoded as $1;

  • Compound uses chainlink as a price feed, it also verifies data via a TWAP oracle from the Uniswap;

  • Users are rewarded with COMP tokens for interaction with the protocol. You should always make sure that the contract that works with Compound has a built-in functionality that allows these tokens to be claimed.

  • Carefully study the Comptroller, you can find it here. The Comptroller is architected as an upgradable proxy, the name of the actual proxy is named the “Unitroller”, you can find the contract’s code here.

cTokens Specifications:


IV - Resources

General:

Learning Materials:

Compound Audit Practice:

Research Papers:


We hope that this article was informative and useful for you! Thank you for reading!

What instruments should we review? What would you be interested in reading about?

By the way, here are some vacant slots in the first quarter of 2023 now so if your project needs an audit — feel free to write to us, visit our public reports page here!


Support is very important to me, with it I can do what I love — educating users!

If you want to support my work, you can send me a donation to the address:

Stay safe!

Subscribe to Officer's Blog
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.