Query editor
-- part of a query repo-- query name: Outstanding Loans by Principal-- query link: https://dune.com/queries/6589462-- Breakdown of outstanding loans by principal amount ranges-- Groups loans into standard value buckets for analysis-- Converts all currencies to USD using price at loan start time-- Uses uploaded CSV data from Fabrica's loan tracking---- OPTIMIZATION NOTES:-- 1. Hardcoded decimals for known currencies (USDC=6, WETH=18) to avoid tokens.erc20 scan-- 2. Limited prices.usd to WETH only and date range of active loans-- 3. USDC treated as $1 (stablecoin)WITH date_bounds AS (-- Get the date range of active loans to limit price lookupsSELECTMIN(DATE(FROM_UNIXTIME(CAST(start_time AS BIGINT)))) AS min_date,MAX(DATE(FROM_UNIXTIME(CAST(start_time AS BIGINT)))) AS max_dateFROM dune.fabrica.dataset_fabrica_loansWHERE loan_status IN ('Active', 'Default')),-- Get daily WETH prices only for the relevant date rangeweth_prices AS (SELECTDATE(minute) AS price_date,AVG(price) AS price_usdFROM prices.usdWHERE blockchain = 'ethereum'AND contract_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 -- WETHAND minute >= (SELECT CAST(min_date AS TIMESTAMP) FROM date_bounds)AND minute < (SELECT CAST(max_date + INTERVAL '1' DAY AS TIMESTAMP) FROM date_bounds)GROUP BY DATE(minute)),-- Loan data with inline USD conversion-- Stablecoins (all $1): USDC (6 dec), USDT (6 dec), USAT (6 dec), DAI (18 dec)loans_with_usd AS (SELECTCASE-- USDC: 6 decimals, price = $1WHEN l.currency_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48THEN CAST(l.principal_amount AS DOUBLE) / 1e6-- USDT: 6 decimals, price = $1WHEN l.currency_address = 0xdAC17F958D2ee523a2206206994597C13D831ec7THEN CAST(l.principal_amount AS DOUBLE) / 1e6-- USAT (Tether America): 6 decimals, price = $1WHEN l.currency_address = 0x07041776f5007ACa2A54844F50503a18A72A8b68THEN CAST(l.principal_amount AS DOUBLE) / 1e6-- DAI: 18 decimals, price = $1WHEN l.currency_address = 0x6B175474E89094C44Da98b954EedeAC495271d0FTHEN CAST(l.principal_amount AS DOUBLE) / 1e18-- WETH: 18 decimals, use daily priceWHEN l.currency_address = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2THEN CAST(l.principal_amount AS DOUBLE) / 1e18 * COALESCE(wp.price_usd, 0)-- Unknown currency: assume 18 decimals and $1 (fallback)ELSE CAST(l.principal_amount AS DOUBLE) / 1e18END AS principal_usdFROM dune.fabrica.dataset_fabrica_loans lLEFT JOIN weth_prices wp ON DATE(FROM_UNIXTIME(CAST(l.start_time AS BIGINT))) = wp.price_dateWHERE l.loan_status IN ('Active', 'Default')