Query editor
with latest_close_troves as (SELECT _borrower, _collateral, max(evt_block_time) as trove_updatedFROM ethos_reserve_v2_1_optimism.BorrowerOperations_evt_TroveUpdatedWHERE operation = 1GROUP BY _borrower, _collateral), -- gets a list of closed troves by borrowerlatest_open_troves as (SELECT _borrower, _collateral, max(evt_block_time) as trove_updatedFROM ethos_reserve_v2_1_optimism.BorrowerOperations_evt_TroveUpdatedWHERE operation = 0GROUP BY _borrower, _collateral),-- gets a list of closed troves by borrowerlatest_liquidated_troves as (SELECT _borrower, _collateral, max(evt_block_time) as trove_updatedFROM ethos_reserve_v2_1_optimism.TroveManager_evt_TroveLiquidatedGROUP BY _borrower, _collateral),open_troves as (SELECT DISTINCT lot.*FROM latest_open_troves as lotLEFT JOIN latest_close_troves as lct on lot._borrower = lct._borrower and lot._collateral = lct._collateralLEFT JOIN latest_liquidated_troves as llt on lot._borrower = llt._borrower and lot._collateral = llt._collateralWHERE (lot.trove_updated > lct.trove_updated OR lct.trove_updated IS NULL)AND (lot.trove_updated > llt.trove_updated OR llt.trove_updated IS NULL)), -- should be a list of only open trovestt as (SELECT a._borrower, a._collateral, a._coll, a._debt, a.evt_block_number, a.evt_index, a.evt_block_timeFROM ethos_reserve_v2_1_optimism.BorrowerOperations_evt_TroveUpdated as aRIGHT JOIN open_troves as b on a._borrower = b._borrower and a._collateral = b._collateralUNION ALLSELECT a._borrower, a._collateral, a._coll, a._debt, a.evt_block_number, a.evt_index, a.evt_block_timeFROM ethos_reserve_v2_1_optimism.BorrowerOperations_evt_TroveUpdated as aRIGHT JOIN open_troves as b on a._borrower = b._borrower and a._collateral = b._collateral),t as (select *, ROW_NUMBER() over (partition by _borrowerorder by evt_block_number desc, evt_index desc) as updateNumberfrom tt),-- tells us the min(upDateNumber) for each of the possible collateral typest_clean as (SELECT _borrower, _collateral, min(updateNumber) as updateNumberFROM tWHERE _coll > CAST(0 AS UINT256)GROUP BY _borrower, _collateral),weth_price as(SELECT oracle_price as weth_price, block_time as most_recent_blockFROM chainlink_optimism.price_feedsWHERE blockchain = 'optimism'--AND underlying_token_address = 0x4200000000000000000000000000000000000006AND feed_name = 'ETH / USD'and block_time = (SELECT max(block_time) FROM chainlink_optimism.price_feedsWHERE blockchain = 'optimism'--AND underlying_token_address = 0x4200000000000000000000000000000000000006AND feed_name = 'ETH / USD')