Kyber, a Decentralized Finance (DeFi) system, proposed and applied the Dynamic Market Maker (DMM) model for solving Capital Inefficiency (CI) and Impermanent Loss (IL) issues in DeFi. DMM is one step ahead of the Automatic Market Maker (AMM) model.
Kyber’s router, one of its liquidity pool access points, is secure against sandwich attacks, but the pool contract, the second access point, is vulnerable. Therefore, interacting with the Kyber liquidity pool using the pool contract puts a user at risk of a sandwich attack.
The router is secure by virtue of a code correction of its earlier design, but the pool contract lacks a code correction. The researchers, therefore, suggest that using the same code correction method Kyber applied in securing the router will also work in securing the pool contract against sandwich attacks.
Core Research Question
How can sandwich attacks be mitigated in Kyber DMM?
Kyber: This is a Decentralized Finance (DeFi) liquidity protocol built on the Ethereum blockchain.
Automatic Market Maker (AMM): This is a DeFi equivalent of a traditional market maker which provides liquidity automatically using liquidity pools.
Dynamic Market Maker (DMM): This is an advanced form of AMM introduced by Kyber. It aims to solve Capital Inefficiency (CI) and Impermanent Loss (IL) issues of DeFi through the use of amplification factors and dynamic fees, respectively.
Capital Inefficiency (CI): This is a capital inefficient system that does not yield reasonable profit for the time the fund spends in the system (liquidity pool).
Impermanent Loss (IL): This is a phenomenon where the price of a token changes as compared to the price when it was added to a liquidity pool.
Amplification Factor: This is a parameter for augmenting liquidity, which leads to slippage reduction in liquidity pool transactions.
Liquidity Provider (LP): This is a decentralized exchange user who stakes their tokens to enable trading on the platform with the hope of making passive profits.
Sandwich Attack: This is an attack in DeFi in which an attacker targets a pending transaction to manipulate it for profit. Here, the attacker front runs and back runs the transaction, hence sandwiching it in between and stealing a percentage of the user’s fund through price manipulation.
Slippage: This occurs when the execution price of a token trade order differs from the actual price the trader intended to execute at. This occurs due to the price movement of tokens.
Transaction Reordering: This is the process of front running or back running DeFi transactions with the hope of manipulating prices for profits.
Summary
Stringent security measures are important in the DeFi ecosystem due to their widespread adoption. Consequently, vulnerabilities should be tackled as exploits that could be catastrophic.
Kyber is a DeFi liquidity hub built on the Ethereum blockchain. DeFi depends largely on smart contracts to implement its transactions, and smart contracts are famous for their autonomy in self-executing these transactions.
Kyber DMM is a new and upgraded form of AMM built by Kyber with inspiration from Uniswap’s AMM. It aims to solve the issues of Capital Inefficiency (CI) and Impermanent Loss (IL) in DeFi.
For solving CI issues, a Kyber liquidity provider sets an amplification factor for the creation of a liquidity pool. This amplification factor helps to decrease CI.
Kyber implements the use of dynamic fees, which fluctuate with the increase or decrease of volatility. The goal is to use the varying dynamic fees as compensation for the IL of liquidity providers (LPs).
In a DMM liquidity pool, there are two reserves: the real and the virtual reserves. The real reserve contains the true amount of the tokens involved in the swap, while the virtual reserve contains the number of tokens after the amplification factor has been applied.
A sandwich attack arises because an attacker can unbalance the virtual reserve ratio. The attacker will achieve this using transaction reordering. In transaction reordering, the attacker creates a higher gas fee than the victim to get her an order executed first (front running) and pays a lesser fee to execute her transaction after the victim (back running).
If the attacker unbalances this virtual reserve ratio through front running, the victim experiences a slippage in performing her transaction. The attacker then uses the incorrect ratio to back up the victim’s transaction, thus scooping part of the victim’s token as profit.
The above diagram shows how a typical sandwich attack happens. In a pool with X and Y tokens, a user initiates a transaction to swap X for Y, but an attacker sees the pending transaction on the mempool due to the open nature of the Ethereum blockchain and decides to attack it. The attacker creates and schedules two transactions to front run and back run that of the victim. The user achieves this using X to swap Y, applying a high gas fee and back runs it by swapping back Y for X, using a low gas fee.
Front running a victim’s transaction creates a slippage that makes the victim lose a percentage of their fund.
There are two access points for any user who plans to interact with the Kyber liquidity pool: the router (accessible through Kyber’s website) and the pool contract.
Presently, Kyber employs slippage protection for mitigation against sandwich attacks. This works by reverting the victim’s transaction if the attacker creates a potential slippage by unbalancing the virtual reserve ratio. In the end, the victim’s fund is not lost except for the transaction gas fee.
The use of slippage protection in the add liquidity function is only present in the router and absent in the pool contract. Therefore, the pool contract is vulnerable to sandwich attacks while the router is secure.
To secure the pool contract, the mint function of the pool contract has to have slippage protection as in the router. This is the suggestion the researchers made because this measure is not presently employed in Kyber’s pool contract.
Method
This research was more of a literature study than actual testing. The resources used were scientific papers, whitepapers, security audits, and Kyber’s blog posts.
These resources were found, using search queries on search engines such as Google Scholar and IEEE Xplore.
The researchers agreed with ChainSecuity, who initially audited the Kyber DMM smart contract, that the Kyber pool contract address was vulnerable to sandwich attacks while the router was not.
To confirm the veracity of the above claim, the researchers forked the DMM repository code and edited it using Visual Studio Code.
The researchers used Javascript to edit an existing test for a sandwich attack on the router. This was employed by earlier researchers based on the resources the present researchers consulted. This test code was edited to accommodate the pool contract. The test code can be found with the file name ”sandwichAttack2.js” here on this GitHub repository.
Results
In testing to confirm the vulnerability of the pool contract by the researchers, the test failed, showing that the pool contract was vulnerable to sandwich attacks.
Below is a breakdown of the pool contract vulnerability test, using the aforementioned test code on GitHub:
From the above result, 6.41% of the victim’s fund was stolen.
Before the start of the swap, the pool reserve ratio was token 0 : token1 = 1:100
The victim’s addition of liquidity and the attacker’s removal of liquidity from the pool increased the virtual reserve ratio to 175.9:27,490.19 (1:156.28).
But after the final swap, the ratio gets back to its original value, that is 220.07:21,989.94 (1:100)
With the present code, the test case failed. This showed its vulnerability to sandwich attacks. The reason was that the virtual reserve ratio was unbalanced from the initial value, yet the transaction was not reverted.
The researchers formally put forward a suggestion to implement the code correction by adding slippage protection to the mint function of the pool contract as was done by Kyber on the router.
The slippage protection would be achieved by adding two parameters to the function used when minting liquidity. The parameters represent the lower and upper bounds of the virtual reserve ratio, respectively.
Discussion and Key Takeaways
Kyber DMM is an efficient way to solve Capital Inefficiency and Impermanent Loss issues in Decentralized Finance.
The two access points — the router and the pool contract — for users intending to interact with Kyber’s liquidity pool are not completely safe against sandwich attacks. The pool contract is vulnerable while the router is secure.
The slippage created by attackers during transaction reordering is the cause of sandwich attacks. To resolve the vulnerability in the pool contract, the researchers propose adding slippage protection in the mint function of the pool contract.
Implications and Follow-ups
As the researchers have proven that a vulnerability exists in the pool contract, Kyber should adhere to the proffered solution or find a better way to resolve this issue. Otherwise, users planning to interact with the Kyber liquidity pool should rather use the router which is accessible through the website.
If this vulnerability in the pool contract is not resolved, in the event of Kyber’s website having technical issues, there will be no other secure way of interacting with Kyber’s liquidity pool.
Since this solution has not yet been implemented at the time of writing this paper, a bad actor could exploit the information on how a sandwich attack is implemented on Kyber DMM for their financial gain.
Because the DMM is a new concept, future work should be focused on the result of Kyber’s security audit which is on the DMM. This will help to advance DMM.
Applicability
Dynamic Market Maker (DMM) can replace Automatic Market Maker (AMM) in DeFi as it is more efficient and provides a practical way of solving Capital Inefficiency and Impermanent Loss issues.
According to Certik, in 2021 alone, money lost to DeFi exploits was about $1.3 billion. This is alarming. If the issue of vulnerability to sandwich attacks is decisively resolved, vulnerability of DeFi to exploits can be mitigated thus leading to more growth of the DeFi ecosystem.
If you think you need more background understanding on sandwick attacks after going through this summary, you may consider this research summary on the title: Analyzing and preventing sandwich attacks in Ethereum
It always helps when users are aware of how these exploits start/are created.
True to our conclusion via the Writer’s Cohort, Kyber’s DMM mechanism is a good framework for mitigating sandwich attacks. Context about sandwich attacks has helped me understand how they’re created; front and back running victims’ transactions in the mempool creates price slippage. Oftentimes, users pay more for transactions than they normally should, without even knowing. It might seem miniscule but a dive into the statistics will show users are losing a lot of money. That’s why I’m glad to learn more about Kyber’s DMM slippage protection.
It’s a bit disappointing that the solution only works in theory/more about study than actual testing.
I envisage a near future where the DMM model is adopted by most if not all DeFi protocols which in turn reduces and hopefully eliminated these sandwich attacks. The industry has seen its fair share of exploits and profiteering.
This is a well detailed and amazing research summary on the mitigation of sandwich attacks in Kyber DMM @Ulysses.
One can understand that the proposed solution to the Sandwich attack in the Pool Contract of the Kyber’s liquidity pool access point is based on Suggestion as illustrated by the researcher.
Also, Kyber uses slippage protection in mitigating against sandwich attack which is only used in the Router, hence, the need for the same to be used for the Pool Contract.
This slippage protection would help in implementing code correction which the researcher suggested by adding two parameters to the function.
I am intrigued. It is quite a fascinating read.
I would like to ask, what is the probability that using the same code correction as in the router would be efficient for the Pool contract? Is there a model in which this is based?
Is there a base point in the two parameters for the virtual reserve ratio to be used for the slippage protection?
Yes it is. Only that presently, it seems as if only sophisticated users are aware. Maybe because of how complicated the technology is or how innocuous the attacks appear to be to an unsuspecting user.
Exactly the point I was trying to make in the previous paragraph.
This is probably imminent. If Kyber succeeds, they will be an example to other protocols to copy from.
The probability is high. Remember this is practically working on the router already.The model here is Kyber’s router. Since, it has been implemented by Kyber on one part leading to its liquidity pool, why not on the second part?
To make it clearer, basically, the thing to be done is code correction on the same medium (lines of code). That is using the router as a reference, the developers will rewrite or modify the codes for the pool contract.
Both the pool contract and router are made up of lines of codes. If they are made of the same stock, they will yield the same result or similar result in the worst case.
Can you please specify the two parameters you mean here?
Sandwich attack is sophisticated and subtle. This is because it happens in a very short time and is, most times, done by bots.
If you initiate a swap on a decentralized exchange for instance, the order stays pending for a short time before completing your swap. During that short time, you can do little or nothing about that swap. That is, you can’t cancel it once you have clicked confirm.
It is within this short time that a user gets sandwiched by these bots. The bots are very fast.
You only know that you were sandwiched once your swap has been completed and you got less of the token than you expected.
One of the best ways to stay safe against sandwich attacks is by using a limit order instead of instant execution. That way all your orders get filled at a specified price.
Thank you for the response to the first question @Ulysses.
Here, i was referring to the the parameters which the researcher pointed to represent the lower and upper bounds of the virtual reserve ratio as in herein;
This parameters, i understand is to be used to for the virtual reserve ratio which when unbalanced by an attacker, can result in sandwich attack.
@Ulysses Thanks for coming up with this patent summary of sandwich attack. From your summary I gleaned the problem statement emanated from the inability of the second access point of Kyber, pool contract to withstand attack as a result of lack of code correction. I also, understand that the research proposed a solution albeit a theoretical one.
I agree with you that Decentralized finance has risen to be one of the sorts after aspect of DLT, because of its ability to entrust trust in a trustless environment and to perpetually bench the central authority in the financial transactions. It’s ability to onboard unbanked population, eliminate and/ or reduce transaction costs has made it a joy to behold by the participants. However, the operation of DeFi in an unregulated environment has like the Achilles heel exposed it to various attacks, one of which is sandwich attacks.
The sandwich attacker targets DEX by using bots to sniff out trade transactions with low gas prices and liquidity pool transactions where users can claim rewards and convert same to required token. The Attackers rely on AMMs pricing algorithms to identify transactions and thus place a transaction with a higher fee which frontruns the normal transaction.
For Instance: A user places an order to buy 1,000 tokens at 100 USDT each, and the slippage factor is set to 10 per cent. While executing the trade, DEX will allow the trade to happen as long as the price is below 110 USDT. The attacker needs to check what is the maximum number of tokens the attacker can buy to increase the price, making sure the price change won’t be more than the slippage set by the user.
In addition to solution proposed by your summary, I have curated some solutions as recommend by some industrialist to further the discussion. For instance,Karkara from Zebpay recommended decreasing the slippage when the trade amount increases and incorporating new technology like ZK-Snarks to mask users trade information so that bots cannot identify it. See Cryptocurrency news: U.S. senators unveil bill to regulate cryptocurrency - The Economic Times
Further, sandwich attack can be avoided by using the Flashbots RPC which allows user to send transaction directly to the miners thereby bypassing the public mempool ( a place pending transactions are stored before being confirmed and added to the block) for additional protection. See Sandwich Attacks in Defi – What Are They and How to Avoid One.
Hello @Ulysses weldon for posting this paper. I see that the DeFi system of interest for this paper is one known as Kyber. Five security audits have been published for Kyber since it was released in 2017, for me I think this is a good development because these audits
have brought several security vulnerabilities to light, most of which were subsequently mitigated by the programming team at Kyber. Had the Kyber protocol not been openly auditable, these vulnerabilities would likely
be exploited by malicious users, leading to security breaches and potential losses of funds. This shows how important it is for vulnerabilities to be documented.
Is interesting to know that Sandwich attacks in Kyber’s DMM are slightly different
from the conventional kind, as the issue is related to the virtual reserves which exist in addition to the real reserves.
I think the objective of this paper is to show that the vulnerability is indeed present in the mint function and to suggest applying the mitigation to the vulnerable part of the system as well.
Kyber’s current mitigation only exists
in the router, so the vulnerability still exists if users mint liquidity via the pool contract directly.
Only users who add liquidity through the pool contract directly are vulnerable to a sandwich attack. This way of adding liquidity is discouraged by Kyber and the only situation where such an act makes sense is when the interface is down. I think there is a low chance for this attack to occur.
I think this paper has only suggested to broaden an existing mitigation and has not featured a solution to the issue.
I think For AMMs, it is crucial to develop countermeasures capable of protecting users from sandwich attacks.
Despite clear financial incentives to sandwich attack, doing so may not always be worthwhile. The cost of performing these transactions to front and back-run other traders will often outweigh the financial gain for attackers especially when using the Ethereum network, which notes transaction costs (per action) rather regularly, do you think or feel that Sandwich Attacks Worth the Work? My opinion at the moment.
Hi @Lanedot thanks for taking out time to read through my contribution. You have made very wonderful points that I agree with.
However, I have a slight objection to the idea of sandwich attacks not being profitable on the basis of gas fees being expensive.
Let’s consider @PatrickZuest’s Bachelor thesis on analyzing and preventing sandwich attacks in Ethereum. He even made a summary of that paper here on the forum incase you want something shorter and concise.
From the image he shared, you can see that in 10 months, the attackers made a consistent profit even though some individual transactions were unprofitable. The research also suggests that at some points, the attackers collaborated with miners which yielded maximum profit. Note that gas fees have been subtracted from the results on the graph.
So some factors will actually encourage more profit on sandwich attacks.
Kyber’s current mitigation includes slippage protection to guard users from sandwich assaults. Slippage protection is implemented by adding two parameters to the function used for adding liquidity. These variables define an upper bound and a lower bound for the virtual reserve ratio. Kyber now employs slippage protection to counteract sandwich attacks. The victim’s transaction is reversed if the attacker disrupts the virtual reserve ratio in order to potentially cause slippage. With the exception of the transaction gas fee, the victim’s money is ultimately not lost. To put it simply, a sandwich attack involves sandwiching a user’s transactions between two other transactions.
The phrase may be used to find your wallet if you happen to lose it.
Thank you @Ulysses for this astute Research Summary on Sandwich Attack in Kyber DMM (now known as KyberSwap).
Preliminary, it is a settled fact that DeFi market offers a plethora of exciting opportunities, however it remains vulnerable to attacks that try to take advantage of the smart contract-built nature of DeFi applications, and Sandwich Attack is one of such attacks.
I understand that Sandwich Attack involves sandwiching a user’s transactions in between two transactions. These two transactions are before and after the user’s transaction, generating a loss for the user and a gain for the attacker.
Furthermore, I equally understand that a Sandwich Attack typically takes place on decentralized exchanges (DEXs) and result in price manipulation.
However, in addition to the solutions offered in your Research Summary on possible ways to mitigate Sandwich Attack in Kyber DMM (KyberSwap), research has also shown that one of the ways to prevent getting sandwiched is to place a limit order, unlike typical market orders which are susceptible to slippage, users can set their fill price instead. While this was typically only available on Centralized Exchanges, DEXs such as 1inch and SpiritSwap currently allow this.
Hi @Livinus_Oluchukwu, thanks for sharing your thoughts! The suggestions you made are very practical in solving issues of sandwich attacks on protocols using the Automatic Market Makers (AMM).
So there is a slight difference here. This paper is focused on Dynamic Market Maker (DMM). DMM, as a market making model, was proposed to solve issues of impermanent loss(IL) and capital inefficiency(CI). These two issues are prevalent in AMM protocols.
Therefore, it’s safe to say that DMM is an invention for improving AMM. So Kyber DMM solves the problem of CI and IL.
In Kyber, there are two access points for adding liquidity to its protocol.
The router accessible through the website
The pool’s contract
The router is secure from sandwich attacks and no user who adds liquidity through that means would be sandwiched.
But the pool’s contract is vulnerable to sandwich attacks. The goal of this paper is to solve this pool contract sandwich issue fundamentally. That is, to starve all factors that could even make sandwich attacks flourish in the first place.
If this is solved fundamentally, there will not be need for taking precautions such as using limit orders.
Good job @Ulysses Due to its capacity to foster confidence in an untrustworthy context and permanently displace the role of the centralized agency in monetary operations, decentralized funding has emerged into one of the most pursued features of DLT. It has made it a delight to watch for the partners thanks to its capacity to enroll the low - income public and nullify and/or cut overheads.
Sandwich assaults are one of the many assaults that DeFi has been susceptible to due to its functioning in an uncontrolled context, which has served as its Weak spot.
By employing robots to look for sales with cheap fuel costs and liquidity group purchases so customers may earn bonuses and exchange them to needed tokens, the sandwich hacker aims at DEX.
Assailants initiate a trade with a good price that frontruns the normal trade by using AMM’s costing techniques to analyze trades. A sandwich assault solely affects customers who actively inject liquidity to the group agreement.
Kyber opposes this method of generating liquidity, and the only time it is appropriate is if the website is inaccessible.
I believe the likelihood of this attack happening is quite minimal.
Sandwich assaults have obvious monetary advantages, but it could not be beneficial. When leveraging the Blockchain, the expense of carrying out certain trades to the front and away opposing traders frequently surpasses the cash advantage for assailants.
I have read through your work and had to study more into the subject. Now, I’d love to talk about your research question, but before then, just as earlier noted, sandwich attacks are a type of attack that can take place in decentralized market makers (DMMs) like Kyber DMM. These attacks involve an attacker simultaneously placing orders on both the buy and sell sides of a market in order to profit from the spread between the two orders.
There are a number of ways in which sandwich attacks can be mitigated in Kyber DMM and other decentralized market makers:
Implementing anti-arbitrage mechanisms: Anti-arbitrage mechanisms can be implemented to prevent traders from profiting from the spread between buy and sell orders. For example, Kyber DMM uses a mechanism called “strict price matching” to ensure that orders are matched at the exact price specified by the trader, rather than at a price that is slightly different from the specified price.
Using order-matching algorithms: Order-matching algorithms can be used to ensure that orders are matched in a fair and transparent way, rather than allowing some traders to profit from the spread between buy and sell orders.
Ensuring liquidity: Ensuring that there is sufficient liquidity in the market can help to prevent sandwich attacks, as it reduces the likelihood that an attacker will be able to profit from the spread between buy and sell orders.
Implementing reputation systems: Reputation systems can be used to incentivize good behavior and discourage malicious behavior in the market. In the case of Kyber DMM, this could involve implementing a reputation system that rewards traders who provide liquidity to the market and punishes those who engage in malicious behavior.
Overall, sandwich attacks are a significant challenge in decentralized market makers, and it is important for organizations such as Kyber DMM to take steps to mitigate these attacks.