Query editor
WITH-- Optional: keep your alias decoding if you need it later.latest_licenseAlias AS (SELECTtokenId,FROM_UTF8(FROM_HEX(SUBSTRING(TRY_CAST(licenseAlias_binary AS VARCHAR), 3))) AS licenseAlias_textFROM (SELECTtokenId,licenseAlias_binary,ROW_NUMBER() OVER (PARTITION BY tokenId ORDER BY evt_block_number DESC) AS rnFROM devlicensedimo_v2_polygon.devlicensedimo_v2_evt_LicenseAliasSetWHERE licenseAlias_binary IS NOT NULL) subWHERE rn = 1),-- A single place to hold a safe far-future cap for timestamps.params AS (SELECT TIMESTAMP '2099-12-31 23:59:59' AS MAX_TS),/* Build connection records and compute a SAFE implicit disconnect time.- expiration is in SECONDS (not days).- If expiration is null/<=0/absurdly large, treat as open-ended capped at MAX_TS.- TRY(...) prevents arithmetic errors; COALESCE to MAX_TS on failure. */connections AS (SELECTc.tokenId,c.grantee,c.evt_block_time AS connection_time,COALESCE(TRY(CASEWHEN c.expiration IS NULL THEN (SELECT MAX_TS FROM params)WHEN CAST(c.expiration AS bigint) <= 0 THEN (SELECT MAX_TS FROM params)-- guard huge expirations (> 50 years) as effectively "no expiry"WHEN CAST(c.expiration AS bigint) > 50 * 365 * 24 * 3600 THEN (SELECT MAX_TS FROM params)ELSE date_add('second', CAST(c.expiration AS bigint), c.evt_block_time)END),(SELECT MAX_TS FROM params)) AS implicit_disconnect_timeFROM dimo_data_sharing_polygon.dimo_data_sharing_evt_PermissionsSet cWHERE c.permissions <> 0),-- Explicit disconnect events.disconnects AS (SELECTtokenId,grantee,evt_block_time AS disconnect_timeFROM dimo_data_sharing_polygon.dimo_data_sharing_evt_PermissionsSetWHERE permissions = 0),/* For each connection, choose the EARLIEST explicit disconnect after the connection,then take the min between that, the implicit/capped disconnect time, and NOW.This keeps open-ended connections clamped at current_timestamp. */