Insights

Understanding DEXes through Balancer

Post by
Sidhanth Kumar
Insights

Understanding DEXes through Balancer

By
Sidhanth Kumar
|
December 1, 2021
|
3 Mins Read
Understanding DEXes through Balancer

Disclaimer: Nothing in the Site constitutes professional and/or financial advice, nor does any information on the Site constitute a comprehensive or complete statement of the matters discussed or the law relating thereto. Bitbaza.io or related companies are not a fiduciary by virtue of any person's use of or access to the Site or Content.

The trading volume on decentralized exchanges have been increasing lately which is a positive sign towards the adoption of DeFi. So now the question arises what are these dexes and how they are different from their centralized counterparts. As the name goes a decentralized exchange is essentially an exchange, so the main purpose it is used for is trading but there’s one thing that makes trading less attractive on decentralized exchanges as compared to centralized ones and that is the amount of liquidity on the dexes. Liquidity is the most important thing an exchange should have if it has to ensure seamless experience for its users i.e. traders. So to circumvent this issue dexes have something called liquidity pool where the users only are incentivised to provide liquidity to the platform in exchange for liquidity tokens which entitles them to certain amount of monetary benefits. So essentially on a decentralised exchange there are two types of users : 

  • Traders: Who exchange one asset for another
  • Liquidity providers: Who are responsible for providing liquidity to the exchange to ensure smooth execution of trades.  

Now there’s one more thing that centralized exchanges have while the dexes don’t and that is the market maker. A market maker is someone who quotes the bid and ask price for a certain asset and based on the supply and demand of the asset keeps changing these prices to ensure liquidity. Now since the whole idea of decentralized exchange is that there shouldn’t be any third party or middleman who verifies or oversees the transaction, that’s why dexes don’t have any market maker. So to resolve this issue of pricing, dexes employs what is known as automated market maker(AMM). AMMs are algorithmic agents that perform those functions and, as a result, provide liquidity in electronic markets. So basically what a typical decentralized exchange does is it pools everyone’s liquidity together and makes markets according to that deterministic algorithm i.e. the AMM which quotes prices to the end user according to some pre-defined rule set.

So now that we know how a typical decentralised exchange functions, it’s time to have a look at one of the most famous decentralized exchange Balancer, how trading and liquidity provision works on it and the maths behind it.

Balancer ,unlike Uniswap which only allows a max of 2 tokens, supports liquidity pools of up to 8 tokens i.e. liquidity providers can form a pool of up to 8 ERC-20 tokens. The deterministic algorithm that it follows is called the constant mean market maker. Constant mean markets satisfy the following equation:

There are three terms in the above equation that we need to know:

  • V - The invariant that has to be maintained constant during a trade.
  • Bt -  Balance of token t i.e. the no of coins of cryptocurrency t
  • Wt - The normalized weight of the token such that the value of all weights is 1, basically the share of the value of token t

Now let’s have a look at how trading works, how it changes the dynamics of the pool and what are the mathematical equations behind it.

Trading

Trading, as mentioned above as well, is basically exchanging one asset in the pool for another asset which is also there in the pool. So the first and foremost thing that comes to mind while trading is that what will be the price at which the tokens will be traded i.e. how many tokens of a certain asset Bi would have to be put in the pool to get a certain amount of token Bo. One thing we know from above discussion is that it is the AMM algorithm that’ll determine the price. Now if we talk in general, how do we determine the price of two entities with respect to each other, we simply trade both assets for one another and see how much we are able to buy one asset by selling a certain amount of the other. For example if we are able to buy 10 ETH for 5000 DAI we’ll say that the price of 1 ETH is 5000/10 = 500 DAI. But this price that we are getting is the average price of 1 ETH during that trade and not the instantaneous price because the price of ETH at the start of trade is different and price of ETH at the end of the trade is different due to the lesser supply of ETH in the pool after the trade, this phenomenon in called slippage. And bigger the size of the trade larger the slippage is, more is the price difference between the start and end point of the trade. So our objective is to calculate instantaneous price and not the average price, it’s just like calculating average velocity and instantaneous velocity like average velocity is calculated as Total distance/Total Time and instantaneous velocity is calculated as dx/dt. So to calculate the instantaneous price we have to make sure that the slippage is zero i.e. the price of the entity at the start and at the end of the trade is same meaning that the trade is infinitesimal. So if we are buying ∆Bo tokens of asset o for ∆Bi tokens of asset i then both ∆Bi, ∆Bo tend to zero  and the price of the token o with respect to token i is ∆Bi/∆Bo and this price is known as the spot price. Below is the mathematical derivation for the spot price in balancer pool:

So now no of tokens of asset o in the pool = Bo - ∆Bo

              No. of tokens of asset i in the pool = Bi + ∆Bi

Proof:

Let Bk be the no. of coins of token K in the pool

And Wt -> Normalized weight of the token

Now that we know what the formula of spot price is, we can use it to discuss a phenomenon called arbitrage and how it leads to impermanent loss for the liquidity providers. Arbitrage is a situation when the price of an asset differs across exchanges, so an opportunity of profit is generated in this way as one can buy the asset from one exchange at a lower price and sell on the other exchange at a higher price thus making profit. Now how it could lead to impermanent loss for liquidity providers let’s see it through an example:

Example: 

Let’s assume that our balancer pool has only two types of tokens – DAI and ETH and it’s a 50-50 pool i.e. the weights of both the tokens i.e. Wi and Wo are 0.5 and 0.5, and the initial values of Bi and Bo provided by the liquidity provider are 10000 and 20 respectively. From the AMM formula we get the value of V as 100*20^0.5. Now this value of V has to be maintained no matter how much trading activity occurs on Balancer. So current spot price of ETH w.r.t DAI is Bo*Wi/Bi*Wo from the spot price formula that we derived above, it comes out to be 500. The data is tabulated in the table below:


Now suppose the price of ether on some other exchange i.e. the spot price shoots to 550$ i.e. 550 DAI per ETH, now this is an opportunity of arbitrage. So now until the price difference is eliminated arbitrageurs can make use of this difference and keeping swapping ETH for DAI in the pool and make profit. So we have to find the new value of Bo and Bi in the balancer pool so that the new spot price is 550. We have two equations, one from the AMM formula which is 100*20^0.5 = Bi^0.5*Bo^0.5 and one is the spot price equation Bi/Bo = 550   So upon completing the calculations we see that when the price of ether reaches 550 DAI i.e. the ratio Bi/Bo reaches 550, the value of Bi and Bo comes out to be 10448.09 and 19.07 respectively.

So the arbitrager is basically able to buy 0.93 ETH in order to achieve equilibrium between Balancer and the market costing 488.09 DAI. So the average price at which it ETH was bought for was 524.83 DAI/ETH, and he can easily sell it for 550 DAI(1 DAI = 1$) now in the market, so the profit he earns is 25$ - Transaction fees. So now if you see the total value with the LP before the arbitrage was 10000 + 20*500 = 20000, after the arbitrage the value was 10488.09 + 19.07*550 = 20976.59, had he simply held onto his assets instead of using them for providing liquidity the total value with him would be : 10000 + 550*20 = 21000, so this loss of 21000 – 20976.59  = 23.41 $ is the impermanent loss for the liquidity provider. Although this loss could be recovered if the price changes again, that’s why it is termed as impermanent loss. 

Now there also are some upsides of this arbitrage phenomenon which Balancer uses to its advantage like these arbitrageurs restores the stability onto the exchange i.e. they make sure that the price of assets on Balancer is in line with the market price. Also Balancer collect fees from traders, who rebalances the pool by following arbitrage opportunities. 

A general formula can be derived to find out the number of tokens Ai that needs to be put in the pool to change the current Spot Price SP (Bi*Wo/Bo*Wi) to the market spot price SP'(Bi'*Wo/Bo'*Wi). In the balancer white paper only the formula is given, the derivation is provided below:

Bi' = Bi + Ai;

Bo' = Bo - Ao

As you might have noted in the above derivation the formula for number of tokens Ao of asset o one can buy by selling Ai tokens of asset i is also automatically derived.

So with this the trade part is pretty much over and we were also able to get a look at liquidity providers a bit in the arbitrage section but now we’ll discuss more about liquidity providers in detail in the following section.

Liquidity Providers:

Liquidity providers are a very integral component of the ecosystem of any decentralized exchange as it is impossible to sustain trading activities on an exchange without having sufficient liquidity. So the liquidity providers are provided with incentives, basically an opportunity to earn passive income on the trades by providing liquidity in the pool. The liquidity providers are provided with LP tokens as a receipt for the amount of liquidity they have provided which makes them eligible for a share in the transaction fees that is collected from the traders for executing any sort of trade on the exchange. The amount of the fees that the LP gets is proportional to the amount contributed to the pool, bigger the contribution more the fees they get. Since pool tokens represent the ownership of the assets in the pool, they can also be used to withdraw a certain amount of assets from the pool. This proportion of pool tokens that the liquidity providers hold is not constant and changes with the changing liquidity because every time a user provides liquidity to the pool, he is also issued some pool tokens which increases the outstanding supply of tokens hence decreasing everyone’s individual share. 

So to put it simply, more liquidity on the platform ensures cheaper trades, cheaper trades promotes more trading activity, more trading activity means more transaction fees, more transaction fees means more income for liquidity providers which in turn incentivises them to provide more liquidity. So this is the cycle that decentralized exchanges always try to maintain to ensure seamless user experience.

The mechanics for balancer pool are pretty much the same in terms of liquidity provision with some unique features. Like for example in Uniswap a liquidity pool can only have maximum of 2 tokens whereas the limit is 8 for balancer, in Uniswap it is mandatory for the liquidity provider to provide liquidity for both the assets in the pool and that too in a fixed ratio, the reason for that is that just like Balancer has spot price equal to Bi*Wo/Bo*Wi in the same way Uniswap also has the spot price = x/y where x and y are the number of tokens of Asset A and Asset B(basically the assets in the pool), and as we learnt in the previous section that spot price is essentially the price of the two tokens with respect to each other and if liquidity provider are not depositing tokens in a fixed ratio that means they are changing the ratio which is equivalent to changing the price and if the price is changed, there will be an impermanent loss for liquidity providers. But balancer provides flexibility to its users in terms of depositing tokens, the LPs in balancer can chose to provide tokens of only one asset. But if the LPs are providing tokens only for one asset say for token i then they’ll be changing the spot price, which only happens in trade so providing tokens of only one asset is just like executing a trade and they’ll be charged a transaction fees for that just like the traders are charge for executing any kind of trade. On the other hand if all the tokens are provided proportionally then the spot price remains same and hence no swap fee is charged. 

The liquidity providing formulas have been beautifully explained in the Balancer whitepaper.

Now there also are various risks of using balancer or any defi protocol and users must be aware about them before investing their money into them. Some of the risks are:

Risks of Balancer:

  • Impermanent loss: One of the biggest risks of using balancer or any decentralized exchange for that matter, is the risk of incurring impermanent loss, it mostly happens when in a pool one asset is highly volatile with respect to the other, how the deviation of price from market price leads to impermanent loss that has already been discussed above in detail.
  • Price Slippage : Slippage is defined as the price difference between the expected price of the trade and the price at which the trade is executed. Whenever the volume of trade is of the order of the size of the pool, then the slippage is huge that’s why it is very risky to trade on pools with low liquidity.
  • High gas fees : Since balancer is also built on Ethereum network just like many decentralized exchanges, the heavy traffic on Ethereum network has resulted in slower processing of transactions and increased gas price. 
  • Losing Private key : It’s important to note that although decentralized exchanges like balancer provides the user a greater control over their funds than centralized ones because of absence of any third party but this also means that if users somehow lose their private key there is no forget password to reset the key, the funds will be lost forever. So it’s very important to store it in a safe place where there is no chance of being hacked.
  • Oracle manipulation : DeFi protocols rely on “oracles” to provide them with off-chain data like the price of Ethereum. We have seen in the above sections that how the price is essentially a ratio of the no of tokens and is this price information is wrong then then balancer will allow liquidity to be added according to that incorrect ratio which will ultimately lead to impermanent loss for LPs. So depending on single source of information is always a risks because there always is a possibility of manipulation.
  • Hacking : Now since the codes of all of the defi protocols are open source, so hackers also have access to the code and if there are able to spot a bug before the user community does, they can always exploit it to their advantage.

So to conclude, DeFi right now is in its very early years but given the perks it comes along with and the freedom it provides to its users it won’t be any exaggeration to term it as the future of the finance with Balancer playing the role of New York Stock Exchange in that future.

Looking to develop a DeFi project like an exchange or swap platform or something else? Reach out to Tektorch.AI ---> Learn all about their Crypto Projects here

References

  • Balancer White paper
  • Finematics
  • IRM India Affiliate