startSession method

Future<void> startSession({
  1. required dynamic onSuccess(
    1. dynamic
    ),
  2. required dynamic onError(
    1. Exception
    ),
})

Implementation

Future<void> startSession({
  required Function(dynamic) onSuccess,
  required Function(Exception) onError,
}) async {
  if (_sessionId.isEmpty) {
    const message =
        "Session can't be started due to undefined value of sessionId";
    logger.info(message);
    throw sessionNotStartedError(message);
  }

  logger.info('Starting session');
  final timer = Timer.periodic(const Duration(seconds: 3), (timer) async {
    try {
      final statusResponse = await fetchStatusUrl(_sessionId);

      if (statusResponse.session == null) return;

      // Check for failure status and handle timeout
      if (statusResponse.session!.statusV2 ==
          SessionStatus.PROOF_GENERATION_FAILED.name) {
        final currentTime = DateTime.now().millisecondsSinceEpoch;
        if (_lastFailureTime == null) {
          _lastFailureTime = currentTime;
        } else if (currentTime - _lastFailureTime! >= _failureTimeout) {
          clearInterval(_intervals, _sessionId);
          onError(providerFailedError(
              'Proof generation failed - timeout reached'));
          return;
        }
        return; // Continue monitoring if under timeout
      }

      // Reset failure time if status is not PROOF_GENERATION_FAILED
      _lastFailureTime = null;

      // check if the callback url is default or not
      final isDefaultCallbackUrl = getAppCallbackUrl() ==
          '${Constants.DEFAULT_RECLAIM_CALLBACK_URL}$_sessionId';

      if (isDefaultCallbackUrl) {
        if (statusResponse.session!.proofs != null &&
            statusResponse.session!.proofs!.isNotEmpty) {
          final proofs = statusResponse.session!.proofs;
          final verified = await verifyProof(proofs);
          if (!verified) {
            logger.info('Proof not verified: $proofs');
            throw proofNotVerifiedError('Unable to verify proof');
          }
          if (proofs?.length == 1) {
            onSuccess(proofs![0]);
          } else {
            onSuccess(proofs);
          }
          clearInterval(_intervals, _sessionId);
        }
      } else {
        if (statusResponse.session!.statusV2 ==
            SessionStatus.PROOF_SUBMISSION_FAILED.name) {
          throw proofSubmissionFailedError('Proof submission failed');
        }
        if (statusResponse.session!.statusV2 ==
            SessionStatus.PROOF_SUBMITTED.name) {
          onSuccess(
              'Proof submitted successfully to the custom callback url');
          clearInterval(_intervals, _sessionId);
        }
      }
    } catch (e) {
      logger.info('Error in startSession: $e');
      onError(e is Exception ? e : Exception(e.toString()));
      clearInterval(_intervals, _sessionId);
    }
  });

  _intervals[_sessionId] = timer;
  scheduleIntervalEndingTask(_intervals, _sessionId, onError);
}