getNetworkTime method

Future<DateTime?> getNetworkTime()

Fetches the current network time using NTP. Falls back to monotonic-adjusted cached NTP time if fetching fails.

Implementation

Future<DateTime?> getNetworkTime() async {
  try {
    DateTime ntpTime = await _networkTimeProvider().timeout(
      const Duration(seconds: 20),
      onTimeout: () {
        safeLog('NTP request timed out after 20 seconds');
        throw TimeoutException(
          'NTP request timed out',
          const Duration(seconds: 20),
        );
      },
    );

    safeLog('Network time: $ntpTime');

    final monotonicTimeMillis = await _getMonotonicTimeMillis();
    if (monotonicTimeMillis != null) {
      _runtimeSnapshot = NetworkTimeSnapshot(
        networkTime: ntpTime,
        monotonicTimeMillis: monotonicTimeMillis,
      );
      await localDataSource.storeNetworkTime(
        networkTime: ntpTime,
        monotonicTimeMillis: monotonicTimeMillis,
      );
    } else {
      safeLog('Monotonic time unavailable; skipping trusted time cache.');
    }

    return ntpTime;
  } catch (e) {
    DateTime? storedNTPTime = await _getNetworkTimeStoredOffline();
    safeLog('Stored Network time: $storedNTPTime', error: e);

    return storedNTPTime; // fallback to device time
  }
}