Query editor
/* Dune: @gasweighing & Twitter/X: @Selectrong */with debt_token_txn as (select distinct evt_tx_hash as txn_hashfrom erc20_sonic.evt_transfer --- transferred debt tokenswhere contract_address in (0x2273cabad63b7d247a6b107e723c803fc49953a0 --- debt usdc.e token, 0xf6089b790fbf8f4812a79a31cfabeb00b06ba7bd --- debt ws token, 0x07b1adfb7d5795cf21bae8a77eceb222f2fafbce --- debt weth token)and casewhen '{{current_date}}' = 'exclude'then date_trunc('day', evt_block_time) < date_trunc('day', current_date)when '{{current_date}}' = 'include'then date_trunc('day', evt_block_time) <= date_trunc('day', current_date)else trueend --- exclude or include current date to optimize the query and accurecy), borrow_summary as (select date_trunc('day', b.block_time) as txn_date, bytearray_substring(b.topic1, 13, 20) as reserve_address --- borrowed asset, sum(bytearray_to_uint256(bytearray_substring(b."data", 33, 32))) as total_borrowed_raw --- the raw amount of asset borrowed, round(avg(bytearray_to_uint256(bytearray_substring(b."data", 97, 32)) / 1e27), 6) as avg_borrow_rate --- the raw value for the borrow ratefrom sonic.logs bjoin debt_token_txn d on b.tx_hash = d.txn_hashwhere b.topic0 = 0xb3d084820fb1a9decffb176436bd02558d15fac9b0ddfed8c465bc7359d7dce0 --- event for borrowing assetgroup by 1, 2), repay_summary as (select date_trunc('day', r.block_time) as txn_date, bytearray_substring(r.topic1, 13, 20) as reserve_address --- repayed asset, sum(bytearray_to_uint256(bytearray_substring(r."data", 1, 32))) as total_repaid_raw --- the raw amount of asset borrowedfrom sonic.logs rjoin debt_token_txn d on r.tx_hash = d.txn_hashwhere r.topic0 = 0xa534c8dbe71f871f9f3530e97a74601fea17b426cae02e1c5aee42c96c784051 --- event for repaying assetgroup by 1, 2), asset_market_formatted as (select date_trunc('day', "minute") as mkt_date, contract_address, symbol, decimals, avg(price) as mkt_pricefrom prices.usdwhere blockchain = 'sonic'and casewhen '{{current_date}}' = 'exclude'then date_trunc('day', "minute") < date_trunc('day', current_date)when '{{current_date}}' = 'include'then date_trunc('day', "minute") <= date_trunc('day', current_date)else trueendand contract_address in (0x29219dd400f2bf60e5a23d13be72b486d4038894, -- usdc.e0x039e2fb66102314ce7b64ce5ce3e5183bc94ad38, -- ws0x50c42deacd8fc9773493ed674b675be577f2634b -- weth)group by 1, 2, 3, 4), combined_summary as (select coalesce(b.txn_date, r.txn_date) as txn_date