LP Price
This function calculateLpValue calculates the value of a single LP (Liquidity Provider) token for a specific pool. It fetches the total liquidity from both tokens in the pool (liquidityA and liquidityB) and the total supply of LP tokens.
- The liquidity value is computed by summing the reserve, claimable, and cancelable fields for each token.
- Token A (e.g., USDC) is assumed to have 6 decimals, and Token B (e.g., WETH) has 18 decimals.
- Prices for the assets (e.g., ETH = 2000, USDC = 1) are hardcoded for simplicity.
- LP tokens are assumed to use 18 decimals.
- The final LP token value is calculated as:
import { createPublicClient, formatUnits, http } from 'viem'
import { base } from 'viem/chains'
const calculateLpValue = async (): Promise<number> => {
const _abi = [
{
inputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
},
],
name: 'totalSupply',
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
},
],
stateMutability: 'view',
type: 'function',
},
{
inputs: [
{
internalType: 'bytes32',
name: 'key',
type: 'bytes32',
},
],
name: 'getLiquidity',
outputs: [
{
components: [
{
internalType: 'uint256',
name: 'reserve',
type: 'uint256',
},
{
internalType: 'uint256',
name: 'claimable',
type: 'uint256',
},
{
internalType: 'uint256',
name: 'cancelable',
type: 'uint256',
},
],
internalType: 'struct ILiquidityVault.Liquidity',
name: 'liquidityA',
type: 'tuple',
},
{
components: [
{
internalType: 'uint256',
name: 'reserve',
type: 'uint256',
},
{
internalType: 'uint256',
name: 'claimable',
type: 'uint256',
},
{
internalType: 'uint256',
name: 'cancelable',
type: 'uint256',
},
],
internalType: 'struct ILiquidityVault.Liquidity',
name: 'liquidityB',
type: 'tuple',
},
],
stateMutability: 'view',
type: 'function',
},
] as const
const publicClient = createPublicClient({
chain: base,
transport: http(),
})
const ethPrice = 2000
const usdcPrice = 1
const LIQUDITY_VAULT_ADDRESS = '0xeA0E19fbca0D9D707f3dA10Ef846cC255B0aAdf3'
const poolKey =
'0xc8cbe608c82ee9c4c30f01d7c0eefd977538ac396ed34430aa3993bfe0d363ae'
const [totalSupply, [totalLiquidityA, totalLiquidityB]] =
await publicClient.multicall({
allowFailure: false,
contracts: [
{
address: LIQUDITY_VAULT_ADDRESS,
abi: _abi,
functionName: 'totalSupply',
args: [BigInt(poolKey)],
},
{
address: LIQUDITY_VAULT_ADDRESS,
abi: _abi,
functionName: 'getLiquidity',
args: [poolKey],
},
],
})
const wethBalance = Number(
formatUnits(
totalLiquidityB.reserve +
totalLiquidityB.claimable +
totalLiquidityB.cancelable,
18,
),
)
const usdcBalance = Number(
formatUnits(
totalLiquidityA.reserve +
totalLiquidityA.claimable +
totalLiquidityA.cancelable,
6,
),
)
const lpBalance = Number(formatUnits(totalSupply, 18))
return (wethBalance * ethPrice + usdcBalance * usdcPrice) / lpBalance
}