Query editor
/** [Title] History: Total Staked TON & TVL (Time Series)** [Description]* This query reconstructs the entire history of "Total Staked TON" and "TVL".* It merges `ChangedFactor` and `ChangedBalance` events to calculate the exact* staked amount at every point in time and joins it with daily price data.** [Logic]* 1. Price History: Fetches daily TON prices.* 2. Event Aggregation: Combines Factor and Balance change events into a single timeline.* 3. Fill Forward: Uses `LAST_VALUE(IGNORE NULLS)` to determine the valid Factor and Balance for every event.* 4. Daily Snapshot: Aggregates the final state of each day to match with daily price data.* 5. Calculation:* - Staked TON = (Balance * Factor) / 1e54* - TVL = Staked TON * Daily Price*/WITH price_history AS (-- 1. Get daily price history for TONSELECTDATE(timestamp) as day_date,priceFROM prices.dayWHEREcontract_address = 0x2be5e8c109e2197D077D13A82dAead6a9b3433C5AND timestamp >= CAST('2023-01-01' AS TIMESTAMP) -- Adjust start date if needed),raw_events AS (-- 2. Fetch ChangedFactor eventsSELECTevt_block_time,evt_block_number,evt_index,CAST(json_extract_scalar("next", '$.factor') AS DOUBLE) as factor_change,NULL as balance_changeFROM tokamak_network_ethereum.sWTON_evt_ChangedFactorUNION ALL-- 3. Fetch ChangedBalance eventsSELECTevt_block_time,evt_block_number,evt_index,NULL as factor_change,CAST(json_extract_scalar(newTotalBalance, '$.balance') AS DOUBLE) as balance_changeFROM tokamak_network_ethereum.sWTON_evt_ChangedBalance),state_reconstruction AS (-- 4. Fill Forward logic to get the state at every eventSELECTevt_block_time,DATE(evt_block_time) as day_date,-- Get the latest valid FactorLAST_VALUE(factor_change) IGNORE NULLS OVER (ORDER BY evt_block_number, evt_index