Query editor
-- RailgunSmartWallet (V2) addresses per chainWITH wallets AS (SELECT * FROM (VALUES('ethereum', 0xfa7093cdd9ee6932b4eb2c9e1cde7ce00b1fa4b9),('polygon', 0x19b620929f97b7b990801496c3b361ca5def8c71),('bnb', 0x590162bf4b50f6576a459b75309ee21d92178a10),('arbitrum', 0xfa7093cdd9ee6932b4eb2c9e1cde7ce00b1fa4b9)) AS t(blockchain, smart_wallet)),relevant_transfers AS (-- Pre-filter once; both inflows/outflows aggregate over this set.SELECT t.blockchain,t.contract_address,t.symbol,t.amount_raw,t.amount_usd,t.price_usd,t.block_time,CASE WHEN t."to" = w.smart_wallet THEN 'in' ELSE 'out' END AS directionFROM tokens.transfers tJOIN wallets w ON t.blockchain = w.blockchainWHERE t.block_date >= DATE '2022-01-01'AND t.token_standard IN ('erc20', 'bep20')AND (t."to" = w.smart_wallet OR t."from" = w.smart_wallet)),inflows AS (SELECT blockchain, contract_address AS token_address,MAX_BY(symbol, block_time) AS symbol,SUM(amount_raw) AS in_raw,SUM(amount_usd) AS in_usdFROM relevant_transfersWHERE direction = 'in'GROUP BY 1, 2),outflows AS (SELECT blockchain, contract_address AS token_address,SUM(amount_raw) AS out_raw,SUM(amount_usd) AS out_usdFROM relevant_transfersWHERE direction = 'out'GROUP BY 1, 2),last_prices AS (-- Latest price seen on any transfer involving the wallet (good enough for snapshot pricing)SELECT blockchain, contract_address AS token_address,MAX_BY(price_usd, block_time) AS price_usdFROM relevant_transfersWHERE price_usd IS NOT NULL AND price_usd > 0GROUP BY 1, 2)SELECTCOALESCE(i.blockchain, o.blockchain) AS blockchain,COALESCE(i.token_address, o.token_address) AS token_address,COALESCE(e.symbol, i.symbol) AS symbol,e.decimals AS decimals,CAST(COALESCE(i.in_raw, UINT256 '0') AS DECIMAL(38, 0)) AS total_shielded_raw,CAST(COALESCE(o.out_raw, UINT256 '0') AS DECIMAL(38, 0)) AS total_unshielded_raw,CAST(COALESCE(i.in_raw, UINT256 '0') AS DECIMAL(38, 0))- CAST(COALESCE(o.out_raw, UINT256 '0') AS DECIMAL(38, 0)) AS expected_balance_raw,COALESCE(i.in_usd, 0) AS total_shielded_usd,