select top 20 COUNT(DISTINCT x.wallet) as n_wallet,
CASE WHEN tl.label is null THEN tm.attribute_value ELSE tl.label END as contract_label,
tl.project_name as contract_name,
tm.attribute_value as contract_address
FROM
(SELECT tx_sender as wallet,
min(block_timestamp) as first_tx,
tx_id
from terra.core.fact_transactions
group BY wallet,tx_id
HAVING first_tx between CURRENT_DATE-210 and CURRENT_DATE-180) x
left JOIN terra.core.fact_msg_attributes tm
ON tm.tx_id = x.tx_id
left JOIN terra.core.dim_address_labels tl
on tm.attribute_value = tl.address
WHERE tm.attribute_key IN ('_contract_address', 'contract_addr', 'contract_address', 'contract_name', 'contract')
GROUP BY contract_label, contract_name, contract_address
HAVING contract_name is not null
order BY n_wallet DESC