Query editor
WITH wallets(label,wallet,scale) AS (VALUES('e957',0xe957a99f5134e7129c30ff87c173b536a38188f2,0.45e0),('5422',0x5422ee0965a121f0197c6885d4a373115f7eb418,0.65e0)),events AS (SELECT * FROM dune.tusa3112.result_rh_public6505_combined_events),self_lots AS (SELECT wallet,token,symbol,block_time,block_number,tx_index,tx_hash,token_in lot_qty,buy_cost_usd lot_cost_usd,IF(buy_cost_usd>0e0,'PAID','UNPAID_SELF') lot_kindFROM events WHERE token IS NOT NULL AND token_in>1e-12),external_lots AS (SELECT w.wallet,tr.contract_address token,MAX_BY(tr.symbol,tr.evt_index) symbol,tr.block_time,tr.block_number,COALESCE(t.index,0) tx_index,tr.tx_hash,SUM(COALESCE(tr.amount,0e0)) lot_qty,0e0 lot_cost_usd,'EXTERNAL' lot_kindFROM wallets w JOIN tokens.transfers tr ON tr."to"=w.walletLEFT JOIN robinhood.transactions t ON t.block_date=tr.block_date AND t.hash=tr.tx_hashWHERE tr.blockchain='robinhood'AND tr.block_date>=DATE '2026-06-01' AND tr.block_date<=CURRENT_DATEAND tr."from"<>w.walletAND COALESCE(tr.tx_from,0x0000000000000000000000000000000000000000)<>w.walletAND LOWER(tr.token_standard)<>'native'AND tr.contract_address NOT IN (0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73,0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168)GROUP BY 1,2,4,5,6,7),all_lots0 AS (SELECT * FROM self_lots UNION ALL SELECT * FROM external_lots),all_lots1 AS (SELECT *,SUM(lot_qty) OVER(PARTITION BY wallet,token ORDER BY block_number,tx_index,tx_hash,lot_kindROWS UNBOUNDED PRECEDING) cum_lot_endFROM all_lots0),lots AS (SELECT *,cum_lot_end-lot_qty cum_lot_start,lot_cost_usd/NULLIF(lot_qty,0e0) unit_cost_usdFROM all_lots1),removes0 AS (SELECT wallet,token,symbol,block_time,block_number,tx_index,tx_hash,token_out remove_qty,proceeds_usd,assigned_gas_usd,SUM(token_out) OVER(PARTITION BY wallet,tokenORDER BY block_number,tx_index,tx_hash ROWS UNBOUNDED PRECEDING) cum_remove_endFROM events WHERE token IS NOT NULL AND token_out>1e-12),removes AS (SELECT *,cum_remove_end-remove_qty cum_remove_start FROM removes0),removed AS (SELECT r.wallet,r.token,r.block_time,r.block_number,r.tx_index,r.tx_hash,r.remove_qty,r.proceeds_usd,r.assigned_gas_usd,COALESCE(SUM(GREATEST(LEAST(r.cum_remove_end,l.cum_lot_end)-GREATEST(r.cum_remove_start,l.cum_lot_start),0e0)),0e0) matched_qty,