Zero-Knowledge Proof (ZK) Technology: May Be Widely Used in the DeFi Field
Original Title: "Zero-Knowledge Proof Technology: The New Star Lighting Up DeFi"
Original Author: LZ
1. Introduction
Decentralized Finance (DeFi) is an important development direction in the current financial innovation field. In DeFi, the concealment of transaction information and the maintenance of user privacy are crucial. As DeFi continues to expand and deepen, various projects emerge, full of vitality. The application of Zero-Knowledge Proof (ZK) technology opens up new possibilities for privacy protection in DeFi. ZK technology allows one party to prove to another that they know certain information without revealing any specific details about that information. This technology has been applied in DeFi projects such as ZigZag, unyfy, and OKX's ZK DEX, significantly enhancing the privacy protection capabilities of DeFi, especially for transaction information. It is foreseeable that the widespread application of ZK technology will bring about innovations in how DeFi and the entire cryptocurrency sector operate, promoting future development and achieving significant breakthroughs.
2. Privacy Challenges in DeFi
There are no secrets on the blockchain, and the transparency of DeFi data is indisputable. For example, in a transaction on Uniswap V3, we can easily view the transaction details through the Etherescan website (as shown in Figure 1). For instance, the address 0x3A4D…a6f2 exchanged 2 WETH for 17,654,123,249,375 Bonk on Uniswap V3, with a transaction fee of 0.0046 Ether. Key information such as the sender (From), receiver (To), transaction amount (Value), and transaction fee (Transaction Fee) in these transactions is publicly accessible.
Figure 1 Public transaction details on Etherescan
We can also view all transaction records under the address 0x3A4D…a6f2 (as shown in Figure 2), and if conditions allow, we can infer the real-world identity of this address.
Figure 2 All transaction lists for a specific address are publicly available on Etherescan
However, the transparency of DeFi data may bring some adverse effects. If you are a DeFi whale, every transaction you make may attract market attention. For example, when a whale withdraws 11.24 million WOO (approximately 4.2 million USD) from Binance, this transaction will draw widespread attention. Similarly, any large payment or institutional-level trading behavior may also trigger public scrutiny.
Other market participants may make buy or sell decisions based on these trading behaviors, adversely affecting your investment strategy. For instance, if you invest a large amount in a project, once your transaction is noticed by the market, other investors may follow suit, leading to an increase in asset prices and, consequently, your investment costs. Additionally, your selling actions may trigger market panic, causing prices to drop and affecting your investment returns.
This situation highlights the urgent need for privacy protection among DeFi projects and users. If we do not want our transaction details to be publicly known, we can choose to keep certain information about DeFi transactions private.
ZK technology can hide transaction details while ensuring the legality of transactions. Users need to submit two types of information: one is the transaction with partially hidden details (such as the transaction recipient or amount) (i.e., privacy transaction), and the other is the ZK proof regarding these hidden details. Verifying the legality of a privacy transaction is essentially verifying the corresponding ZK proof.
3. Unlocking DeFi Potential: Opportunities Brought by ZK Technology
3.1 The Role of ZK Technology in Preventing Front-Running Transactions
Suppose you are fortunate enough to learn that a large company is about to purchase a significant amount of a certain asset; you might choose to buy that asset before the company does. Then, when the company's large purchase drives up the asset price, you sell it for a profit. In this case, your transaction ahead of the large company constitutes front-running.
Front-running is an investment strategy in financial transactions that typically occurs in exchanges like Uniswap. This is because transactions on the blockchain are public, and transaction confirmations take some time. Therefore, some malicious traders may increase their transaction gas fees to have their transactions confirmed by miners before others, achieving the purpose of front-running.
Front-running can harm other traders because it alters the original trading environment, making it difficult for other traders to execute their trades as planned. On the other hand, the attacker initiates front-running transactions to profit for themselves, potentially profiting before price changes. As a result, many DeFi projects are also trying various methods to prevent front-running.
ZK technology can play a key role in resisting front-running transactions. Below, we take the sandwich attack in decentralized exchanges (DEX) as an example, which is also a common type of front-running transaction, for case analysis.
3.1.1 Case Analysis: Sandwich Attack in DEXs
What is a Sandwich Attack?
Suppose there is a liquidity pool on a DEX with a reserve state of 100 ETH / 300,000 USDT. Alice initiates a transaction to buy USDT, exchanging 20 ETH for USDT. When she submits the transaction, the DEX returns a result based on the current liquidity pool's reserve state, telling Alice she can buy approximately 50,000 USDT. However, in reality, Alice ends up receiving only 45,714 USDT.
Here, let's briefly understand why Alice can buy 50,000 USDT with 20 ETH. The DEX uses an Automated Market Maker (AMM) model, automatically calculating buy and sell prices through a Constant Product Market Maker (CPMM) algorithm. CPMM is a widely used automated market maker algorithm that maintains a constant product of two assets in the trading pool to provide liquidity and automatically adjust asset prices. In this example, the number of USDT Alice can buy is calculated using the formula 50,000=300,000-(100*300,000)/(100+20) (assuming no fees).
Alice did not buy the expected amount of USDT because she fell victim to a sandwich attack.
Sandwich attacks primarily occur in AMM-based DEXs. In a sandwich attack, the attacker places two transactions around the victim's regular transaction to manipulate the asset price and profit from the victim's loss. The two transactions are the front-running transaction and the follow-up transaction, with the transaction before the regular transaction referred to as the front-running transaction and the transaction after the regular transaction referred to as the follow-up transaction.
So, how did Alice suffer from a sandwich attack? As shown in Figure 3.
Figure 3 Sandwich Attack Process
Attacker's front-running transaction: Before Alice's transaction to buy USDT is executed, the attacker also initiates a transaction to buy USDT (the front-running transaction), exchanging 5 ETH for USDT. Moreover, the attacker pays a higher gas fee to miners for this transaction than Alice, so the attacker's transaction will be executed before Alice's.
After the attacker's transaction to buy USDT is executed, they receive approximately 14,286 USDT from the liquidity pool, where 14,286≈300,000-(100*300,000)/(100+5). The liquidity pool's reserves change from the initial state of 100 ETH / 300,000 USDT to 105 ETH / 285,714 USDT. However, during the time between Alice submitting her transaction and its execution, she is unaware that the liquidity pool's reserve state has changed.
Victim's regular transaction: Subsequently, Alice's regular transaction begins execution.
After Alice's transaction to buy USDT is executed, she receives 45,714 USDT from the liquidity pool (according to the constant product function, 45,714≈285,714-(105*285,714)/(105+20)). The liquidity reserve state changes from 105 ETH / 285,714 USDT to 125 ETH / 240,000 USDT. Therefore, Alice should have been able to buy 50,000 USDT with 20 ETH, but due to the attacker's transaction altering the liquidity pool, she can only buy 45,714 USDT. Alice incurs a loss of approximately 4,286 USDT (4,286=50,000-45,714).
Attacker's follow-up transaction: Finally, the attacker initiates another transaction (the follow-up transaction), exchanging 14,286 USDT for ETH (the 14,286 USDT just purchased).
After the attacker's follow-up transaction is executed, they receive 7 ETH from the liquidity pool (constant product function, 7≈125-(125*240,000)/(240,000+14,286)). The liquidity pool's reserve state changes from 125 ETH / 240,000 USDT to 118 ETH / 254,286 USDT. Thus, the attacker initially spent 5 ETH but ended up with 7 ETH, gaining a profit of 2 ETH (2=7-5).
Throughout the sandwich attack process, the attacker initiated two transactions: the front-running transaction and the follow-up transaction. The front-running transaction caused Alice to incur a loss of approximately 4,286 USDT. The combination of the front-running and follow-up transactions allowed the attacker to profit 2 ETH.
In DEXs, the public nature of transactions is a key factor leading to the occurrence of sandwich attacks, especially in AMM protocols. These protocols publicly disclose real-time transaction information on DEXs, and this high transparency provides opportunities for attackers, allowing them to observe and analyze transaction flows to find opportunities for sandwich attacks.
3.1.2 ZK Technology Can Resist Sandwich Attacks
The application of ZK technology can significantly reduce the likelihood of being subjected to sandwich attacks. By using ZK technology to hide transaction volumes, asset types, user or liquidity pool balances, user identities, transaction instructions, and other protocol-related information, the privacy of transaction data can be effectively enhanced. This way, attackers find it difficult to obtain complete transaction information, making the implementation of sandwich attacks more challenging.
Moreover, ZK technology not only resists sandwich attacks but also increases the difficulty of inferring user behavior models. Any third party attempting to analyze account transaction histories, infer behavioral patterns, explore active cycles, trading frequencies, or preferences by collecting blockchain data will face challenges. This type of analysis is known as behavioral model inference, which not only infringes on user privacy but may also pave the way for honey pot attacks and phishing scams.
3.2 Preventing Liquidity Manipulation Based on ZK Technology
Liquidity manipulation and front-running transactions are both attack methods in DeFi, and both involve leveraging market information and trading speed to gain benefits, but their specific strategies and operations differ.
Front-running transactions exploit information advantages, while liquidity manipulation misleads other traders through market activity. The former primarily profits by obtaining and utilizing undisclosed important information, while the latter misleads other investors by creating false market activity, leading them to make unfavorable trading decisions.
ZK technology can play a key role not only in resisting front-running transactions but also in preventing liquidity manipulation.
3.2.1 Case Analysis: Using Oracles for Liquidity Manipulation
Suppose you are buying apples at a busy fruit market. The market price typically fluctuates based on supply and demand changes. You usually observe the prices for a while and then decide whether to buy based on the average price. Now imagine a very wealthy buyer enters the market and is very eager to buy apples. They start buying apples in large quantities, regardless of the price. This will cause the price of apples to skyrocket in a short period. If you still decide to buy apples based on this price, you might end up paying more than the actual value.
This example helps to better understand the working principle of TWAP (Time-Weighted Average Price) oracles and the concept of liquidity manipulation. Deciding to buy apples based on the average price is similar to how TWAP oracles operate, while the wealthy buyer's large purchases causing price increases resemble liquidity manipulation.
TWAP oracles determine asset prices by calculating the average trading price over a period. The closer the transaction time, the greater the impact on the average price. If someone conducts a large number of transactions or trades with a large amount of funds in a short period, it may significantly affect the asset's average price, which is liquidity manipulation. Liquidity manipulation artificially inflates or deflates asset prices, leading to inaccurate price information. If someone wants to deliberately raise the asset price using a TWAP oracle, they can purchase the asset with a large amount of funds in a short time, causing a temporary price increase. If, within this time window, the asset price shows a significant increase, the TWAP oracle may regard this higher price as the asset price.
Implementing liquidity manipulation on TWAP oracles can have significant impacts on DeFi protocols, especially for emerging tokens with low liquidity. These DeFi protocols often make financial decisions based on asset prices, such as liquidation and lending. If the price information is inaccurate or unreliable, it may lead to erroneous decisions, resulting in losses for users. Therefore, preventing TWAP oracles from being subjected to liquidity manipulation is crucial.
3.2.2 ZK Technology Can Resist Liquidity Manipulation
ZK technology can resist liquidity manipulation in TWAP oracles. A smart contract can be designed to rely on TWAP oracles to obtain asset prices. If an attacker conducts liquidity manipulation, the price obtained from the TWAP oracle may exceed the preset acceptable range. In this case, the contract will temporarily halt its operations. Then, it will recalculate and confirm the asset price based on ZK technology.
To use ZK technology to calculate asset prices, a wrapper contract needs to be added to the TWAP oracle. This contract can directly access N price reports or record the N checkpoint values of prices at any interval. Once N data points are available within a given interval, a ZK proof can be constructed to prove the median of the unsorted array of prices. The unsorted price array is denoted as a column vector x, with a length of N. The following is the process of calculating asset prices based on ZK technology:
The proof can be verified in either of the following two ways, regardless of which case, the prover cannot arbitrarily choose a price array as input.
● Retrieve array values from contract storage and use them as public inputs for on-chain verification;
● Gradually form a hash chain through a hash function, representing the array as a single hash value, and use that value in the on-chain verifier.
There exists an N x N matrix A (square matrix), such that when this matrix is multiplied by the column vector x, it produces the column vector y, making y=Ax. A is an invertible permutation matrix, but due to the possibility of duplicate price values, A is not necessarily unique, and A only contains binary values.
The values in y are ordered, i.e., { yi≤yi+1 ∀ i ∈ 0…N-1 }. Again, it should be noted that < cannot be used because there may be duplicate price values.
The public output m of the circuit is the median value of y. The proof shows y⌊N/2⌋=m, where N is a static value at the time of circuit compilation and must be odd.
Based on the above process, a median price m is output based on ZK technology, which is tamper-proof. The median m can help prevent liquidity manipulation to some extent. To achieve this, we need to limit the values of y so that within each block, the values of y are only inserted once, or the number of insertions remains within an acceptable range.
3.3 ZK Technology Empowers Lending Platforms
As mentioned above, ZK technology can resist front-running transactions and liquidity manipulation in DEXs. So, can we further explore the potential applications of ZK technology in other DeFi scenarios? For example, in the important component of DeFi projects—lending, ZK technology can also play a key role.
3.3.1 Key to Lending: How to Assess Borrower Credit
In traditional lending platforms, the loan application process typically includes five steps: application, credit assessment, loan approval, loan disbursement, and repayment. Among these, the credit assessment stage is particularly important, as borrowers must prove their income meets standards and that they have the ability to repay. During the assessment process, the platform conducts an in-depth investigation of the borrower's credit history, including income, debts, and past repayment records, to ensure they can repay the loan. Only on this basis will the platform consider approving the loan application.
However, when you turn to DeFi lending platforms like Aave or Compound, the situation is different. Most DeFi lending platforms, due to their decentralized nature, do not have traditional banks' KYC (Know Your Customer) procedures and risk assessment stages, nor can they investigate borrowers' credit status through joint credit agencies. In this case, you might wonder, how will my credit be assessed?
On DeFi lending platforms, you can prove your credit level through reputation tokens. Reputation tokens are a credit system based on blockchain technology, representing and quantifying users' credibility through digital tokens. The number of reputation tokens becomes an important indicator for assessing user credibility; the more tokens, the better the user's reputation, and the higher the credit rating, which may lead to obtaining more loan limits on DeFi lending platforms.
However, the generation of reputation tokens relies on users' transaction histories and financial information, which may infringe on users' privacy.
3.3.2 Assessing Borrower Credit: Reputation Tokens Based on ZK Technology
ZK technology can protect user privacy. The combination of ZK technology and reputation tokens can maintain and track users' reputations in the network while protecting their privacy.
Users can leverage ZK technology to generate reputation tokens without disclosing historical transactions. On one hand, users can generate proofs of historical transactions based on ZK technology; on the other hand, smart contracts (commonly referred to as reputation token generation contracts) can verify these proofs, and upon successful verification, reputation tokens can be generated.
Additionally, on some DeFi lending platforms that require over-collateralization, reputation tokens can lower collateral requirements, thereby addressing the issue of excessive collateral and improving market liquidity. Furthermore, the application of reputation tokens based on ZK technology is not limited to DeFi lending platforms; it can also be widely applied in areas such as insurance and medical assistance.
4. Conclusion and Outlook
This article explores various application scenarios of ZK technology in achieving privacy protection in DeFi, particularly its potential in resisting front-running transactions, liquidity manipulation, and lending. In the process of exploring DeFi, we face multiple challenges, especially those related to privacy and security. The privacy challenges in the DeFi ecosystem are a key issue, and ZK technology provides a unique solution that not only enhances privacy protection but also improves transaction efficiency and security. If you want to introduce ZK technology into your DApp, feel free to contact Salus.
Looking ahead, ZK technology may find applications in deeper DeFi fields, such as liquidity staking, derivatives protocols, real-world assets, insurance, and more. Salus focuses on researching and exploring the application of ZK technology in DeFi and other Ethereum application layer projects. We invite blockchain researchers, technical developers, and all professionals in the web3 field worldwide to work together with us to promote the in-depth development and widespread application of ZK technology, driving the development of DeFi and the entire industry.