The recent launch of dYdX V4 has ignited significant interest and participation in perpetual futures exchanges. While dYdX stands as a successful example of applied leverage trading, it is crucial to look beyond its potential and focus on the foundational security of leverage protocols. This article will guide you through different leverage strategies and critical safety considerations, complete with practical code analysis and examples.
What Is Leverage?
In finance, leverage is a strategy that relies on borrowing funds to amplify the potential returns of an investment. In simple terms, an investor or trader borrows money to gain exposure to a specific asset, project, or instrument far beyond what their own capital would allow. Typically, using leverage enables investors to magnify their purchasing power in the market.
Leverage in DeFi Trading
The use of leverage is one of the most important and common features in crypto asset trading. Shortly after the establishment of decentralized exchanges (DEXs), leveraged trading grew increasingly popular, despite the crypto market's inherent high volatility.
As in traditional finance, traders use leverage either to borrow funds to increase their buying power or to utilize various financial derivatives like futures and options.
Leverage ratios have expanded from 3x and 5x to over 100x. Higher leverage entails higher risk, but as seen on most centralized exchanges, the growing volume of leveraged trading indicates that aggressive traders are willing to take on this risk in pursuit of greater returns.
A Detailed Breakdown of Leverage Types
In the DeFi space, leverage products are primarily categorized into four distinct types, each with a different mechanism for generating leverage: leveraged lending, margin trading leverage, perpetual futures leverage, and leveraged tokens.
Leveraged Lending
DeFi lending and borrowing is one of the earliest and largest DeFi applications, with established giants like MakerDAO, Compound, AAVE, and Venus operating in the market. The logic behind borrowing crypto assets to gain leverage is straightforward.
For example, if you hold $10,000 in Ethereum (ETH) and are bullish, you could deposit your ETH as collateral into Compound, borrow $5,000 in USDC, and then use that USDC to acquire an additional $5,000 worth of ETH. This gives you 1.5x leverage on ETH, providing $15,000 of exposure compared to your initial $10,000 capital.
Similarly, if you are bearish, you could choose to deposit a stablecoin and borrow ETH. If the price of ETH falls, you can repurchase ETH at a lower market price to repay your debt.
It is important to note that because you are borrowing from a decentralized protocol, you could face liquidation if the value of your collateral drops or the value of the borrowed asset exceeds a certain threshold.
Margin Trading Leverage
With DeFi lending, you can do whatever you wish with the borrowed digital assets. DeFi margin trading is more focused on increasing position size (increasing buying power) and is considered a true "leveraged position." However, there is a key distinction—while a margin position remains open, the trader's assets act as collateral for the borrowed funds.
dYdX is a well-known decentralized margin trading platform that allows leverage of up to 5x. In dYdX's margin trading, traders use their own funds as collateral, magnify their original principal several times over, and use these amplified funds for larger-scale investments.
Traders must pay interest fees as well as fees associated with the trades. The position is not virtually constructed; it involves actual borrowing and buying/selling.
If the market moves adversely, the trader's assets might not be sufficient to cover the borrowed amount. To prevent this, the protocol will liquidate your position once a certain liquidation ratio is reached.
Here is how leverage can change during margin trading:
Assume you are bullish on ETH with 3x leverage in a margin trade but do not wish to adjust your exposure constantly.
You hold $100 in USDC, borrow an additional $200 in USDC, and trade the total $300 for ETH to establish your desired long ETH position. The leverage level is $300 / $100 = 3x.
If the price of ETH increases by 20%, your profit would be $300 * (1 + 20%) - $300 = $60. Your risk of being liquidated is lower, and the actual leverage level decreases to $360 / ($360 - $200) = 2.25x. In other words, you automatically deleverage as the ETH price rises.
If the price of ETH decreases by 20%, your loss would be $300 * (1 - 20%) - $300 = -$60. You are in a more dangerous position regarding liquidation, and the actual leverage level automatically increases to $240 / ($240 - $200) = 6x. This indicates that you rebalance leverage as the ETH price falls, leaving you at a higher risk level than before.
Therefore, even though you might think a fixed 3x margin trade maintains constant leverage, real-time leverage is constantly changing.
Perpetual Futures Leverage
Perpetual futures contracts are similar to traditional futures contracts but have no expiration date. They mimic margin-based spot markets, so trading occurs close to the underlying reference index price.
Many DeFi projects offer perpetual contracts to traders, including dYdX, MCDEX, Perpetual Protocol, and Injective. Many traders might struggle to distinguish between margin trading and perpetual futures—both involve user leverage.
However, there are differences in the leverage mechanism, fees, and leverage levels.
A perpetual futures contract is a derivative product that trades synthetic assets with the characteristic of trading on margin. The tracking of the underlying asset's price is done synthetically, without the need to trade the actual asset. In contrast, margin trading involves actual borrowing and trading of real crypto assets.
With perpetual futures, the concept of funding rates emerged. Their purpose is to keep the trading price of perpetual contracts aligned with the underlying reference price. If the contract price is higher than the spot price, long positions pay short positions. In other words, traders must continuously pay fees for borrowing.
Leverage in perpetual futures is typically higher than in margin trading, reaching up to 100x. The liquidation and actual leverage mechanisms are the same as in margin trading.
Leveraged Tokens
Leveraged tokens are derivatives that provide holders with leveraged exposure to the cryptocurrency market without the need to actively manage a leveraged position. Although they offer leveraged exposure, they do not require holders to handle margin, liquidation, collateral, or funding rates.
The most significant difference between leveraged tokens and margin/perpetual trading is that leveraged tokens will rebalance periodically or when a certain threshold is reached to maintain a specific leverage level.
This is distinctly different from margin trading and perpetual futures—the actual leverage in these products constantly changes with price fluctuations, even if the trader initially specified a leverage level.
Let's examine how rebalancing works using the 3x ETH example from above:
You hold $100 in USDC and purchase an ETHBULL (3x) leveraged token. The protocol automatically borrows $200 in USDC and trades it for $200 worth of ETH.
Assume the price of ETH increases by 20%, and the ETHBULL (3x) token price rises to $300 * (1 + 20%) - $200 = $160 before rebalancing. Your actual leverage is now 2.25 ($360 / $160), which is below the target leverage.
As part of the rebalancing process, the protocol will borrow more dollars from the stablecoin pool and purchase additional ETH tokens to readjust the leverage back to 3x. In our example, the protocol would borrow an additional $120 and exchange it for ETH. The total leverage becomes ($360 + $120) / $160 = 3x again.
Assume the price of ETH decreases by 20%, and the ETHBULL (3x) token price drops to $300 * (1 - 20%) - $200 = $40 before rebalancing. Your actual leverage becomes 6 ($240 / $40), which is above the target leverage.
In this case, the protocol will sell ETH tokens and repay outstanding debt to reduce leverage. In this example, the protocol would sell $120 worth of ETH to pay the pool. The debt becomes $80, and the total leverage is again ($240 - $120) / $40 = 3x.
In other words, leveraged tokens automatically releverage in profit and deleverage in loss to return to their target leverage level. If this mechanism functions well, leveraged token holders will not face liquidation even in adverse market trends because the deleveraging mechanism continually reduces the user's effective leverage.
Therefore, the lending pool in the leveraged token model is free from liquidation risk and is safer than the lending pool in margin trading.
Leverage Application Case Studies
Having explored common types of DeFi leverage protocols, let's examine specific applications of leverage in practice.
GMX
GMX is a decentralized spot and perpetual exchange that provides traders with the ability to trade assets with leverage of up to 50x. The protocol currently operates on Arbitrum and Avalanche. On GMX, traders are fully informed about their counterparty, which is entirely different from trading on a CEX. Unlike other perpetual protocols like dYdX, GMX operates fully on-chain and uses AMM functionality to enable leveraged trading.
GMX differentiates itself by being a decentralized exchange that offers leveraged trading services. In this regard, it combines the experience of other DeFi exchanges like Uniswap with the leveraged trading services offered by platforms like Binance.
GMX features a liquidity pool called GLP, which is a multi-asset pool that provides liquidity for margin trading: users can go long/short and execute trades by minting and burning GLP tokens. The pool earns LP fees from trading and leveraged trading, which are distributed to GMX and GLP holders.
To engage in leveraged trading, traders deposit collateral into the protocol. Traders can choose leverage of up to 50x; higher leverage results in a higher liquidation price, which gradually increases as borrowing costs accumulate.
For example, when going long on ETH, the trader is "renting" the upside of ETH from the GLP pool; when shorting ETH, the trader is "renting" the stablecoin's upside relative to ETH's rise. However, the assets in the GLP pool are not actually rented out.
When a position is closed, if the trader is correct, profits are paid from the GLP pool in the token that was longed; otherwise, losses are deducted from the collateral and paid into the pool. GLP profits from traders' losses and loses from traders' profits.
Throughout this process, traders pay trading fees, open/close position fees, and borrowing fees in exchange for exposure to the upside of going long/short on specified tokens (BTC, ETH, AVAX, UNI, and LINK) against the dollar.
Merkle Trade
Merkle Trade is a decentralized trading platform offering cryptocurrency, forex, and commodity trading with leverage of up to 1,000x, along with user-centric advanced trading features. Powered by the Aptos blockchain, Merkle Trade boasts first-class performance and scalability. Compared to Gains Network, which offers similarly high leverage, Merkle Trade features lower transaction latency and fees.
Unlike most exchanges, Merkle Trade does not have an order book. Instead, Merkle LP acts as the counterparty for every trade, collecting collateral when traders lose and paying out profits on closed trades with positive returns.
- Trade cryptocurrencies, forex, and commodities with leverage up to 1,000x: Merkle Trade is designed to offer a wide range of trading pairs from the outset, including cryptocurrencies, forex, and commodities, with some of the highest leverage in the market—up to 150x on cryptocurrencies and 1,000x on forex.
- Fair-price order execution, millisecond latency, minimal slippage: Leveraging the ultra-low latency of the Aptos blockchain, it provides one of the fastest on-chain trading experiences. For traders, this means quicker trade execution and less price slippage due to execution delays.
- Decentralized, non-custodial trading with no counterparty risk: Traders interact with a liquidity pool (Merkle LP), which acts as the counterparty for every trade on the protocol. All trades and settlements are executed by smart contracts, with no custody of user funds at any point.
- Lowest fees: Merkle Trade claims to have some of the lowest fees in the market. At launch, fees are as low as 0.05% for cryptocurrency pairs and 0.0075% for forex pairs.
dYdX
dYdX is a decentralized exchange (DEX) that empowers users to trade perpetual contracts efficiently while maintaining full control of their assets. Since its launch in 2021, dYdX V3 employed a unique non-custodial Layer 2 scaling solution for its exchange, but its order book and matching engine remained centrally managed.
Now, with dYdX V4, the protocol is evolving into its own chain and undergoing a complete overhaul to achieve full decentralization while improving throughput. dYdX incorporates three functionalities: lending, leveraged trading, and perpetual contracts. Leveraged trading includes a built-in lending feature; user-deposited funds automatically form a capital pool, and if funds are insufficient during trading, they are borrowed automatically with interest payments.
Leverage Security Analysis
Having introduced common types and applications of leverage in DeFi, it's important to note that many security issues still exist in the design of leverage systems. We will analyze DeFi leverage security problems and audit points using specific audit case studies.
Distinguishing Between Limit and Market Orders
In most leveraged exchange applications, both limit and market orders exist. Strictly distinguishing between and validating these order types is essential. We will use an issue discovered during a Merkle Trade audit to provide a detailed analysis.
let now = timestamp::now_seconds();
if (now - order.created_timestamp > 30) {
cancel_order_internal (
_order_id,
order,
T_CANCEL_ORDER_EXPIRED
);
return
};
This code segment is part of the order execution function's validation checks. It checks whether more than 30 seconds have passed since the order was created. If the condition is met, it calls cancel_order_internal() to cancel the order. However, if the order is a limit order—meaning it has a specific price set by the trader at which they are willing to buy or sell an asset—this check should not apply. This could prevent most limit orders from being executed. Therefore, it is crucial to strictly separate the trading logic for limit and market orders.
Leverage Calculation Errors
Calculation errors are a common issue in DeFi, especially in leverage systems. We will examine a problem found in a third-party audit of the Unstoppable protocol to delve deeper into leverage calculation issues.
Consider the code for calculating leverage in Unstoppable:
def _calculate_leverage(
_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_leverage function incorrectly calculates leverage by using _debt_value + _margin_value as the numerator instead of _position_value. The three input parameters—_position_value, _debt_value, and _margin_value—are all determined by price information from Chainlink's on-chain oracle. Here, _debt_value represents the value of converting the position's debt share into a USD debt amount. _margin_value represents the current value (in USD) of the position's initial margin amount. _position_value represents the current value (in USD) of the position's initial position amount.
The problem with the above calculation is that _debt_value + _margin_value does not represent the position's value. Leverage is the ratio between the current position value and the current margin value. _position_value - _debt_value is correct, as it represents the current margin value. However, _debt_value + _margin_value does not represent the position's current value because there is no guarantee that the debt token and the position token have correlated price movements.
Example: Debt token is ETH, position token is BTC.
Alice uses 1 ETH as margin (worth $2,000), borrows 14 ETH (each worth $2,000), and acquires a position of 1 BTC (worth $30,000). The leverage is 14.
The next day, the price of ETH remains $2,000, but the price of BTC falls from $30,000 to $29,000. The leverage should now be (_position_value == $29,000) / (_position_value == $29,000 - _debt_value == $28,000) = 29, not the value calculated by the contract: (_debt_value == $28,000 + _margin_value == $2,000) / (_position_value == $29,000 - _debt_value == $28,000) = 30.
Therefore, to fix this issue, the correct formula mentioned above should be used to calculate leverage in the smart contract. Incorrect leverage calculation can lead to unfair liquidations or over-leveraged positions during price volatility.
In smart contracts, ensuring accurate leverage calculation is vital for maintaining system robustness and protecting user interests. Correct leverage calculation should be based on the ratio between the current value of the position and the current value of the margin. Using an incorrect formula can cause the system to react inappropriately to price changes, potentially liquidating positions that shouldn't be liquidated or allowing over-leveraged positions to persist, thereby increasing risk for both the system and its users.
Logic Errors
Logic errors require particular attention in smart contract audits, especially in complex systems like DeFi leverage trading.
Let's use an issue found in a third-party audit of Tigris (a decentralized synthetic leverage trading platform on Arbitrum and Polygon) to discuss logical problems in DeFi leverage.
Examine the limit close function logic 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 closing a position using a stop-loss, the user's closing price is their set stop-loss price, not the asset's current market price. In directional markets with high leverage, users could potentially abuse this feature to execute almost risk-free trades. A user could open a long position and set a stop-loss price just $0.01 below the current price.
If the price drops immediately in the next update, they would close the position at their entry price, paying only the open and close fees. If the price rises, they stand to make significant gains. This allows users to abuse the stop-loss price setting mechanism to open high-leverage trades with substantial upside potential and minimal downside risk.
Price Volatility
The impact of price volatility on DeFi leverage is significant. Continuously accounting for price fluctuations is essential to ensure the security of leverage protocols. Let's use an issue discovered in a third-party audit of the DeFiner protocol as an example for in-depth analysis:
The DeFiner protocol performs two checks before processing a withdrawal.
First, the method checks if the amount the user requests to withdraw exceeds the balance of that asset:
function withdraw(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized returns(uint256) {
// Check if withdraw amount is less than user's balance
require(_amount <= getDepositBalanceCurrent(_token, _accountAddr), "Insufficient balance.");
uint256 borrowLTV = globalConfig.tokenInfoRegistry().getBorrowLTV(_token);
Second, the method checks if the withdrawal would make the user's leverage ratio too high. The withdrawal amount is subtracted from the user's "borrow power" at the current price. If the user's total borrowed value exceeds the new borrow power, the method fails because the user no longer has sufficient collateral to support their borrowing position. However, this require check is only performed if the user is not already over-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)
), "Insufficient collateral when withdraw.");
If the user has already borrowed more than their "borrow power" allows, the withdrawal can proceed regardless. This situation can arise under various circumstances, most commonly due to price volatility. The protocol failed to consider the impact of price volatility, leading to this issue.
Other Considerations
Beyond the issues mentioned above—failure to distinguish between limit and market orders, calculation errors, logic errors, and the effects of price volatility—many other security points related to leverage protocols require attention. These include, but are not limited to, flash loan attacks, price manipulation, oracle security, permission controls, and insufficient or missing leverage checks. When designing and implementing leverage protocols, it is essential to consider these factors meticulously to ensure protocol robustness and the safety of user assets. Preventive measures, real-time monitoring, and emergency response plans are also key to mitigating potential risks and safeguarding user interests.
Frequently Asked Questions
What is the main benefit of using leverage in DeFi trading?
The primary advantage is the ability to amplify potential returns on an investment by using borrowed funds. This allows traders to gain larger market exposure than their initial capital would permit, potentially increasing profits from successful trades.
How does leverage increase risk in DeFi protocols?
Leverage magnifies both gains and losses. If a trade moves against the leveraged position, losses can exceed the initial investment quickly. Furthermore, leveraged positions are susceptible to liquidation if the value of the collateral falls below a required threshold, potentially resulting in a total loss of the initial funds.
What is the difference between margin trading and perpetual futures in DeFi?
Margin trading involves actually borrowing assets to increase position size, with the borrowed assets acting as collateral. Perpetual futures are derivative contracts that track an asset's price synthetically without requiring physical ownership of the asset, often featuring funding rates to maintain price alignment with the spot market.
Can leveraged tokens protect users from liquidation?
Yes, that is a key design feature. Leveraged tokens automatically rebalance their leverage to maintain a target level, deleveraging during losses to reduce risk. This mechanism is intended to prevent the liquidation that can occur in maintained margin or perpetual futures positions.
Why are oracle price feeds critical for DeFi leverage protocols?
Leverage calculations, liquidation triggers, and position valuations rely heavily on accurate, real-time price data. If an oracle provides incorrect or manipulated data, it can lead to unfair liquidations, incorrect leverage ratios, and significant financial losses for users.
Where can I learn more about managing risk in leveraged DeFi strategies?
👉 Explore advanced risk management techniques for decentralized finance. Understanding proper position sizing, stop-loss mechanisms, and the specific mechanics of your chosen protocol is essential for safe participation.
Conclusion
The introduction of leveraged trading in DeFi protocols has undoubtedly provided the market with greater operability, but it has also introduced more complex trading mechanisms. Although leverage offers users more investment opportunities, the associated risks and challenges to protocol security have become more pronounced.
As leverage increases, protocol operations become more flexible but also more fragile and susceptible to various security threats. This includes potential failures to strictly distinguish between limit and market orders, calculation errors, logic errors, and extreme sensitivity to factors like price volatility. In this environment, we must pay increased attention to protocol security to ensure users' assets are effectively protected.