Skip to content
Snippets Groups Projects
wallet_view.dart 30.2 KiB
Newer Older
// ignore_for_file: use_build_context_synchronously

Hugo Trentesaux's avatar
Hugo Trentesaux committed
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:gecko/globals.dart';
import 'package:flutter/material.dart';
poka's avatar
poka committed
import 'package:gecko/models/g1_wallets_list.dart';
import 'package:gecko/models/widgets_keys.dart';
import 'package:gecko/providers/cesium_plus.dart';
poka's avatar
poka committed
import 'package:gecko/providers/home.dart';
poka's avatar
poka committed
import 'package:gecko/providers/substrate_sdk.dart';
poka's avatar
poka committed
import 'package:gecko/providers/wallet_options.dart';
import 'package:gecko/providers/my_wallets.dart';
poka's avatar
poka committed
import 'package:gecko/models/wallet_data.dart';
import 'package:gecko/providers/wallets_profiles.dart';
import 'package:gecko/screens/activity.dart';
import 'package:gecko/screens/common_elements.dart';
import 'package:gecko/screens/myWallets/choose_wallet.dart';
poka's avatar
poka committed
import 'package:gecko/screens/myWallets/unlocking_wallet.dart';
poka's avatar
poka committed
import 'package:gecko/screens/qrcode_fullscreen.dart';
import 'package:gecko/screens/transaction_in_progress.dart';
import 'package:provider/provider.dart';
poka's avatar
poka committed
import 'package:qr_flutter/qr_flutter.dart';

class WalletViewScreen extends StatelessWidget {
poka's avatar
poka committed
  const WalletViewScreen(
poka's avatar
poka committed
      {required this.pubkey, this.username, this.avatar, Key? key})
poka's avatar
poka committed
      : super(key: key);
poka's avatar
poka committed
  final String? pubkey;
  final String? username;
  final Image? avatar;
poka's avatar
poka committed
  final double buttonSize = 100;
  final double buttonFontSize = 18;

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    WalletsProfilesProvider walletProfile =
poka's avatar
poka committed
        Provider.of<WalletsProfilesProvider>(context, listen: false);
    CesiumPlusProvider cesiumPlusProvider =
poka's avatar
poka committed
        Provider.of<CesiumPlusProvider>(context, listen: false);
    walletProfile.address = pubkey!;
    SubstrateSdk sub = Provider.of<SubstrateSdk>(context, listen: false);
    HomeProvider homeProvider =
poka's avatar
poka committed
        Provider.of<HomeProvider>(context, listen: false);
    MyWalletsProvider myWalletProvider =
        Provider.of<MyWalletsProvider>(context, listen: false);
    WalletData? defaultWallet = myWalletProvider.getDefaultWallet();
    sub.setCurrentWallet(defaultWallet);
    // sub.spawnBlock();
    // sub.spawnBlock(0, 25);

poka's avatar
poka committed
        backgroundColor: backgroundColor,
poka's avatar
poka committed
        resizeToAvoidBottomInset: true,
poka's avatar
poka committed
          elevation: 0,
          toolbarHeight: 60 * ratio,
poka's avatar
poka committed
          actions: [
poka's avatar
poka committed
            Row(
              children: [
                Consumer<WalletsProfilesProvider>(
                    builder: (context, walletProfile, _) {
                  return IconButton(
poka's avatar
poka committed
                    onPressed: () async {
                      G1WalletsList? newContact;
                      g1WalletsBox.toMap().forEach((key, value) {
                        if (key == pubkey) newContact = value;
                      });
                      // G1WalletsList(pubkey: pubkey!, username: username);
                      await walletProfile.addContact(
                          newContact ?? G1WalletsList(pubkey: pubkey!));
poka's avatar
poka committed
                    },
                    icon: Icon(
                      walletProfile.isContact(pubkey!)
                          ? Icons.add_reaction_rounded
                          : Icons.add_reaction_outlined,
                      size: 35,
                    ),
                  );
                }),
                const SizedBox(width: 10),
                InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) {
                        return QrCodeFullscreen(
                          walletProfile.address!,
                        );
                      }),
poka's avatar
poka committed
                    );
poka's avatar
poka committed
                  },
                  child: QrImageWidget(
                    data: walletProfile.address!,
                    version: QrVersions.auto,
                    size: 80,
                  ),
                ),
              ],
            )
poka's avatar
poka committed
          ],
Hugo Trentesaux's avatar
Hugo Trentesaux committed
          title: SizedBox(
poka's avatar
poka committed
            height: 22,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
            child: Text('seeAWallet'.tr()),
poka's avatar
poka committed
          ),
        ),
        bottomNavigationBar: homeProvider.bottomAppBar(context),
        body: SafeArea(
          child: Column(children: <Widget>[
            walletProfile.headerProfileView(context, pubkey!, username),
            SizedBox(height: isTall ? 10 : 0),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
              Column(children: <Widget>[
                SizedBox(
poka's avatar
poka committed
                  height: buttonSize,
                  child: ClipOval(
                    child: Material(
                      color: yellowC, //const Color(0xffFFD58D), // button color
                          splashColor: orangeC, // inkwell color
                          child: const Padding(
poka's avatar
poka committed
                              padding: EdgeInsets.all(13),
                              child: Image(
                                  image: AssetImage(
                                      'assets/walletOptions/clock.png'),
                                  height: 90)),
                          onTap: () {
poka's avatar
poka committed
                            // _historyProvider.nPage = 1;
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) {
                                return ActivityScreen(
                                    address: pubkey,
                                    avatar:
                                        cesiumPlusProvider.defaultAvatar(50));
                          }),
                    ),
                  ),
                ),
                const SizedBox(height: 9),
poka's avatar
poka committed
                Text(
poka's avatar
poka committed
                  "displayNActivity".tr(),
                  textAlign: TextAlign.center,
poka's avatar
poka committed
                  style: TextStyle(
                      fontSize: buttonFontSize, fontWeight: FontWeight.w500),
              Consumer<SubstrateSdk>(builder: (context, sub, _) {
                WalletData? defaultWallet = myWalletProvider.getDefaultWallet();
                return FutureBuilder(
                  future: sub.certState(defaultWallet.address!,
poka's avatar
poka committed
                      pubkey!), // .canCertify(_defaultWallet.address!, pubkey!),
                  builder: (context, AsyncSnapshot<Map<String, int>> snapshot) {
                    if (snapshot.data == null) return const SizedBox();
                    String duration = '';
poka's avatar
poka committed
                    log.d('certDelay ${snapshot.data!['certDelay']}');
                    log.d('certRenewable ${snapshot.data!['certRenewable']}');
poka's avatar
poka committed
                    if (snapshot.data!['certDelay'] != null ||
                        snapshot.data!['certRenewable'] != null) {
                      final Duration durationSeconds = Duration(
poka's avatar
poka committed
                          seconds: snapshot.data!['certDelay'] ??
                              snapshot.data!['certRenewable']!);
                      final int seconds = durationSeconds.inSeconds;
                      final int minutes = durationSeconds.inMinutes;
                      if (seconds <= 0) {
                        duration = 'seconds'.tr(args: ['0']);
                      } else if (seconds <= 60) {
                        duration = 'seconds'.tr(args: [seconds.toString()]);
                      } else if (seconds <= 3600) {
                        duration = 'minutes'.tr(args: [minutes.toString()]);
                      } else if (seconds <= 86400) {
                        final int hours = durationSeconds.inHours;
                        final int minutesLeft = minutes - hours * 60;
                        String showMinutes = '';
                        if (minutesLeft < 60) {}
                        showMinutes =
                            'minutes'.tr(args: [minutesLeft.toString()]);
                        duration =
                            'hours'.tr(args: [hours.toString(), showMinutes]);
                      } else if (seconds <= 2592000) {
                        final int days = durationSeconds.inDays;
                        duration = 'days'.tr(args: [days.toString()]);
poka's avatar
poka committed
                      } else {
                        final int months =
                            (durationSeconds.inDays / 30).round();
                        duration = 'months'.tr(args: [months.toString()]);
                    final toStatus = snapshot.data!['toStatus'] ?? 0;

                    return Visibility(
poka's avatar
poka committed
                      visible: (snapshot.data != {}),
                      child: Column(children: <Widget>[
                        if (snapshot.data!['canCert'] != null ||
                            duration == 'seconds'.tr(args: ['0']))
poka's avatar
poka committed
                          Column(children: <Widget>[
                            SizedBox(
                              height: buttonSize,
                              child: ClipOval(
                                child: Material(
                                  color:
                                      const Color(0xffFFD58D), // button color
                                  child: InkWell(
poka's avatar
poka committed
                                      splashColor: orangeC, // inkwell color
                                      child: const Padding(
                                        padding: EdgeInsets.only(bottom: 0),
                                        child: Image(
                                            image: AssetImage(
                                                'assets/gecko_certify.png')),
                                      ),
                                      onTap: () async {
                                        final bool? result = await confirmPopup(
                                            context,
                                            "areYouSureYouWantToCertify".tr(
                                                args: [
                                                  getShortPubkey(pubkey!)
                                                ]));
                                        if (result ?? false) {
                                          String? pin;
                                          if (myWalletProvider.pinCode == '') {
                                            pin = await Navigator.push(
poka's avatar
poka committed
                                              context,
                                              MaterialPageRoute(
                                                builder: (homeContext) {
                                                  return UnlockingWallet(
                                                      wallet: defaultWallet);
                                                },
                                              ),
                                            );
                                          }
                                          if (pin != null ||
                                              myWalletProvider.pinCode != '') {
poka's avatar
poka committed
                                            WalletsProfilesProvider
                                                walletViewProvider = Provider
poka's avatar
poka committed
                                                    .of<WalletsProfilesProvider>(
                                                        context,
                                                        listen: false);
                                            final acc = sub.getCurrentWallet();
                                            sub.certify(
poka's avatar
poka committed
                                                acc.address!,
poka's avatar
poka committed
                                                walletViewProvider.address!,
                                                pin ??
                                                    myWalletProvider.pinCode);
poka's avatar
poka committed

                                            Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                  builder: (context) {
                                                return const TransactionInProgress(
                                                    transType: 'cert');
                                              }),
                                            );
                                          }
                                        }
                                      }),
                                ),
                              ),
                            ),
                            const SizedBox(height: 9),
                            Text(
poka's avatar
poka committed
                              "certify".tr(),
poka's avatar
poka committed
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: buttonFontSize,
                                  fontWeight: FontWeight.w500),
                            ),
                          ])
                        else if (toStatus == 1)
                          waitToCert('mustConfirmHisIdentity', duration)
                        else if (snapshot.data!['certRenewable'] != null &&
                            duration != 'seconds'.tr(args: ['0']))
                          waitToCert('canRenewCertInX', duration)
                        else if (snapshot.data!['certDelay'] != null)
                          waitToCert('mustWaitXBeforeCertify', duration)
              Column(children: <Widget>[
                SizedBox(
poka's avatar
poka committed
                  height: buttonSize,
                  child: ClipOval(
                    child: Material(
                      color: const Color(0xffFFD58D), // button color
                      child: InkWell(
                          splashColor: orangeC, // inkwell color
                          child: const Padding(
                              padding: EdgeInsets.all(20),
                              child: Image(
                                  image: AssetImage('assets/copy_key.png'),
                                  height: 90)),
                          onTap: () {
                            Clipboard.setData(ClipboardData(text: pubkey));
poka's avatar
poka committed
                            snackCopyKey(context);
                          }),
                    ),
                  ),
                ),
                const SizedBox(height: 9),
poka's avatar
poka committed
                Text(
Hugo Trentesaux's avatar
Hugo Trentesaux committed
                  "copyAddress".tr(),
                  textAlign: TextAlign.center,
poka's avatar
poka committed
                  style: TextStyle(
                      fontSize: buttonFontSize, fontWeight: FontWeight.w500),
            Consumer<SubstrateSdk>(builder: (context, sub, _) {
poka's avatar
poka committed
              return Opacity(
                opacity: sub.nodeConnected ? 1 : 0.5,
poka's avatar
poka committed
                child: Container(
                  height: buttonSize,
                  decoration: BoxDecoration(
                    color: const Color(0xff7c94b6),
                    borderRadius: const BorderRadius.all(Radius.circular(100)),
                    border: Border.all(
                      color: const Color(0xFF6c4204),
                      width: 4,
                    ),
                  ),
                  child: ClipOval(
                    child: Material(
                      color: orangeC, // button color
                      child: InkWell(
                          splashColor: yellowC,
                          onTap: sub.nodeConnected
                              ? () {
                                  paymentPopup(context, walletProfile);
                                }
                              : null, // inkwell color
poka's avatar
poka committed
                          child: const Padding(
                              padding: EdgeInsets.all(14),
                              child: Image(
                                image: AssetImage('assets/vector_white.png'),
poka's avatar
poka committed
                    ),
                  ),
poka's avatar
poka committed
              );
            }),
            const SizedBox(height: 9),
            Consumer<SubstrateSdk>(builder: (context, sub, _) {
poka's avatar
poka committed
              return Text(
poka's avatar
poka committed
                'doATransfer'.tr(),
poka's avatar
poka committed
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: sub.nodeConnected ? Colors.black : Colors.grey[500],
poka's avatar
poka committed
                    fontSize: buttonFontSize,
                    fontWeight: FontWeight.w500),
              );
            }),
poka's avatar
poka committed
            SizedBox(height: isTall ? 50 : 20)
poka's avatar
poka committed

  Widget waitToCert(String status, String duration) {
    return Column(children: <Widget>[
      SizedBox(
        height: buttonSize,
        child: Padding(
          padding: const EdgeInsets.only(bottom: 0),
          child: Container(
            foregroundDecoration: const BoxDecoration(
              color: Colors.grey,
              backgroundBlendMode: BlendMode.saturation,
            ),
            child: const Opacity(
              opacity: 0.5,
              child: Image(image: AssetImage('assets/gecko_certify.png')),
            ),
          ),
        ),
      ),
      Text(
        status.tr(args: [duration]),
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: buttonFontSize - 4,
            fontWeight: FontWeight.w400,
            color: Colors.grey[600]),
      ),
    ]);
  }

poka's avatar
poka committed
  void paymentPopup(
      BuildContext context, WalletsProfilesProvider walletViewProvider) {
    // WalletsProfilesProvider _walletViewProvider =
    //     Provider.of<WalletsProfilesProvider>(context, listen: false);
poka's avatar
poka committed
    final myWalletProvider =
        Provider.of<MyWalletsProvider>(context, listen: false);
poka's avatar
poka committed
    final sub = Provider.of<SubstrateSdk>(context, listen: false);
poka's avatar
poka committed

    const double shapeSize = 20;
    WalletData? defaultWallet = myWalletProvider.getDefaultWallet();
    log.d(defaultWallet.address);

    bool canValidate = false;

poka's avatar
poka committed
    final bool isUdUnit = configBox.get('isUdUnit') ?? false;
    final udValue = sub.udValue;
    final double balanceRatio = isUdUnit ? round(udValue / 100, 6) : 1;

poka's avatar
poka committed
    showModalBottomSheet<void>(
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(shapeSize),
            topLeft: Radius.circular(shapeSize),
          ),
        ),
        isScrollControlled: true,
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            if (walletViewProvider.payAmount.text != '' &&
poka's avatar
poka committed
                (double.parse(walletViewProvider.payAmount.text) +
                        2 / balanceRatio) <=
poka's avatar
poka committed
                    (balanceCache[defaultWallet.address] ?? 0) &&
                walletViewProvider.address != defaultWallet.address) {
poka's avatar
poka committed
              if ((balanceCache[pubkey] == 0 || balanceCache[pubkey] == null) &&
poka's avatar
poka committed
                  double.parse(walletViewProvider.payAmount.text) <
                      5 / balanceRatio) {
                canValidate = false;
              } else {
                canValidate = true;
              }
            } else {
              canValidate = false;
            }
poka's avatar
poka committed
            final bool isUdUnit = configBox.get('isUdUnit') ?? false;
            return Padding(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom),
              child: Container(
                height: 400,
                decoration: const ShapeDecoration(
                  color: Color(0xffffeed1),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(shapeSize),
                      topLeft: Radius.circular(shapeSize),
                    ),
poka's avatar
poka committed
                  ),
                ),
poka's avatar
poka committed
                  padding: const EdgeInsets.only(
                      top: 24, bottom: 0, left: 24, right: 24),
                  child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
poka's avatar
poka committed
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
Hugo Trentesaux's avatar
Hugo Trentesaux committed
                              Text(
                                'executeATransfer'.tr(),
                                style: const TextStyle(
poka's avatar
poka committed
                                    fontSize: 26, fontWeight: FontWeight.w700),
                              ),
                              IconButton(
                                iconSize: 40,
                                icon: const Icon(Icons.cancel_outlined),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ]),
poka's avatar
poka committed
                          'from'.tr(),
                          style: TextStyle(
                              fontSize: 19,
                              fontWeight: FontWeight.w500,
                              color: Colors.grey[600]),
                        ),
poka's avatar
poka committed
                        const SizedBox(height: 10),
                        Consumer<SubstrateSdk>(builder: (context, sub, _) {
poka's avatar
poka committed
                          return InkWell(
                            key: keyChangeChest,
                              String? pin;
                              if (myWalletProvider.pinCode == '') {
                                pin = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (homeContext) {
                                      return UnlockingWallet(
                                          wallet: defaultWallet);
                                    },
                                  ),
                                );
                              }
                              if (pin != null ||
                                  myWalletProvider.pinCode != '') {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) {
                                    return ChooseWalletScreen(
                                        pin: pin ?? myWalletProvider.pinCode);
poka's avatar
poka committed
                            },
                            child: Container(
                              width: double.infinity,
                              decoration: BoxDecoration(
                                border: Border.all(
poka's avatar
poka committed
                                    color: Colors.blueAccent.shade200,
                                    width: 2),
poka's avatar
poka committed
                                borderRadius: const BorderRadius.all(
poka's avatar
poka committed
                                    Radius.circular(10.0)),
poka's avatar
poka committed
                              ),
poka's avatar
poka committed
                              padding: const EdgeInsets.all(10),
                              child: Row(children: [
poka's avatar
poka committed
                                const Spacer(),
poka's avatar
poka committed
                                balance(context, defaultWallet.address!, 20)
poka's avatar
poka committed
                          );
                        }),
                        const Spacer(),

                        // const SizedBox(height: 10),
                        Text(
poka's avatar
poka committed
                          'amount'.tr(),
poka's avatar
poka committed
                          style: TextStyle(
                              fontSize: 19,
                              fontWeight: FontWeight.w500,
                              color: Colors.grey[600]),
                        ),
                        const SizedBox(height: 10),
                        TextField(
                          key: keyAmountField,
                          controller: walletViewProvider.payAmount,
poka's avatar
poka committed
                          autofocus: true,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          onChanged: (_) => setState(() {
                            // _walletViewProvider.reload();
                          }),
                          inputFormatters: <TextInputFormatter>[
                            // FilteringTextInputFormatter.digitsOnly,
                            FilteringTextInputFormatter.deny(',',
                                replacementString: '.'),
poka's avatar
poka committed
                            FilteringTextInputFormatter.allow(
                                RegExp(r'(^\d+\.?\d{0,2})')),
poka's avatar
poka committed
                          // onChanged: (v) => _searchProvider.reload(),
poka's avatar
poka committed
                          decoration: InputDecoration(
                            hintText: '0.00',
poka's avatar
poka committed
                            suffix: Text(isUdUnit
poka's avatar
poka committed
                                ? 'ud'.tr(args: [''])
poka's avatar
poka committed
                                : currencyName), // udUnitDisplay(40),
poka's avatar
poka committed
                            filled: true,
                            fillColor: Colors.transparent,
                            // border: OutlineInputBorder(
                            //     borderSide:
                            //         BorderSide(color: Colors.grey[500], width: 2),
                            //     borderRadius: BorderRadius.circular(8)),

                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey[500]!, width: 2),
                              borderRadius: BorderRadius.circular(8),
poka's avatar
poka committed
                            ),
poka's avatar
poka committed
                            contentPadding: const EdgeInsets.all(20),
                          ),
                          style: const TextStyle(
                            fontSize: 40,
                            color: Colors.black,
                            fontWeight: FontWeight.w600,
                          ),
poka's avatar
poka committed
                        // const SizedBox(height: 40),
                        const Spacer(),
                        SizedBox(
                          width: double.infinity,
                          height: 60,
                          child: ElevatedButton(
                            key: keyConfirmPayment,
poka's avatar
poka committed
                            style: ElevatedButton.styleFrom(
poka's avatar
poka committed
                              foregroundColor: Colors.white, elevation: 4,
                              backgroundColor: orangeC, // foreground
                            onPressed: canValidate
                                    String? pin;
                                    if (myWalletProvider.pinCode == '') {
                                      pin = await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (homeContext) {
                                            return UnlockingWallet(
                                                wallet: defaultWallet);
                                          },
                                        ),
                                      );
                                    }
                                    log.d(pin);
                                    if (pin != null ||
                                        myWalletProvider.pinCode != '') {
                                      // Payment workflow !
                                      WalletsProfilesProvider
                                          walletViewProvider =
                                          Provider.of<WalletsProfilesProvider>(
                                              context,
                                              listen: false);
                                      SubstrateSdk sub =
                                          Provider.of<SubstrateSdk>(context,
                                              listen: false);
                                      final acc = sub.getCurrentWallet();
                                          "fromAddress: ${acc.address!},destAddress: ${walletViewProvider.address!}, amount: ${double.parse(walletViewProvider.payAmount.text)},  password: $pin");
                                      sub.pay(
                                          fromAddress: acc.address!,
                                          destAddress:
                                              walletViewProvider.address!,
                                              walletViewProvider
                                          password:
                                              pin ?? myWalletProvider.pinCode);
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) {
                                          return const TransactionInProgress();
                                        }),
                                      );
                                    }
poka's avatar
poka committed
                                  }
                                : null,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
                            child: Text(
                              'executeTheTransfer'.tr(),
                              style: const TextStyle(
poka's avatar
poka committed
                                  fontSize: 20, fontWeight: FontWeight.w600),
                            ),
                          ),
                        ),
                        const Spacer(),
poka's avatar
poka committed
              ),
        }).then((value) => walletViewProvider.payAmount.text = '');
poka's avatar
poka committed
  }