Query editor
-- Query 2.G (REVISED - Using dex.trades for Price): query_feem_gas_on_contracts_30dWITH project_gas_spent_s AS (SELECTcmap.project_id,SUM(TRY_CAST(tx.gas_used AS DOUBLE) * (TRY_CAST(tx.gas_price AS DOUBLE) / 1e18)) AS total_gas_sFROMsonic.transactions txINNER JOINdune.soniclabs.result_view_feem_project_contract_map cmapON LOWER(CAST(tx.to AS VARCHAR)) = LOWER(cmap.contract_address)WHEREtx.block_time >= NOW() - INTERVAL '30' DAYAND tx.success = trueGROUP BY1),latest_sonic_price_from_dex AS ( -- Renamed CTE for claritySELECT(dt.amount_usd /CASEWHEN LOWER(dt.token_bought_symbol) = 'ws' THEN dt.token_bought_amountWHEN LOWER(dt.token_sold_symbol) = 'ws' THEN dt.token_sold_amountELSE NULL -- Should ideally not happen due to WHERE clause, but good for safetyEND) AS sonic_usdFROMdex.trades dtWHEREdt.blockchain = 'sonic'AND ((LOWER(dt.token_bought_symbol) = 'ws' AND LOWER(dt.token_sold_symbol) IN ('usdc', 'usdt', 'dai', 'usd+', 'frax', 'usdb')) OR(LOWER(dt.token_sold_symbol) = 'ws' AND LOWER(dt.token_bought_symbol) IN ('usdc', 'usdt', 'dai', 'usd+', 'frax', 'usdb')))AND dt.amount_usd > 0AND dt.token_bought_amount > 0 -- Avoid division by zero if amounts are not populatedAND dt.token_sold_amount > 0 -- Avoid division by zeroORDER BYdt.block_time DESCLIMIT 1)SELECTcmap_agg.project_name AS "Project",COALESCE(pgs.total_gas_s, 0) AS "S",COALESCE(pgs.total_gas_s * lsf.sonic_usd, 0) AS "USD"FROMproject_gas_spent_s pgsINNER JOIN (SELECT DISTINCT project_id, project_name FROM dune.soniclabs.result_view_feem_project_contract_map) cmap_agg ON cmap_agg.project_id = pgs.project_id-- Crucial Change: Use LEFT JOIN for the price to ensure rows are returned even if price is temporarily unavailableLEFT JOINlatest_sonic_price_from_dex lsf ON true -- `ON true` effectively makes it a conditional cross join if lsf has a row, or preserves pgs rows if notORDER BY"USD" DESC, "S" DESC -- Added secondary sort by S in case USD is 0 for multiple;