from static method

PaymentRequestDoc? from(
  1. List<TransactionDoc> transactions
)

Implementation

static PaymentRequestDoc? from(List<TransactionDoc> transactions) {
  // Extract requests
  final requestTxs = transactions
      .where((t) => t.error == null)
      .map(RequestDoc.from)
      .whereNotNull()
      .toList()
    // Sort by txId
    ..sort((left, right) => left.txId.compareTo(right.txId));

  // Extract initial request
  final invokedRequest =
      requestTxs.firstWhereOrNull((tx) => tx.request != null);

  if (invokedRequest == null) {
    return null;
  }

  // Extract potential failure status
  final lastNonPendingTxStatus = requestTxs
      .lastWhereOrNull((tx) => tx.status != RequestStatus.pending)
      ?.status;

  // Check if there's a matching transfer
  final transfers = transactions
      .where((t) => t.error == null && t.txId > invokedRequest.txId)
      .whereNotNull();

  final requestValue = invokedRequest.amount;

  // Check if single or multi-phase transfer is complete
  final isComplete =
      transfers.map((t) => t.commitTransfer ?? t.transfer).whereNotNull().any(
            (transfer) => transfer.steps
                .where((step) => !step.metadata.isFee)
                .any((step) => step.amount == requestValue),
          );

  late final RequestStatus requestStatus;
  if (isComplete) {
    requestStatus = RequestStatus.completed;
  } else {
    // Check if initiateTransfer exists without completed commitTransfer
    requestStatus = transfers.any((t) => t.initiateTransfer != null)
        ? RequestStatus.inProgress
        : RequestStatus.pending;
  }

  return PaymentRequestDoc(
    invokedRequest,
    lastNonPendingTxStatus ?? requestStatus,
  );
}