Query editor
WITH daily_events AS (SELECTp.contract_address AS address,p.token0,p.token1,p.dec0 AS dec0,p.dec1 AS dec1,p.pid, -- corrected heree.*,date_trunc('day', e.evt_block_time) AS event_day,ROW_NUMBER() OVER (PARTITION BY p.contract_address, date_trunc('day', e.evt_block_time)ORDER BY e.evt_block_time DESC) AS rnFROM dune.sonusexchange.result_pairs_reserves pJOIN shadow_sonic.pair_evt_sync eON p.contract_address = e.contract_addressWHERE e.evt_block_time >= CAST('{{timestamp}}' AS timestamp)),deduped_events AS (SELECT *FROM daily_eventsWHERE rn = 1),events_with_token_value AS (SELECTde.*,tv.token0_value,ROW_NUMBER() OVER (PARTITION BY de.address, de.evt_block_timeORDER BY tv.call_block_time DESC) AS tv_rnFROM deduped_events deLEFT JOIN (SELECTcontract_address,tokenIn,call_block_time,output_0 * 1.0 / amountIn AS token0_valueFROM shadow_sonic.pair_call_getamountout) tvON tv.contract_address = de.addressAND tv.tokenIn = de.token0AND tv.call_block_time <= de.evt_block_time),final AS (SELECTe.evt_block_time,CAST(e.event_day AS date) AS block_date,CAST(146 AS int) AS chain_id,e.token0 AS underlying_token_address,CAST(0 AS bigint) AS underlying_token_index,e.address AS pool_address,e.pid AS pid,e.reserve0 / POWER(10, COALESCE(e.dec0, 18)) AS underlying_token_amount,(e.reserve0 / POWER(10, COALESCE(e.dec0, 18))) * t.price_usd AS underlying_token_amount_usdFROM events_with_token_value eLEFT JOIN LATERAL (