with
deposited as (
select
event_contract,
event_data:to as user_address,
sum(event_data:amount) as inflow
from flow.core.fact_events
where event_type = 'TokensDeposited'
and tx_succeeded = 1
group by user_address, event_contract
),
withdrawn as (
select
event_contract,
event_data:from as user_address,
sum(event_data:amount) as outflow
from flow.core.fact_events
where event_type = 'TokensWithdrawn'
and tx_succeeded = 1
group by user_address, event_contract
),
price_flow as (
select avg(price_usd) as usd_price
from flow.core.fact_prices
where timestamp::date = (select max(timestamp::date) from flow.core.fact_prices)
and symbol = 'FLOW'
),
main as (
select user_address,
inflow, outflow,
inflow - outflow as balance,
usd_price * balance as balance_usd
from deposited