Blog

Explanation of @CryptoAlgebra 's Liquidity Pools ( Based on @CamelotDEX )

Algebra’s DEX is a concentrated liquidity DEX. Pools are consisting of two tokens.

For example, a pool can be created with USDC and WETH. Below is a breakdown of how to work with these pools, fetch price data, and understand the mathematics behind it, including the code and computation involved.


1. Finding the Pool Address

To interact with a specific liquidity pool, you need to find its address. This is possible through the Factory contract, which is responsible for managing all the pools. On Arbitrum, the Factory contract is deployed at the following address:

Factory contract:

https://arbiscan.io/address/0x1a3c9B1d2F0529D97f2afC5136Cc23e58f1FD35B

Using this Factory contract, you can search for the pool using the poolByPair mapping, which returns the pool's address if it has already been created.

If the pool doesn’t yet exist, you can use the computeAddress() function to compute the address deterministically.


2. Determining the Pool's Tokens

Once the pool is identified (for example, at the address https://arbiscan.io/address/0x7CcCBA38E2D959fe135e79AEBB57CCb27B128358) , you need to verify which tokens are involved and in what order.

In liquidity pools, the tokens are referred to as token0 and token1. The order of these tokens can be determined by comparing the addresses: the token with the smaller address is token0.

Code to Determine the Token Order:

For the pool at the above address, the tokens are WETH and USDT. Since WETH has a smaller address than USDT, WETH is token0 and USDT is token1.


3. Fetching the Current Price

The price of WETH in terms of USDT can be retrieved by querying the globalState variable of the pool. This variable contains the sqrtX96Price. In this case, the globalState returns the value:

3786433254360286272269346


4. Converting sqrtX96Price to the Real Price

To get the actual price, you need to square the value of sqrtX96Price and divide it by 2^192. Here's how the conversion works:

price = (sqrtX96Price * sqrtX96Price) / (2**192)


5. Interpreting the Price with Token Decimals

This calculated price value is 0.000000002284. Since USDT uses 6 decimals, this needs to be scaled accordingly (multiplied with 1e12). The actual price becomes 2284 USDT