Behind the dYdX V4 boom, in-depth analysis of DeFi leverage classification, application and security practices

IntermediateDec 13, 2023
This paper explores the diversity and application scenarios of DeFi leverage through dYdX V4, analyzes code level vulnerabilities, and puts forward the key security points of the leverage protocol.
Behind the dYdX V4 boom, in-depth analysis of DeFi leverage classification, application and security practices

An introduction to DeFi leverage

The recent launch of dYdX V4 has attracted a lot of attention and participation in the perpetual contract exchange. dYdX has successfully applied leveraged trading examples, and we should not only look forward to the great potential of dYdX V4, but also pay more attention to the safety of leveraged agreements. Next, we’ll use specific code analysis and examples to guide you through the different leverage strategies and security considerations.

What is leverage

In finance, leverage is a strategy that relies on borrowing money to increase the potential return on an investment. Simply put, investors or traders borrow money to amplify their exposure to specific types of assets, projects, or instruments far more than they can achieve by relying on their own capital alone. Often, through the use of leverage, investors are able to amplify their purchasing power in the market.

Leverage in DeFi trading

The use of leverage is one of the most important and common features of crypto asset trading. Shortly after the establishment of decentralized exchanges, trading using leverage became increasingly popular even though the crypto market was already showing high volatility.

As with traditional finance, traders use leverage either simply to borrow capital to increase their purchasing power, or to take advantage of various financial derivatives, such as futures and options.

The leverage ratio has also increased from 3x and 5x to over 100x. Higher leverage means higher risk, but as seen on most centralized exchanges, this is a risk aggressive traders seeking higher returns are willing to take as leveraged trading volume grows.

Detailed explanation of leverage classification

As far as DeFi is concerned, leveraged products are mainly divided into four types, and the mechanisms for generating leverage are different: leveraged lending, margin trading leverage, perpetual contract leverage, and leveraged tokens.

Leveraged borrowing

DeFi lending and lending is one of the earliest and largest DeFi applications. Giants such as MakerDAO, Compound, AAVE, and Venus are already operating in the market. The logic for obtaining leverage by borrowing crypto assets is simple.

For example, if you hold $10,000 in Ether (ETH) and are bullish, you can deposit your ETH as collateral into Compound, lend $5,000 in USDC, and then use that $5,000 USDC deal in exchange for another $5,000 in ETH. This way you’ll get 1.5 times leverage on ETH, and compared to your initial capital of $10,000, you’ll get $1.5 million in ETH exposure.

Similarly, if you’re bearish, you can choose to deposit stablecoins and lend ETH. If the price of ETH falls, you can buy ETH on the market at a lower price and pay off your debts.

Note that since you’ll be borrowing from a decentralized protocol, you may be liquidated if the value of the collateral falls or if the value of the asset you’re borrowing exceeds a certain threshold.

Margin trading leverage

With DeFi lending, you can do what you want with these digital assets. DeFi margin trading focuses more on increasing position size (increasing purchasing power) and is considered a true “leveraged position.” There is one important difference, however — while margin positions are still open, traders’ assets act as collateral for borrowed funds.

dYdX is a well-known decentralized margin trading platform that allows up to 5x leverage. In dYdX’s margin trading, traders use their own funds as collateral, magnify their original principal by several times, and use these amplified funds to invest on a larger scale.

Traders are required to pay interest fees and fees associated with the transaction. This position is not fictitious; it involves actual borrowing and buying/selling.

If the market moves in an unfavorable direction, the trader’s assets may not be able to fully repay the loan. To prevent this from happening, the agreement will liquidate your positions before a certain liquidation ratio is reached.

How does leverage change in margin trading——

Let’s say you’re bullish on ETH 3 times in margin trading, but you don’t want to adjust your exposure all the time.

You hold $100 in USDC and borrow another $200 in USDC to trade $300 in ETH to establish the ETH long position you need. The leverage level is $300/$100 = 3x.

If the price of ETH rises 20%, your profit would be 300 (1 +20%) -300 = $60. Your risk of being liquidated is lower, while the actual leverage level is reduced to 360/ (360-200) = 2.25x. In other words, you will automatically reduce your leverage when the price of ETH rises.

If the price of ETH falls 20%, your loss would be 300 (1-20%) -300 = -60 dollars. When it comes to liquidation, you’re in a more dangerous position, and the actual level of leverage is automatically increased to 240/ (240-200) = 6x. In other words, you rebalance your leverage when the price of ETH falls, which indicates that you are in a higher risk position than before.

Therefore, while you might think that you can maintain constant leverage by trading on a fixed 3x margin, real-time leverage is constantly changing. Please check the chart below to see how leverage will change depending on price changes [1].

Perpetual contract leverage

Perpetual contracts are similar to traditional futures contracts, but they do not have an expiration date. Perpetual contracts mimic a margin-based spot market, so trading is close to the price of the underlying reference index.

There are many DeFi projects that provide perpetual contracts for traders, such as dYdX, MCDEX, Perpetual Protocol, Incomplete, etc. Many traders may find it difficult to tell the difference between margin trading and perpetual contracts — in fact, they all involve user leverage.

However, there are some differences in leverage mechanisms, fees, and levels of leverage.

A perpetual contract is a derivative product that trades synthetic assets and has the characteristic of trading on margin. The price of the underlying asset is tracked in a synthetic manner, without the need to trade the actual underlying asset. However, margin trading involves actual borrowing and trading of actual crypto assets.

With the advent of perpetual contracts, the concept of funding rates emerged. The purpose is to keep the transaction price of a perpetual contract consistent with the underlying reference price. If the contract price is higher than the spot price, then the bulls will pay the shorts. In other words, traders need to constantly pay fees for borrowing.

The leverage in perpetual contracts is generally higher than that in margin trading, and can be as high as 100x. Liquidation and actual leverage mechanisms are the same as margin trading.

Leveraged Tokens

Leveraged tokens are derivatives that provide holders with leveraged exposure to the cryptocurrency market without having to worry about actively managing leveraged positions. While they provide holders with leverage exposure, they don’t require them to deal with margin, liquidation, collateral, or funding rates.

The biggest difference between leveraged tokens and margin trading/perpetual contracts is that leveraged tokens will be rebalanced periodically or when a certain threshold is reached to maintain a specific level of leverage.

This is clearly different from margin trading and perpetual contracts — the actual leverage of these products is constantly changing according to price fluctuations, even if the trader may initially specify a level of leverage.

Let’s take a look at how the rebalancing works in the 3x ETH example above:

You hold $100 of USDC and buy an ETHBULL (3x) leveraged token. The protocol will automatically borrow $200 in USDC and trade $200 in ETH.

Assume that the price of ETH has risen 20%, while the ETHBULL (3x) token price rises to 300* (1 +20%) -200 = $160 before rebalancing. Your actual leverage is now 2.25 (360/160), below your target leverage.

As part of the rebalancing process, the protocol will borrow more dollars from the stablecoin pool and buy additional ETH tokens to bring leverage back to 3x. In our example, the protocol would borrow an additional $120 and exchange it for ETH. Thus, the total leverage again becomes (360+120) /160 = 3 times.

Assume that the price of ETH has fallen 20%, while the price of the ETHBULL (3x) token falls to 300* (1-20%) -200 = $40 before rebalancing. Your actual leverage will now be 6 (240/40), above your target leverage.

In this case, the agreement would sell ETH tokens and repay outstanding debts to reduce leverage. In this example, the protocol would sell $120 in ETH to pay the pool. The debt will become $80, and the total leverage will once again be (240-120) /40 = 3x.

In other words, leveraged tokens will be automatically re-leveraged in profits and deleveraged in losses to restore their target level of leverage. If this mechanism works well, even in adverse market trends, leveraged token holders will not be liquidated because the deleveraging mechanism will continuously reduce the effective leverage level of users.

As a result, the lending pool in the leveraged token model will be exempt from the risk of liquidation and is more secure than the borrowing pool in margin trading.

Leverage application examples

Now that we’ve learned about some common DeFi protocol types of leverage, let’s discuss the application of leverage in detail in relation to specific DeFi protocols.

GMX

GMX [2] is a decentralized spot and perpetual exchange that offers traders the ability to trade assets with up to 50 times leverage. The agreement currently runs on Arbitrum and Avalanche. On GMX, traders are fully aware of their counterparty’s situation, which is completely different from trading on CEX. Unlike other perpetual contract agreements such as dYdX, GMX operates entirely on-chain and uses AMM functionality to enable leveraged trading.

What sets GMX apart from other services is that it is a decentralized exchange that provides leveraged trading services. In this regard, it combines an experience similar to other DeFi exchanges such as Uniswap with leveraged trading services offered by Binance and others.

GMX has a liquidity pool GLP, which is a multi-asset pool that provides liquidity for margin trading: users can go long/short and execute trades by minting and destroying GLP tokens. The pool earns LP fees from trades and leveraged trades, which are distributed to GMX and GLP holders.

To trade with leverage, traders deposit collateral into an agreement. Traders can choose leverage of up to 50x. The higher the leverage, the higher the liquidation price, which will gradually increase as borrowing costs increase.

For example, when going long on ETH, traders are “leasing” the upward space of ETH from the GLP pool; when shorting ETH, traders are “renting” the upward space of stablecoins against ETH from the GLP pool. However, the assets in the GLP pool are not actually leased out.

When closing a position, if the trader bets right, profits will be paid in the form of increasing tokens from the GLP pool; otherwise, losses will be deducted from collateral and paid into the pool. GLP profits from traders’ losses and profits from traders’ profits.

In the process, traders pay transaction fees, opening/closing fees, and borrowing fees in exchange for upward space to long/short specified tokens (BTC, ETH, AVAX, UNI, and LINK) against the US dollar.

Merkle Trade

Merkle Trade [3] is a decentralized trading platform that offers cryptocurrency, forex, and commodities trading with up to 1,000x leverage and advanced user-centric trading features. Merkle Trade is powered by the Aptos blockchain and has first-class performance and scalability. Compared to Gains Network, which offers the same high leverage, it has lower transaction delays and fees.

Unlike most exchanges, there is no order book on Merkle Trade. Instead, Merkle LP acts as a counterparty to every trade, and when traders lose money, it takes collateral and pays out profits on closed trades with positive returns.

  • Trade cryptocurrencies, forex, and commodities with up to 1,000x leverage

Merkle Trade was designed from the outset to offer a wide range of trading pairs, including cryptocurrencies, forex, and commodities, and some of the highest leverage on the market; up to 150x on cryptocurrency and up to 1,000x on forex.

  • Fair price order execution, millisecond latency, minimal slippage

Generating blockchain with Aptos, which has the lowest latency to date, can provide the fastest on-chain transaction experience. For traders, this means a quicker trading experience and less price slippage due to execution delays.

  • Decentralized, non-custodial transactions with no counterparty risk

Traders trade with a liquidity pool (Merkle LP), which acts as a counterparty to every transaction on the agreement. All transactions and settlements are executed by smart contracts, and there is no hosting of user funds at any time.

  • Lowest processing fee

Merkle Trade claims to have one of the lowest fees in the market to date. At launch, fees for cryptocurrency trading pairs were as low as 0.05%, and fees for forex trading pairs were as low as 0.0075%.

DYDX

DYDX

dYdX [4] is a decentralized exchange (DEX) that empowers users to efficiently trade perpetual contracts while having full control over assets. Since its launch in 2021, dYdX V3 has adopted a unique non-custodial second-tier scaling solution to implement its exchange, yet its order book and matchmaking engine are still managed centrally.

Now, with dYdX V4, the protocol is growing into its own chain, and the entire protocol is being completely restructured to achieve complete decentralization while increasing throughput. dYdX also includes three functions: lending, leveraged trading, and perpetual contracts. Leveraged trading comes with a borrowing function. The funds deposited by users automatically form a fund pool. If there is insufficient capital during trading, interest is automatically borrowed and paid.

Leverage safety analysis

We have introduced the common types and applications of leverage in DeFi. Also, there are still many security issues in the design of leverage that deserve our attention. We will analyze the security issues and audit points of DeFi leverage based on specific audit cases.

Distinguish between limit orders and market orders

In most leveraged exchange applications, there are limit orders and market orders. Strict differentiation and verification of limit orders and market orders is very necessary. Next, we will conduct a detailed analysis of the issues we found in the Merkle Trade audit [5].

let now = timestamp: :now_seconds ();
 if (now - order.created_timestamp > 30) {
         cancel_order_internal<PairType, CollateralType>(
             _order_id,
             order,
             T_CANCEL_ORDER_EXPIRED
         );
         return
     };

This part of the code performs the checks in the order function, where it checks whether it has been more than 30 seconds since the order was created. If the conditions are met, call cancel_order_internal () to cancel the order. However, if the order is a limit order, it means that the order has a specific price set by the trader and they are willing to buy or sell the asset at that price. There should be no such judgment when executing limit orders; this may cause most limit orders to not be executed. Therefore, it is important to strictly differentiate the trading logic between limit orders and market orders.

Leverage calculation error

Calculation errors have always been a very common problem in DeFi, and they are also particularly common in leverage. We will use the issues discovered by the Unstoppable [6] protocol in third-party audits to thoroughly examine the calculation issues of leverage.

Let’s look at the code for calculating leverage in Unstoppable:

def _calculate_calculation (
 _position_value: uint256, _debt_value: uint256, _margin_value: uint256
) - > uint256:
 if _position_value < = _debt_value:
 #bad debt
 Return max_value (uint256)

 Return (
 precision
 * (_debt_value + _margin_value)
 /(_position_value - _debt_value)
 /PRECISION
 )

The _calculate_margin function caused the leverage to be calculated incorrectly by using _debt_value + _margin_value as the numerator rather than the _position_value. The function’s three input parameters _position_value, _debt_value, and _margin_value are all determined by price information provided by Chainlink’s on-chain oracles. Here, _debt_value indicates the value of converting the position’s debt share into the dollar debt amount. _margin_value indicates the current value of the position’s initial margin amount (in US dollars). _position_value indicates the current value (in US dollars) of the initial position amount of the position.

The problem with the above calculation is that _debt_value + _margin_value does not represent the value of the position. Leverage is the ratio between the current position value and the current margin value. _position_value - _debt_value is correct. It indicates the current margin value, but _debt_value + _margin_value does not represent the current value of the position, because there is no guarantee that debt tokens and position tokens have related price fluctuations.

For example, the debt token is ETH, and the position token is BTC.

Alice uses 1 ETH as margin, borrows 14 ETH ($2,000 each), and gets 1 BTC ($30,000 each) in position tokens. Leverage is 14.

The next day, the price of ETH remained at $2,000/ETH, but the price of BTC fell from $30,000/BTC to $29,000/BTC. At this point, the leverage should be (_position_value == 29,000)/(_position_value == 29,000 - _debt_value == 28,000) = 29, not the value calculated in the contract: (_debt_value == 28,000 + _margin_value == 2,000)/(_position_value == 29,000 - _debt_value == 28,000) = 30.

Therefore, in order to fix this, the correct formula mentioned above should be used to calculate leverage in smart contracts. A miscalculation of leverage can lead to unfair liquidations or excessively leveraged positions in the face of price fluctuations.

In smart contracts, ensuring proper leverage calculation is critical to maintaining the robustness of the system and the interests of users. The correct calculation of leverage should be based on the ratio between the current value of the position and the current margin value. If the wrong calculation formula is used, it may cause the system to react improperly to price changes, may liquidate positions that should not be liquidated, or allow excessively leveraged positions to continue to exist, thus increasing the risk of the system and users.

Logical errors

Logic error

Logic errors require particular attention in smart contract audits, particularly in complex logic such as DeFi leveraged trading.

Let’s discuss the logical issues to be aware of in DeFi leverage using issues discovered by Tigris [7] (Tigris, a decentralized synthetic leverage trading platform based on Arbitrum and Polygon) in a third-party audit.

Let’s take a look at the logic of the price limit closing function in Tigris:

Function limitClose (
 uint _id,
 bool _tp,
 priceData calldata _priceData,
 Bytes calldata _signature
)
 external
{
   _checkDelay(_id, false);
   (uint _limitPrice, address _tigAsset) = tradingExtension._limitClose(_id, _tp, _priceData, _signature);
   _closePosition(_id, DIVISION_CONSTANT, _limitPrice, address(0), _tigAsset, true);
}

function _limitClose (
 uint _id,
 bool _tp,
 priceData calldata _priceData,
 Bytes calldata _signature
) external view returns (uint _limitPrice, address _TIGAsset) {
 _checkGas ();

 iPosition.trade memory _trade = position.trades (_id);
   _tigAsset = _trade.tigAsset;
   getVerifiedPrice (_trade.asset, _priceData, _signature, 0);
 uint256 _price = _priceData.price;
   if (_trade.orderType! = 0) revert (" 4 "); //isLimit
 if (_tp) {
 if (_trade.tpPrice == 0) revert (" 7 "); //limitNotSet
 if (_trade.direction) {
           if (_trade.tpPrice > _price) revert("6"); //LimitNotMet
       } else {
           if (_trade.tpPrice < _price) revert("6"); //LimitNotMet
       }
 _limitPrice = _trade.tpPrice;
   } else {
 if (_trade.slprice == 0) revert (" 7 "); //limitNotSet
 if (_trade.direction) {
           if (_trade.slPrice < _price) revert("6"); //LimitNotMet
       } else {
           if (_trade.slPrice > _price) revert("6"); //LimitNotMet
       }
 //@audit stop loss is closed at user specified price NOT market price
 _limitPrice = _trade.slprice;
   }
}

When using stop-loss to close a position, the user’s closing price is the stop-loss price set by the user, not the current price of the asset. In the case of directional markets and high leverage, users may abuse this to achieve almost risk-free trades. Users can open a long position and set a stop-loss price that is $0.01 lower than the current price.

If the price drops immediately in the next update, they will close their position at their entry price and only pay the opening and closing fees. If prices rise, they are likely to earn a lot of money. As a result, users can misuse stop-loss pricing methods to open trades with high leverage, high upside potential, and low downside risk.

Price fluctuations

Price Tubs

The impact of price fluctuations on DeFi leverage is very important. Only by always considering price fluctuations can we ensure the safety of leverage agreements. Let’s use the DeFiner [8] protocol as an example for an in-depth analysis of the issues discovered in a third-party audit:

The DeFiner protocol undergoes two checks before processing withdrawals.

First, the method checks whether the amount requested by the user to withdraw exceeds the balance of that asset:

function authorization (address _accountAddr, address _token, uint256 _amount) external onlyAuthorized returns (uint256) {

 //Check if enough amount is less than user's balance
 require (_amount < = getDepositBalanceCurrent (_token, _accountAddr), " Earned balance. ");
   uint256 borrowLtv = globalConfig.tokenInfoLogistry () .getBorrowLtv (_token);

Second, the method checks whether withdrawals will make the user’s leverage ratio too high. The amount withdrawn will be subtracted from “ borrow power “ of the user’s current price. If the user’s total borrowing value exceeds the new borrow power, the method fails because the user no longer has enough collateral to support their borrowing position. However, this requirement will only be checked if the user hasn’t been overly leveraged:

if (getBorrowEth (_accountAddr) < = getBorrowPower (_accountAddr))
 require (
 getBorrowEth (_accountAddr) < = getBorrowPower (_accountAddr) .sub (
           _amount.mul (globalConfig.tokenInfoRegistry () .priceFromAddress (_token))
 .mul (borrowLtv) .div (utils.getDivisor (address (globalConfig), _token)) .div (100)
       ), " Colloquium Collège when ");

If users have borrowed more than their “ borrow power “ allows, they can withdraw money regardless. This can happen in a number of situations, the most common being price fluctuations. The agreement did not consider the impact of price fluctuations on the agreement, which caused this problem.

Others

In addition to the effects of not distinguishing between limit orders and market orders, calculation errors, logic errors, and price fluctuations mentioned above, there are many safety points related to leverage agreements that require our attention. This includes, but is not limited to, issues such as flash loan attacks, price manipulation, prophet security, authority control, insufficient leverage checks, or lack of checks. These factors must be carefully considered when designing and implementing leverage agreements to ensure the robustness of the agreement and the safety of user assets. Preventive measures, real-time monitoring, and emergency response plans are also key to reduce potential risks and protect user interests.

summed

Conclusion

The introduction of leveraged trading in DeFi protocols has indeed provided the market with greater maneuverability, while also bringing more complex trading mechanisms. Although leveraged trading provides users with more investment opportunities, its potential risks and challenges to protocol security have also become more significant.

As leverage increases, the operation of agreements becomes more flexible, but as a result, they become more vulnerable and more vulnerable to various security threats. This includes the potential failure to make a strict distinction between limit orders and market orders, calculation errors, logic errors, and extreme sensitivity to factors such as price fluctuations. In this case, we must pay more attention to the security of the protocol to ensure that users’ assets are effectively protected.

As a leading blockchain security team in the Web3 field, ScaleBit is distributed in Silicon Valley, Singapore, Hong Kong, Taiwan, etc. We have provided blockchain security solutions to 200+ institutions and projects in the global Web3 sector, accumulated 180,000+ lines of audit code, and protected more than $8 billion in user assets. Make Security Accessible for All! If you have any security audit needs, please feel free to contact us. We will tailor detailed, comprehensive, and professional security solutions for you to protect you and the Web3 field safely!

Disclaimer:

  1. This article has been reprinted from [ScaleBit] and the copyright belongs to the original author [Polaris]. If you have any objections to the reprint, please contact the Gate Learn team, and the team will deal with it as soon as possible according to the relevant procedures.

  2. Disclaimer: The views and opinions expressed in this article only represent the author’s personal opinions and do not constitute any investment advice.

  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

Start Now
Sign up and get a
$100
Voucher!
Create Account