Skip to main content

raw_price_to_usd

Schema: lib_lending

Description

This function is designed to convert raw USD prices stored in lending pools, particularly those monitored by a "lens" contract, into human-readable USD amounts. Lending pools often store prices as raw values that require manipulation to obtain the equivalent USD amount. This function facilitates this conversion process, ensuring accurate and accessible USD representations.

Usage

Function signature

lib_lending.raw_price_to_usd(raw_val numeric, underlying_token_decimals integer) returns numeric

Parameters

NameTypeDescription
raw_valnumericThe raw USD price (exchange rate) value to be converted into USD.
underlying_token_decimalsintegerThe number of decimal places used by the underlying token. This parameter is crucial for correctly scaling the raw value to obtain the USD amount.

Results

NameTypeDescription
usd_valnumericThe human-readable USD amount corresponding to the provided raw exchange rate value

Examples

Simple example with hard-coded USDT values
-- Simple example using hard-coded USDT raw value and decimals
select lib_lending.raw_price_to_usd(
1000274990000000000000000000000,
6
) as usd_price
Get the USD price for each underlying and LP token Hover lending pools
with lending_pools as (
-- Get all lending pools for the company
select
lpm.account as lending_pool_contract,
lpm.symbol,
lpm.decimals,
lpm.underlying_token_decimals
from lib_lending.lending_pool_metadata_for_company('Hover') as lpm
),
-- Get an array of contract addresses for the company
lending_pool_contracts as (
select array_agg(lp.lending_pool_contract) as contracts
from lending_pools lp
),
-- Price of underlying token in USD
most_recent_prices as (
select
lp.lending_pool_contract as contract,
cm.val as raw_price,
lib_lending.raw_price_to_usd(cm.val, lp.underlying_token_decimals) as usd_price
from lib.latest_custom_metric_by_contract(
(select contracts from lending_pool_contracts),
'price'
) cm
join lending_pools lp on cm.contract = lp.lending_pool_contract
),
-- Exchange rates between LP tokens and underlying tokens
most_recent_exchange_rates as (
select
lp.lending_pool_contract as contract,
cm.val as latest_exchange_rate
from lib.latest_custom_metric_by_contract(
(select contracts from lending_pool_contracts),
'exchangeRate'
) cm
join lending_pools lp on cm.contract = lp.lending_pool_contract
)
select
lp.lending_pool_contract,
lp.symbol,
lp.underlying_token_decimals,
mpr.raw_price,
mpr.usd_price as usd_price_of_underlying_token,
lib_lending.lp_to_usd_amount(
1 * power(10, lp.decimals::numeric), -- 1 LP token
mrer.latest_exchange_rate,
lp.underlying_token_decimals,
mpr.usd_price
) as usd_value_of_single_lp_token
from lending_pools lp
join most_recent_exchange_rates mrer on lp.lending_pool_contract = mrer.contract
join most_recent_prices mpr on lp.lending_pool_contract = mpr.contract;