Skip to content
Snippets Groups Projects
pay_helper.dart 4.77 KiB
import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../data/models/contact.dart';
import '../../../data/models/node_list_cubit.dart';
import '../../../data/models/node_type.dart';
import '../../../data/models/payment_cubit.dart';
import '../../../data/models/transaction.dart';
import '../../../data/models/transaction_cubit.dart';
import '../../../data/models/transaction_type.dart';
import '../../../g1/api.dart';
import '../../../shared_prefs.dart';
import '../data/models/bottom_nav_cubit.dart';
import 'contacts_cache.dart';
import 'logger.dart';
import 'ui_helpers.dart';

Future<void> payWithRetry(
    {required BuildContext context,
    required Contact to,
    required double amount,
    required String comment,
    bool isRetry = false,
    bool useMempool = false}) async {
  logger('Trying to pay state with useMempool: $useMempool');
  final TransactionCubit txCubit = context.read<TransactionCubit>();
  final PaymentCubit paymentCubit = context.read<PaymentCubit>();
  paymentCubit.sending();
  final String fromPubKey = SharedPreferencesHelper().getPubKey();
  final String contactPubKey = to.pubKey;
  final bool? confirmed = await _confirmSend(
      context, amount.toString(), humanizeContact(fromPubKey, to), isRetry);
  final Contact fromContact = await ContactsCache().getContact(fromPubKey);
  if (confirmed == null || !confirmed) {
    paymentCubit.sentFailed();
  } else {
    final PayResult result =
        await pay(to: contactPubKey, comment: comment, amount: amount);
    final Transaction tx = Transaction(
        type: TransactionType.pending,
        from: fromContact,
        to: to,
        amount: -amount * 100,
        comment: comment,
        debugInfo:
            'Node used: ${result.node != null ? result.node!.url : 'unknown'}',
        time: DateTime.now());
    if (result.message == 'success') {
      paymentCubit.sent();
      if (!context.mounted) {
        return;
      }
      showTooltip(
          context, tr('payment_successful'), tr('payment_successful_desc'));

      if (!isRetry) {
        // Add here the transaction to the pending list (so we can check it the tx is confirmed)
        txCubit.addPendingTransaction(tx);
      } else {
        // Update the previously failed tx with an update time and type pending
        txCubit.updatePendingTransaction(tx);
      }
    } else {
      /* this retry didn't work
        if (!useMempool) {
          throw RetryException();
        } */