diff --git a/lib/services/coins/particl/particl_wallet.dart b/lib/services/coins/particl/particl_wallet.dart deleted file mode 100644 index d1b8ea761..000000000 --- a/lib/services/coins/particl/particl_wallet.dart +++ /dev/null @@ -1,3538 +0,0 @@ -// /* -// * This file is part of Stack Wallet. -// * -// * Copyright (c) 2023 Cypher Stack -// * All Rights Reserved. -// * The code is distributed under GPLv3 license, see LICENSE file for details. -// * Generated by Cypher Stack on 2023-05-26 -// * -// */ -// -// import 'dart:async'; -// import 'dart:convert'; -// import 'dart:io'; -// -// import 'package:bech32/bech32.dart'; -// import 'package:bip32/bip32.dart' as bip32; -// import 'package:bip39/bip39.dart' as bip39; -// import 'package:bitcoindart/bitcoindart.dart'; -// import 'package:bs58check/bs58check.dart' as bs58check; -// import 'package:crypto/crypto.dart'; -// import 'package:decimal/decimal.dart'; -// import 'package:flutter/foundation.dart'; -// import 'package:isar/isar.dart'; -// import 'package:stackwallet/db/isar/main_db.dart'; -// import 'package:stackwallet/electrumx_rpc/cached_electrumx_client.dart'; -// import 'package:stackwallet/electrumx_rpc/electrumx_client.dart'; -// import 'package:stackwallet/models/balance.dart'; -// import 'package:stackwallet/models/isar/models/isar_models.dart' as isar_models; -// import 'package:stackwallet/models/paymint/fee_object_model.dart'; -// import 'package:stackwallet/models/signing_data.dart'; -// import 'package:stackwallet/services/coins/coin_service.dart'; -// import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart'; -// import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart'; -// import 'package:stackwallet/services/event_bus/events/global/updated_in_background_event.dart'; -// import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; -// import 'package:stackwallet/services/event_bus/global_event_bus.dart'; -// import 'package:stackwallet/services/mixins/wallet_cache.dart'; -// import 'package:stackwallet/services/mixins/wallet_db.dart'; -// import 'package:stackwallet/services/mixins/xpubable.dart'; -// import 'package:stackwallet/services/node_service.dart'; -// import 'package:stackwallet/services/transaction_notification_tracker.dart'; -// import 'package:stackwallet/utilities/amount/amount.dart'; -// import 'package:stackwallet/utilities/bip32_utils.dart'; -// import 'package:stackwallet/utilities/constants.dart'; -// import 'package:stackwallet/utilities/default_nodes.dart'; -// import 'package:stackwallet/utilities/enums/coin_enum.dart'; -// import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart'; -// import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; -// import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; -// import 'package:stackwallet/utilities/format.dart'; -// import 'package:stackwallet/utilities/logger.dart'; -// import 'package:stackwallet/utilities/prefs.dart'; -// import 'package:stackwallet/widgets/crypto_notifications.dart'; -// import 'package:tuple/tuple.dart'; -// import 'package:uuid/uuid.dart'; -// -// const int MINIMUM_CONFIRMATIONS = 1; -// final Amount DUST_LIMIT = Amount( -// rawValue: BigInt.from(294), -// fractionDigits: Coin.particl.decimals, -// ); -// -// const String GENESIS_HASH_MAINNET = -// "0000ee0784c195317ac95623e22fddb8c7b8825dc3998e0bb924d66866eccf4c"; -// const String GENESIS_HASH_TESTNET = -// "0000594ada5310b367443ee0afd4fa3d0bbd5850ea4e33cdc7d6a904a7ec7c90"; -// -// String constructDerivePath({ -// required DerivePathType derivePathType, -// required int networkWIF, -// int account = 0, -// required int chain, -// required int index, -// }) { -// String coinType; -// switch (networkWIF) { -// case 0x6c: // PART mainnet wif -// coinType = "44"; // PART mainnet -// break; -// default: -// throw Exception("Invalid Particl network wif used!"); -// } -// -// int purpose; -// switch (derivePathType) { -// case DerivePathType.bip44: -// purpose = 44; -// break; -// case DerivePathType.bip84: -// purpose = 84; -// break; -// default: -// throw Exception("DerivePathType $derivePathType not supported"); -// } -// -// return "m/$purpose'/$coinType'/$account'/$chain/$index"; -// } -// -// class ParticlWallet extends CoinServiceAPI -// with -// WalletCache, -// WalletDB -// // , CoinControlInterface -// implements -// XPubAble { -// ParticlWallet({ -// required String walletId, -// required String walletName, -// required Coin coin, -// required ElectrumXClient client, -// required CachedElectrumXClient cachedClient, -// required TransactionNotificationTracker tracker, -// required SecureStorageInterface secureStore, -// MainDB? mockableOverride, -// }) { -// txTracker = tracker; -// _walletId = walletId; -// _walletName = walletName; -// _coin = coin; -// _electrumXClient = client; -// _cachedElectrumXClient = cachedClient; -// _secureStore = secureStore; -// initCache(walletId, coin); -// initWalletDB(mockableOverride: mockableOverride); -// // initCoinControlInterface( -// // walletId: walletId, -// // walletName: walletName, -// // coin: coin, -// // db: db, -// // getChainHeight: () => chainHeight, -// // refreshedBalanceCallback: (balance) async { -// // _balance = balance; -// // await updateCachedBalance(_balance!); -// // }, -// // ); -// } -// -// static const integrationTestFlag = -// bool.fromEnvironment("IS_INTEGRATION_TEST"); -// -// final _prefs = Prefs.instance; -// -// Timer? timer; -// late final Coin _coin; -// -// late final TransactionNotificationTracker txTracker; -// -// NetworkType get _network { -// switch (coin) { -// case Coin.particl: -// return particl; -// default: -// throw Exception("Invalid network type!"); -// } -// } -// -// @override -// set isFavorite(bool markFavorite) { -// _isFavorite = markFavorite; -// updateCachedIsFavorite(markFavorite); -// } -// -// @override -// bool get isFavorite => _isFavorite ??= getCachedIsFavorite(); -// -// bool? _isFavorite; -// -// @override -// Coin get coin => _coin; -// -// @override -// Future> get utxos => db.getUTXOs(walletId).findAll(); -// -// @override -// Future> get transactions => -// db.getTransactions(walletId).sortByTimestampDesc().findAll(); -// -// @override -// Future get currentReceivingAddress async => -// (await _currentReceivingAddress).value; -// -// Future get _currentReceivingAddress async => -// (await db -// .getAddresses(walletId) -// .filter() -// .typeEqualTo(isar_models.AddressType.p2wpkh) -// .subTypeEqualTo(isar_models.AddressSubType.receiving) -// .sortByDerivationIndexDesc() -// .findFirst()) ?? -// await _generateAddressForChain(0, 0, DerivePathTypeExt.primaryFor(coin)); -// -// Future get currentChangeAddress async => -// (await _currentChangeAddress).value; -// -// Future get _currentChangeAddress async => -// (await db -// .getAddresses(walletId) -// .filter() -// .typeEqualTo(isar_models.AddressType.p2wpkh) -// .subTypeEqualTo(isar_models.AddressSubType.change) -// .sortByDerivationIndexDesc() -// .findFirst()) ?? -// await _generateAddressForChain(1, 0, DerivePathTypeExt.primaryFor(coin)); -// -// @override -// Future exit() async { -// _hasCalledExit = true; -// timer?.cancel(); -// timer = null; -// stopNetworkAlivePinging(); -// } -// -// bool _hasCalledExit = false; -// -// @override -// bool get hasCalledExit => _hasCalledExit; -// -// @override -// Future get fees => _feeObject ??= _getFees(); -// Future? _feeObject; -// -// @override -// Future get maxFee async { -// final fee = (await fees).fast as String; -// final satsFee = Decimal.parse(fee) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt()); -// return satsFee.floor().toBigInt().toInt(); -// } -// -// @override -// Future> get mnemonic => _getMnemonicList(); -// -// @override -// Future get mnemonicString => -// _secureStore.read(key: '${_walletId}_mnemonic'); -// -// @override -// Future get mnemonicPassphrase => _secureStore.read( -// key: '${_walletId}_mnemonicPassphrase', -// ); -// -// Future get chainHeight async { -// try { -// final result = await _electrumXClient.getBlockHeadTip(); -// final height = result["height"] as int; -// await updateCachedChainHeight(height); -// if (height > storedChainHeight) { -// GlobalEventBus.instance.fire( -// UpdatedInBackgroundEvent( -// "Updated current chain height in $walletId $walletName!", -// walletId, -// ), -// ); -// } -// return height; -// } catch (e, s) { -// Logging.instance.log("Exception caught in chainHeight: $e\n$s", -// level: LogLevel.Error); -// return storedChainHeight; -// } -// } -// -// @override -// int get storedChainHeight => getCachedChainHeight(); -// -// DerivePathType addressType({required String address}) { -// Uint8List? decodeBase58; -// Segwit? decodeBech32; -// try { -// decodeBase58 = bs58check.decode(address); -// } catch (err) { -// // Base58check decode fail -// } -// -// // return DerivePathType.bip84; -// if (decodeBase58 != null) { -// if (decodeBase58[0] == _network.pubKeyHash) { -// // P2PKH -// return DerivePathType.bip44; -// } -// throw ArgumentError('Invalid version or Network mismatch'); -// } else { -// try { -// decodeBech32 = segwit.decode(address, particl.bech32!); -// } catch (err) { -// // Bech32 decode fail -// } -// if (_network.bech32 != decodeBech32!.hrp) { -// throw ArgumentError('Invalid prefix or Network mismatch'); -// } -// if (decodeBech32.version != 0) { -// throw ArgumentError('Invalid address version'); -// } -// // P2WPKH -// return DerivePathType.bip84; -// } -// } -// -// bool longMutex = false; -// -// @override -// Future recoverFromMnemonic({ -// required String mnemonic, -// String? mnemonicPassphrase, -// required int maxUnusedAddressGap, -// required int maxNumberOfIndexesToCheck, -// required int height, -// }) async { -// longMutex = true; -// final start = DateTime.now(); -// try { -// Logging.instance.log("IS_INTEGRATION_TEST: $integrationTestFlag", -// level: LogLevel.Info); -// if (!integrationTestFlag) { -// final features = await electrumXClient.getServerFeatures(); -// Logging.instance.log("features: $features", level: LogLevel.Info); -// switch (coin) { -// case Coin.particl: -// if (features['genesis_hash'] != GENESIS_HASH_MAINNET) { -// throw Exception("genesis hash does not match main net!"); -// } -// break; -// default: -// throw Exception( -// "Attempted to generate a ParticlWallet using a non particl coin type: ${coin.name}"); -// } -// // if (_networkType == BasicNetworkType.main) { -// // if (features['genesis_hash'] != GENESIS_HASH_MAINNET) { -// // throw Exception("genesis hash does not match main net!"); -// // } -// // } else if (_networkType == BasicNetworkType.test) { -// // if (features['genesis_hash'] != GENESIS_HASH_TESTNET) { -// // throw Exception("genesis hash does not match test net!"); -// // } -// // } -// } -// // check to make sure we aren't overwriting a mnemonic -// // this should never fail -// if ((await mnemonicString) != null || -// (await this.mnemonicPassphrase) != null) { -// longMutex = false; -// throw Exception("Attempted to overwrite mnemonic on restore!"); -// } -// await _secureStore.write( -// key: '${_walletId}_mnemonic', value: mnemonic.trim()); -// await _secureStore.write( -// key: '${_walletId}_mnemonicPassphrase', -// value: mnemonicPassphrase ?? "", -// ); -// -// await _recoverWalletFromBIP32SeedPhrase( -// mnemonic: mnemonic.trim(), -// mnemonicPassphrase: mnemonicPassphrase ?? "", -// maxUnusedAddressGap: maxUnusedAddressGap, -// maxNumberOfIndexesToCheck: maxNumberOfIndexesToCheck, -// ); -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from recoverFromMnemonic(): $e\n$s", -// level: LogLevel.Error); -// longMutex = false; -// rethrow; -// } -// longMutex = false; -// -// final end = DateTime.now(); -// Logging.instance.log( -// "$walletName recovery time: ${end.difference(start).inMilliseconds} millis", -// level: LogLevel.Info); -// } -// -// Future> _checkGaps( -// int maxNumberOfIndexesToCheck, -// int maxUnusedAddressGap, -// int txCountBatchSize, -// bip32.BIP32 root, -// DerivePathType type, -// int chain) async { -// List addressArray = []; -// int returningIndex = -1; -// Map> derivations = {}; -// int gapCounter = 0; -// for (int index = 0; -// index < maxNumberOfIndexesToCheck && gapCounter < maxUnusedAddressGap; -// index += txCountBatchSize) { -// List iterationsAddressArray = []; -// Logging.instance.log( -// "index: $index, \t GapCounter $chain ${type.name}: $gapCounter", -// level: LogLevel.Info); -// -// final _id = "k_$index"; -// Map txCountCallArgs = {}; -// final Map receivingNodes = {}; -// -// for (int j = 0; j < txCountBatchSize; j++) { -// final derivePath = constructDerivePath( -// derivePathType: type, -// networkWIF: root.network.wif, -// chain: chain, -// index: index + j, -// ); -// final node = await Bip32Utils.getBip32NodeFromRoot(root, derivePath); -// -// String addressString; -// isar_models.AddressType addrType; -// switch (type) { -// case DerivePathType.bip44: -// addressString = P2PKH( -// data: PaymentData(pubkey: node.publicKey), -// network: _network) -// .data -// .address!; -// addrType = isar_models.AddressType.p2pkh; -// break; -// case DerivePathType.bip84: -// addressString = P2WPKH( -// network: _network, -// data: PaymentData(pubkey: node.publicKey)) -// .data -// .address!; -// addrType = isar_models.AddressType.p2wpkh; -// break; -// default: -// throw Exception("DerivePathType $type not supported"); -// } -// -// final address = isar_models.Address( -// walletId: walletId, -// subType: chain == 0 -// ? isar_models.AddressSubType.receiving -// : isar_models.AddressSubType.change, -// type: addrType, -// publicKey: node.publicKey, -// value: addressString, -// derivationIndex: index + j, -// derivationPath: isar_models.DerivationPath()..value = derivePath, -// ); -// -// receivingNodes.addAll({ -// "${_id}_$j": { -// "node": node, -// "address": address, -// } -// }); -// txCountCallArgs.addAll({ -// "${_id}_$j": addressString, -// }); -// } -// -// // get address tx counts -// final counts = await _getBatchTxCount(addresses: txCountCallArgs); -// -// // check and add appropriate addresses -// for (int k = 0; k < txCountBatchSize; k++) { -// int count = counts["${_id}_$k"]!; -// if (count > 0) { -// final node = receivingNodes["${_id}_$k"]; -// final address = node["address"] as isar_models.Address; -// // add address to array -// addressArray.add(address); -// iterationsAddressArray.add(address.value); -// // set current index -// returningIndex = index + k; -// // reset counter -// gapCounter = 0; -// // add info to derivations -// derivations[address.value] = { -// "pubKey": Format.uint8listToString( -// (node["node"] as bip32.BIP32).publicKey), -// "wif": (node["node"] as bip32.BIP32).toWIF(), -// }; -// } -// -// // increase counter when no tx history found -// if (count == 0) { -// gapCounter++; -// } -// } -// // cache all the transactions while waiting for the current function to finish. -// unawaited(getTransactionCacheEarly(iterationsAddressArray)); -// } -// return { -// "addressArray": addressArray, -// "index": returningIndex, -// "derivations": derivations -// }; -// } -// -// Future getTransactionCacheEarly(List allAddresses) async { -// try { -// final List> allTxHashes = -// await _fetchHistory(allAddresses); -// for (final txHash in allTxHashes) { -// try { -// unawaited(cachedElectrumXClient.getTransaction( -// txHash: txHash["tx_hash"] as String, -// verbose: true, -// coin: coin, -// )); -// } catch (e) { -// continue; -// } -// } -// } catch (e) { -// // -// } -// } -// -// Future _recoverWalletFromBIP32SeedPhrase({ -// required String mnemonic, -// required String mnemonicPassphrase, -// int maxUnusedAddressGap = 20, -// int maxNumberOfIndexesToCheck = 1000, -// bool isRescan = false, -// }) async { -// longMutex = true; -// -// Map> p2pkhReceiveDerivations = {}; -// Map> p2wpkhReceiveDerivations = {}; -// Map> p2pkhChangeDerivations = {}; -// Map> p2wpkhChangeDerivations = {}; -// -// final root = await Bip32Utils.getBip32Root( -// mnemonic, -// mnemonicPassphrase, -// _network, -// ); -// -// List p2pkhReceiveAddressArray = []; -// List p2wpkhReceiveAddressArray = []; -// int p2pkhReceiveIndex = -1; -// int p2wpkhReceiveIndex = -1; -// -// List p2pkhChangeAddressArray = []; -// List p2wpkhChangeAddressArray = []; -// int p2pkhChangeIndex = -1; -// int p2wpkhChangeIndex = -1; -// -// // actual size is 24 due to p2pkh, and p2wpkh so 12x2 -// const txCountBatchSize = 12; -// -// try { -// // receiving addresses -// Logging.instance -// .log("checking receiving addresses...", level: LogLevel.Info); -// final resultReceive44 = _checkGaps(maxNumberOfIndexesToCheck, -// maxUnusedAddressGap, txCountBatchSize, root, DerivePathType.bip44, 0); -// -// final resultReceive84 = _checkGaps(maxNumberOfIndexesToCheck, -// maxUnusedAddressGap, txCountBatchSize, root, DerivePathType.bip84, 0); -// -// Logging.instance -// .log("checking change addresses...", level: LogLevel.Info); -// // change addresses -// final resultChange44 = _checkGaps(maxNumberOfIndexesToCheck, -// maxUnusedAddressGap, txCountBatchSize, root, DerivePathType.bip44, 1); -// -// final resultChange84 = _checkGaps(maxNumberOfIndexesToCheck, -// maxUnusedAddressGap, txCountBatchSize, root, DerivePathType.bip84, 1); -// -// await Future.wait( -// [resultReceive44, resultReceive84, resultChange44, resultChange84]); -// -// p2pkhReceiveAddressArray = -// (await resultReceive44)['addressArray'] as List; -// p2pkhReceiveIndex = (await resultReceive44)['index'] as int; -// p2pkhReceiveDerivations = (await resultReceive44)['derivations'] -// as Map>; -// -// p2wpkhReceiveAddressArray = -// (await resultReceive84)['addressArray'] as List; -// p2wpkhReceiveIndex = (await resultReceive84)['index'] as int; -// p2wpkhReceiveDerivations = (await resultReceive84)['derivations'] -// as Map>; -// -// p2pkhChangeAddressArray = -// (await resultChange44)['addressArray'] as List; -// p2pkhChangeIndex = (await resultChange44)['index'] as int; -// p2pkhChangeDerivations = (await resultChange44)['derivations'] -// as Map>; -// -// p2wpkhChangeAddressArray = -// (await resultChange84)['addressArray'] as List; -// p2wpkhChangeIndex = (await resultChange84)['index'] as int; -// p2wpkhChangeDerivations = (await resultChange84)['derivations'] -// as Map>; -// -// // save the derivations (if any) -// if (p2pkhReceiveDerivations.isNotEmpty) { -// await addDerivations( -// chain: 0, -// derivePathType: DerivePathType.bip44, -// derivationsToAdd: p2pkhReceiveDerivations); -// } -// -// if (p2wpkhReceiveDerivations.isNotEmpty) { -// await addDerivations( -// chain: 0, -// derivePathType: DerivePathType.bip84, -// derivationsToAdd: p2wpkhReceiveDerivations); -// } -// if (p2pkhChangeDerivations.isNotEmpty) { -// await addDerivations( -// chain: 1, -// derivePathType: DerivePathType.bip44, -// derivationsToAdd: p2pkhChangeDerivations); -// } -// -// if (p2wpkhChangeDerivations.isNotEmpty) { -// await addDerivations( -// chain: 1, -// derivePathType: DerivePathType.bip84, -// derivationsToAdd: p2wpkhChangeDerivations); -// } -// -// // If restoring a wallet that never received any funds, then set receivingArray manually -// // If we didn't do this, it'd store an empty array -// if (p2pkhReceiveIndex == -1) { -// final address = -// await _generateAddressForChain(0, 0, DerivePathType.bip44); -// p2pkhReceiveAddressArray.add(address); -// } -// -// if (p2wpkhReceiveIndex == -1) { -// final address = -// await _generateAddressForChain(0, 0, DerivePathType.bip84); -// p2wpkhReceiveAddressArray.add(address); -// } -// -// // If restoring a wallet that never sent any funds with change, then set changeArray -// // manually. If we didn't do this, it'd store an empty array. -// if (p2pkhChangeIndex == -1) { -// final address = -// await _generateAddressForChain(1, 0, DerivePathType.bip44); -// p2pkhChangeAddressArray.add(address); -// } -// -// if (p2wpkhChangeIndex == -1) { -// final address = -// await _generateAddressForChain(1, 0, DerivePathType.bip84); -// p2wpkhChangeAddressArray.add(address); -// } -// -// if (isRescan) { -// await db.updateOrPutAddresses([ -// ...p2wpkhReceiveAddressArray, -// ...p2wpkhChangeAddressArray, -// ...p2pkhReceiveAddressArray, -// ...p2pkhChangeAddressArray, -// ]); -// } else { -// await db.putAddresses([ -// ...p2wpkhReceiveAddressArray, -// ...p2wpkhChangeAddressArray, -// ...p2pkhReceiveAddressArray, -// ...p2pkhChangeAddressArray, -// ]); -// } -// -// await _updateUTXOs(); -// -// await Future.wait([ -// updateCachedId(walletId), -// updateCachedIsFavorite(false), -// ]); -// -// longMutex = false; -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from _recoverWalletFromBIP32SeedPhrase(): $e\n$s", -// level: LogLevel.Error); -// -// longMutex = false; -// rethrow; -// } -// } -// -// Future refreshIfThereIsNewData() async { -// if (longMutex) return false; -// if (_hasCalledExit) return false; -// Logging.instance.log("refreshIfThereIsNewData", level: LogLevel.Info); -// -// try { -// bool needsRefresh = false; -// Set txnsToCheck = {}; -// -// for (final String txid in txTracker.pendings) { -// if (!txTracker.wasNotifiedConfirmed(txid)) { -// txnsToCheck.add(txid); -// } -// } -// -// for (String txid in txnsToCheck) { -// final txn = await electrumXClient.getTransaction(txHash: txid); -// int confirmations = txn["confirmations"] as int? ?? 0; -// bool isUnconfirmed = confirmations < MINIMUM_CONFIRMATIONS; -// if (!isUnconfirmed) { -// // unconfirmedTxs = {}; -// needsRefresh = true; -// break; -// } -// } -// if (!needsRefresh) { -// var allOwnAddresses = await _fetchAllOwnAddresses(); -// List> allTxs = await _fetchHistory( -// allOwnAddresses.map((e) => e.value).toList(growable: false)); -// for (Map transaction in allTxs) { -// final txid = transaction['tx_hash'] as String; -// if ((await db -// .getTransactions(walletId) -// .filter() -// .txidMatches(txid) -// .findFirst()) == -// null) { -// Logging.instance.log( -// " txid not found in address history already ${transaction['tx_hash']}", -// level: LogLevel.Info); -// needsRefresh = true; -// break; -// } -// } -// } -// return needsRefresh; -// } catch (e, s) { -// Logging.instance.log( -// "Exception caught in refreshIfThereIsNewData: $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future getAllTxsToWatch() async { -// if (_hasCalledExit) return; -// List unconfirmedTxnsToNotifyPending = []; -// List unconfirmedTxnsToNotifyConfirmed = []; -// -// final currentChainHeight = await chainHeight; -// -// final txCount = await db.getTransactions(walletId).count(); -// -// const paginateLimit = 50; -// -// for (int i = 0; i < txCount; i += paginateLimit) { -// final transactions = await db -// .getTransactions(walletId) -// .offset(i) -// .limit(paginateLimit) -// .findAll(); -// for (final tx in transactions) { -// if (tx.isConfirmed(currentChainHeight, MINIMUM_CONFIRMATIONS)) { -// // get all transactions that were notified as pending but not as confirmed -// if (txTracker.wasNotifiedPending(tx.txid) && -// !txTracker.wasNotifiedConfirmed(tx.txid)) { -// unconfirmedTxnsToNotifyConfirmed.add(tx); -// } -// } else { -// // get all transactions that were not notified as pending yet -// if (!txTracker.wasNotifiedPending(tx.txid)) { -// unconfirmedTxnsToNotifyPending.add(tx); -// } -// } -// } -// } -// -// // notify on unconfirmed transactions -// for (final tx in unconfirmedTxnsToNotifyPending) { -// final confirmations = tx.getConfirmations(currentChainHeight); -// -// if (tx.type == isar_models.TransactionType.incoming) { -// CryptoNotificationsEventBus.instance.fire( -// CryptoNotificationEvent( -// title: "Incoming transaction", -// walletId: walletId, -// date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000), -// shouldWatchForUpdates: confirmations < MINIMUM_CONFIRMATIONS, -// txid: tx.txid, -// confirmations: confirmations, -// requiredConfirmations: MINIMUM_CONFIRMATIONS, -// walletName: walletName, -// coin: coin, -// ), -// ); -// -// await txTracker.addNotifiedPending(tx.txid); -// } else if (tx.type == isar_models.TransactionType.outgoing) { -// CryptoNotificationsEventBus.instance.fire( -// CryptoNotificationEvent( -// title: "Sending transaction", -// walletId: walletId, -// date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000), -// shouldWatchForUpdates: confirmations < MINIMUM_CONFIRMATIONS, -// txid: tx.txid, -// confirmations: confirmations, -// requiredConfirmations: MINIMUM_CONFIRMATIONS, -// walletName: walletName, -// coin: coin, -// ), -// ); -// -// await txTracker.addNotifiedPending(tx.txid); -// } -// } -// -// // notify on confirmed -// for (final tx in unconfirmedTxnsToNotifyConfirmed) { -// if (tx.type == isar_models.TransactionType.incoming) { -// CryptoNotificationsEventBus.instance.fire( -// CryptoNotificationEvent( -// title: "Incoming transaction confirmed", -// walletId: walletId, -// date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000), -// shouldWatchForUpdates: false, -// txid: tx.txid, -// requiredConfirmations: MINIMUM_CONFIRMATIONS, -// walletName: walletName, -// coin: coin, -// ), -// ); -// -// await txTracker.addNotifiedConfirmed(tx.txid); -// } else if (tx.type == isar_models.TransactionType.outgoing) { -// CryptoNotificationsEventBus.instance.fire( -// CryptoNotificationEvent( -// title: "Outgoing transaction confirmed", -// walletId: walletId, -// date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000), -// shouldWatchForUpdates: false, -// txid: tx.txid, -// requiredConfirmations: MINIMUM_CONFIRMATIONS, -// walletName: walletName, -// coin: coin, -// ), -// ); -// -// await txTracker.addNotifiedConfirmed(tx.txid); -// } -// } -// } -// -// bool _shouldAutoSync = false; -// -// @override -// bool get shouldAutoSync => _shouldAutoSync; -// -// @override -// set shouldAutoSync(bool shouldAutoSync) { -// if (_shouldAutoSync != shouldAutoSync) { -// _shouldAutoSync = shouldAutoSync; -// if (!shouldAutoSync) { -// timer?.cancel(); -// timer = null; -// stopNetworkAlivePinging(); -// } else { -// startNetworkAlivePinging(); -// refresh(); -// } -// } -// } -// -// @override -// bool get isRefreshing => refreshMutex; -// -// bool refreshMutex = false; -// -// //TODO Show percentages properly/more consistently -// /// Refreshes display data for the wallet -// @override -// Future refresh() async { -// if (refreshMutex) { -// Logging.instance.log("$walletId $walletName refreshMutex denied", -// level: LogLevel.Info); -// return; -// } else { -// refreshMutex = true; -// } -// -// try { -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.syncing, -// walletId, -// coin, -// ), -// ); -// -// GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.0, walletId)); -// -// GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.1, walletId)); -// -// final currentHeight = await chainHeight; -// const storedHeight = 1; //await storedChainHeight; -// -// Logging.instance -// .log("chain height: $currentHeight", level: LogLevel.Info); -// Logging.instance -// .log("cached height: $storedHeight", level: LogLevel.Info); -// -// if (currentHeight != storedHeight) { -// GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.2, walletId)); -// await _checkChangeAddressForTransactions(); -// -// GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.3, walletId)); -// await _checkCurrentReceivingAddressesForTransactions(); -// -// final fetchFuture = _refreshTransactions(); -// final utxosRefreshFuture = _updateUTXOs(); -// GlobalEventBus.instance -// .fire(RefreshPercentChangedEvent(0.50, walletId)); -// -// final feeObj = _getFees(); -// GlobalEventBus.instance -// .fire(RefreshPercentChangedEvent(0.60, walletId)); -// -// GlobalEventBus.instance -// .fire(RefreshPercentChangedEvent(0.70, walletId)); -// _feeObject = Future(() => feeObj); -// -// await utxosRefreshFuture; -// GlobalEventBus.instance -// .fire(RefreshPercentChangedEvent(0.80, walletId)); -// -// await fetchFuture; -// await getAllTxsToWatch(); -// GlobalEventBus.instance -// .fire(RefreshPercentChangedEvent(0.90, walletId)); -// } -// -// refreshMutex = false; -// GlobalEventBus.instance.fire(RefreshPercentChangedEvent(1.0, walletId)); -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.synced, -// walletId, -// coin, -// ), -// ); -// -// if (shouldAutoSync) { -// timer ??= Timer.periodic(const Duration(seconds: 30), (timer) async { -// Logging.instance.log( -// "Periodic refresh check for $walletId $walletName in object instance: $hashCode", -// level: LogLevel.Info); -// if (await refreshIfThereIsNewData()) { -// await refresh(); -// GlobalEventBus.instance.fire(UpdatedInBackgroundEvent( -// "New data found in $walletId $walletName in background!", -// walletId)); -// } -// }); -// } -// } catch (error, strace) { -// refreshMutex = false; -// GlobalEventBus.instance.fire( -// NodeConnectionStatusChangedEvent( -// NodeConnectionStatus.disconnected, -// walletId, -// coin, -// ), -// ); -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.unableToSync, -// walletId, -// coin, -// ), -// ); -// Logging.instance.log( -// "Caught exception in refreshWalletData(): $error\n$strace", -// level: LogLevel.Error); -// } -// } -// -// @override -// Future> prepareSend({ -// required String address, -// required Amount amount, -// Map? args, -// }) async { -// try { -// final feeRateType = args?["feeRate"]; -// final customSatsPerVByte = args?["satsPerVByte"] as int?; -// final feeRateAmount = args?["feeRateAmount"]; -// final utxos = args?["UTXOs"] as Set?; -// -// if (customSatsPerVByte != null) { -// // check for send all -// bool isSendAll = false; -// if (amount == balance.spendable) { -// isSendAll = true; -// } -// -// final bool coinControl = utxos != null; -// -// final result = await coinSelection( -// satoshiAmountToSend: amount.raw.toInt(), -// selectedTxFeeRate: -1, -// satsPerVByte: customSatsPerVByte, -// recipientAddress: address, -// isSendAll: isSendAll, -// utxos: utxos?.toList(), -// coinControl: coinControl, -// ); -// -// Logging.instance -// .log("PREPARE SEND RESULT: $result", level: LogLevel.Info); -// if (result is int) { -// switch (result) { -// case 1: -// throw Exception("Insufficient balance!"); -// case 2: -// throw Exception("Insufficient funds to pay for transaction fee!"); -// default: -// throw Exception("Transaction failed with error code $result"); -// } -// } else { -// final hex = result["hex"]; -// if (hex is String) { -// final fee = result["fee"] as int; -// final vSize = result["vSize"] as int; -// -// Logging.instance.log("txHex: $hex", level: LogLevel.Info); -// Logging.instance.log("fee: $fee", level: LogLevel.Info); -// Logging.instance.log("vsize: $vSize", level: LogLevel.Info); -// // fee should never be less than vSize sanity check -// if (fee < vSize) { -// throw Exception( -// "Error in fee calculation: Transaction fee cannot be less than vSize"); -// } -// return result as Map; -// } else { -// throw Exception("sent hex is not a String!!!"); -// } -// } -// } else if (feeRateType is FeeRateType || feeRateAmount is int) { -// late final int rate; -// if (feeRateType is FeeRateType) { -// int fee = 0; -// final feeObject = await fees; -// switch (feeRateType) { -// case FeeRateType.fast: -// fee = feeObject.fast; -// break; -// case FeeRateType.average: -// fee = feeObject.medium; -// break; -// case FeeRateType.slow: -// fee = feeObject.slow; -// break; -// default: -// throw ArgumentError("Invalid use of custom fee"); -// } -// rate = fee; -// } else { -// rate = feeRateAmount as int; -// } -// -// // check for send all -// bool isSendAll = false; -// if (amount == balance.spendable) { -// isSendAll = true; -// } -// -// final bool coinControl = utxos != null; -// -// final txData = await coinSelection( -// satoshiAmountToSend: amount.raw.toInt(), -// selectedTxFeeRate: rate, -// recipientAddress: address, -// isSendAll: isSendAll, -// utxos: utxos?.toList(), -// coinControl: coinControl, -// ); -// -// Logging.instance.log("prepare send: $txData", level: LogLevel.Info); -// try { -// if (txData is int) { -// switch (txData) { -// case 1: -// throw Exception("Insufficient balance!"); -// case 2: -// throw Exception( -// "Insufficient funds to pay for transaction fee!"); -// default: -// throw Exception("Transaction failed with error code $txData"); -// } -// } else { -// final hex = txData["hex"]; -// -// if (hex is String) { -// final fee = txData["fee"] as int; -// final vSize = txData["vSize"] as int; -// -// Logging.instance -// .log("prepared txHex: $hex", level: LogLevel.Info); -// Logging.instance.log("prepared fee: $fee", level: LogLevel.Info); -// Logging.instance -// .log("prepared vSize: $vSize", level: LogLevel.Info); -// -// // fee should never be less than vSize sanity check -// if (fee < vSize) { -// throw Exception( -// "Error in fee calculation: Transaction fee cannot be less than vSize"); -// } -// -// return txData as Map; -// } else { -// throw Exception("prepared hex is not a String!!!"); -// } -// } -// } catch (e, s) { -// Logging.instance.log("Exception rethrown from prepareSend(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } else { -// throw ArgumentError("Invalid fee rate argument provided!"); -// } -// } catch (e, s) { -// Logging.instance.log("Exception rethrown from prepareSend(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// @override -// Future confirmSend({required Map txData}) async { -// try { -// Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info); -// -// final hex = txData["hex"] as String; -// -// final txHash = await _electrumXClient.broadcastTransaction(rawTx: hex); -// Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info); -// -// final utxos = txData["usedUTXOs"] as List; -// -// // mark utxos as used -// await db.putUTXOs(utxos.map((e) => e.copyWith(used: true)).toList()); -// -// return txHash; -// } catch (e, s) { -// Logging.instance.log("Exception rethrown from confirmSend(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// @override -// Future testNetworkConnection() async { -// try { -// final result = await _electrumXClient.ping(); -// return result; -// } catch (_) { -// return false; -// } -// } -// -// Timer? _networkAliveTimer; -// -// void startNetworkAlivePinging() { -// // call once on start right away -// _periodicPingCheck(); -// -// // then periodically check -// _networkAliveTimer = Timer.periodic( -// Constants.networkAliveTimerDuration, -// (_) async { -// _periodicPingCheck(); -// }, -// ); -// } -// -// void _periodicPingCheck() async { -// bool hasNetwork = await testNetworkConnection(); -// -// if (_isConnected != hasNetwork) { -// NodeConnectionStatus status = hasNetwork -// ? NodeConnectionStatus.connected -// : NodeConnectionStatus.disconnected; -// GlobalEventBus.instance -// .fire(NodeConnectionStatusChangedEvent(status, walletId, coin)); -// -// _isConnected = hasNetwork; -// if (hasNetwork) { -// unawaited(refresh()); -// } -// } -// } -// -// void stopNetworkAlivePinging() { -// _networkAliveTimer?.cancel(); -// _networkAliveTimer = null; -// } -// -// bool _isConnected = false; -// -// @override -// bool get isConnected => _isConnected; -// -// @override -// Future initializeNew( -// ({String mnemonicPassphrase, int wordCount})? data, -// ) async { -// Logging.instance -// .log("Generating new ${coin.prettyName} wallet.", level: LogLevel.Info); -// -// if (getCachedId() != null) { -// throw Exception( -// "Attempted to initialize a new wallet using an existing wallet ID!"); -// } -// -// await _prefs.init(); -// try { -// await _generateNewWallet(data); -// } catch (e, s) { -// Logging.instance.log("Exception rethrown from initializeNew(): $e\n$s", -// level: LogLevel.Fatal); -// rethrow; -// } -// await Future.wait([ -// updateCachedId(walletId), -// updateCachedIsFavorite(false), -// ]); -// } -// -// @override -// Future initializeExisting() async { -// Logging.instance.log("initializeExisting() ${coin.prettyName} wallet.", -// level: LogLevel.Info); -// -// if (getCachedId() == null) { -// throw Exception( -// "Attempted to initialize an existing wallet using an unknown wallet ID!"); -// } -// await _prefs.init(); -// // await _checkCurrentChangeAddressesForTransactions(); -// // await _checkCurrentReceivingAddressesForTransactions(); -// } -// -// // TODO make sure this copied implementation from bitcoin_wallet.dart applies for particl just as well--or import it -// // hack to add tx to txData before refresh completes -// // required based on current app architecture where we don't properly store -// // transactions locally in a good way -// @override -// Future updateSentCachedTxData(Map txData) async { -// final transaction = isar_models.Transaction( -// walletId: walletId, -// txid: txData["txid"] as String, -// timestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000, -// type: isar_models.TransactionType.outgoing, -// subType: isar_models.TransactionSubType.none, -// // precision may be lost here hence the following amountString -// amount: (txData["recipientAmt"] as Amount).raw.toInt(), -// amountString: (txData["recipientAmt"] as Amount).toJsonString(), -// fee: txData["fee"] as int, -// height: null, -// isCancelled: false, -// isLelantus: false, -// otherData: null, -// slateId: null, -// nonce: null, -// inputs: [], -// outputs: [], -// numberOfMessages: null, -// ); -// -// final address = txData["address"] is String -// ? await db.getAddress(walletId, txData["address"] as String) -// : null; -// -// await db.addNewTransactionData( -// [ -// Tuple2(transaction, address), -// ], -// walletId, -// ); -// } -// -// @override -// bool validateAddress(String address) { -// return Address.validateAddress(address, _network, particl.bech32!); -// } -// -// @override -// String get walletId => _walletId; -// late final String _walletId; -// -// @override -// String get walletName => _walletName; -// late String _walletName; -// -// // setter for updating on rename -// @override -// set walletName(String newName) => _walletName = newName; -// -// late ElectrumXClient _electrumXClient; -// -// ElectrumXClient get electrumXClient => _electrumXClient; -// -// late CachedElectrumXClient _cachedElectrumXClient; -// -// CachedElectrumXClient get cachedElectrumXClient => _cachedElectrumXClient; -// -// late SecureStorageInterface _secureStore; -// -// @override -// Future updateNode(bool shouldRefresh) async { -// final failovers = NodeService(secureStorageInterface: _secureStore) -// .failoverNodesFor(coin: coin) -// .map((e) => ElectrumXNode( -// address: e.host, -// port: e.port, -// name: e.name, -// id: e.id, -// useSSL: e.useSSL, -// )) -// .toList(); -// final newNode = await getCurrentNode(); -// _electrumXClient = ElectrumXClient.from( -// node: newNode, -// prefs: _prefs, -// failovers: failovers, -// ); -// _cachedElectrumXClient = CachedElectrumXClient.from( -// electrumXClient: _electrumXClient, -// ); -// -// if (shouldRefresh) { -// unawaited(refresh()); -// } -// } -// -// Future> _getMnemonicList() async { -// final _mnemonicString = await mnemonicString; -// if (_mnemonicString == null) { -// return []; -// } -// final List data = _mnemonicString.split(' '); -// return data; -// } -// -// Future getCurrentNode() async { -// final node = NodeService(secureStorageInterface: _secureStore) -// .getPrimaryNodeFor(coin: coin) ?? -// DefaultNodes.getNodeFor(coin); -// -// return ElectrumXNode( -// address: node.host, -// port: node.port, -// name: node.name, -// useSSL: node.useSSL, -// id: node.id, -// ); -// } -// -// Future> _fetchAllOwnAddresses() async { -// final allAddresses = await db -// .getAddresses(walletId) -// .filter() -// .not() -// .typeEqualTo(isar_models.AddressType.nonWallet) -// .and() -// .group((q) => q -// .subTypeEqualTo(isar_models.AddressSubType.receiving) -// .or() -// .subTypeEqualTo(isar_models.AddressSubType.change)) -// .findAll(); -// -// // final List allAddresses = []; -// // final receivingAddresses = DB.instance.get( -// // boxName: walletId, key: 'receivingAddressesP2WPKH') as List; -// // final changeAddresses = DB.instance.get( -// // boxName: walletId, key: 'changeAddressesP2WPKH') as List; -// // final receivingAddressesP2PKH = DB.instance.get( -// // boxName: walletId, key: 'receivingAddressesP2PKH') as List; -// // final changeAddressesP2PKH = -// // DB.instance.get(boxName: walletId, key: 'changeAddressesP2PKH') -// // as List; -// // -// // for (var i = 0; i < receivingAddresses.length; i++) { -// // if (!allAddresses.contains(receivingAddresses[i])) { -// // allAddresses.add(receivingAddresses[i] as String); -// // } -// // } -// // for (var i = 0; i < changeAddresses.length; i++) { -// // if (!allAddresses.contains(changeAddresses[i])) { -// // allAddresses.add(changeAddresses[i] as String); -// // } -// // } -// // for (var i = 0; i < receivingAddressesP2PKH.length; i++) { -// // if (!allAddresses.contains(receivingAddressesP2PKH[i])) { -// // allAddresses.add(receivingAddressesP2PKH[i] as String); -// // } -// // } -// // for (var i = 0; i < changeAddressesP2PKH.length; i++) { -// // if (!allAddresses.contains(changeAddressesP2PKH[i])) { -// // allAddresses.add(changeAddressesP2PKH[i] as String); -// // } -// // } -// -// return allAddresses; -// } -// -// Future _getFees() async { -// try { -// //TODO adjust numbers for different speeds? -// const int f = 1, m = 5, s = 20; -// -// final fast = await electrumXClient.estimateFee(blocks: f); -// final medium = await electrumXClient.estimateFee(blocks: m); -// final slow = await electrumXClient.estimateFee(blocks: s); -// -// final feeObject = FeeObject( -// numberOfBlocksFast: f, -// numberOfBlocksAverage: m, -// numberOfBlocksSlow: s, -// fast: Amount.fromDecimal( -// fast, -// fractionDigits: coin.decimals, -// ).raw.toInt(), -// medium: Amount.fromDecimal( -// medium, -// fractionDigits: coin.decimals, -// ).raw.toInt(), -// slow: Amount.fromDecimal( -// slow, -// fractionDigits: coin.decimals, -// ).raw.toInt(), -// ); -// -// Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info); -// return feeObject; -// } catch (e) { -// Logging.instance -// .log("Exception rethrown from _getFees(): $e", level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future _generateNewWallet( -// ({String mnemonicPassphrase, int wordCount})? data, -// ) async { -// Logging.instance -// .log("IS_INTEGRATION_TEST: $integrationTestFlag", level: LogLevel.Info); -// if (!integrationTestFlag) { -// try { -// final features = await electrumXClient.getServerFeatures(); -// Logging.instance.log("features: $features", level: LogLevel.Info); -// switch (coin) { -// case Coin.particl: -// if (features['genesis_hash'] != GENESIS_HASH_MAINNET) { -// throw Exception("genesis hash does not match main net!"); -// } -// break; -// default: -// throw Exception( -// "Attempted to generate a ParticlWallet using a non particl coin type: ${coin.name}"); -// } -// } catch (e, s) { -// Logging.instance.log("$e/n$s", level: LogLevel.Info); -// } -// } -// -// // this should never fail -// if ((await mnemonicString) != null || (await mnemonicPassphrase) != null) { -// throw Exception( -// "Attempted to overwrite mnemonic on generate new wallet!"); -// } -// final int strength; -// if (data == null || data.wordCount == 12) { -// strength = 128; -// } else if (data.wordCount == 24) { -// strength = 256; -// } else { -// throw Exception("Invalid word count"); -// } -// await _secureStore.write( -// key: '${_walletId}_mnemonic', -// value: bip39.generateMnemonic(strength: strength)); -// await _secureStore.write( -// key: '${_walletId}_mnemonicPassphrase', -// value: data?.mnemonicPassphrase ?? "", -// ); -// -// // Generate and add addresses to relevant arrays -// final initialAddresses = await Future.wait([ -// // P2WPKH -// _generateAddressForChain(0, 0, DerivePathType.bip84), -// _generateAddressForChain(1, 0, DerivePathType.bip84), -// -// // P2PKH -// _generateAddressForChain(0, 0, DerivePathType.bip44), -// _generateAddressForChain(1, 0, DerivePathType.bip44), -// ]); -// -// await db.putAddresses(initialAddresses); -// -// Logging.instance.log("_generateNewWalletFinished", level: LogLevel.Info); -// } -// -// /// Generates a new internal or external chain address for the wallet using a BIP84, BIP44, or BIP49 derivation path. -// /// [chain] - Use 0 for receiving (external), 1 for change (internal). Should not be any other value! -// /// [index] - This can be any integer >= 0 -// Future _generateAddressForChain( -// int chain, -// int index, -// DerivePathType derivePathType, -// ) async { -// final _mnemonic = await mnemonicString; -// final _mnemonicPassphrase = await mnemonicPassphrase; -// if (_mnemonicPassphrase == null) { -// Logging.instance.log( -// "Exception in _generateAddressForChain: mnemonic passphrase null, possible migration issue; if using internal builds, delete wallet and restore from seed, if using a release build, please file bug report", -// level: LogLevel.Error); -// } -// -// final derivePath = constructDerivePath( -// derivePathType: derivePathType, -// networkWIF: _network.wif, -// chain: chain, -// index: index, -// ); -// final node = await Bip32Utils.getBip32Node( -// _mnemonic!, -// _mnemonicPassphrase!, -// _network, -// derivePath, -// ); -// -// final data = PaymentData(pubkey: node.publicKey); -// String address; -// isar_models.AddressType addrType; -// -// switch (derivePathType) { -// case DerivePathType.bip44: -// address = P2PKH(data: data, network: _network).data.address!; -// addrType = isar_models.AddressType.p2pkh; -// break; -// case DerivePathType.bip84: -// address = P2WPKH(network: _network, data: data).data.address!; -// addrType = isar_models.AddressType.p2wpkh; -// break; -// default: -// throw Exception("DerivePathType $derivePathType not supported"); -// } -// -// // add generated address & info to derivations -// await addDerivation( -// chain: chain, -// address: address, -// pubKey: Format.uint8listToString(node.publicKey), -// wif: node.toWIF(), -// derivePathType: derivePathType, -// ); -// -// return isar_models.Address( -// walletId: walletId, -// derivationIndex: index, -// derivationPath: isar_models.DerivationPath()..value = derivePath, -// value: address, -// publicKey: node.publicKey, -// type: addrType, -// subType: chain == 0 -// ? isar_models.AddressSubType.receiving -// : isar_models.AddressSubType.change, -// ); -// } -// -// /// Returns the latest receiving/change (external/internal) address for the wallet depending on [chain] -// /// and -// /// [chain] - Use 0 for receiving (external), 1 for change (internal). Should not be any other value! -// Future _getCurrentAddressForChain( -// int chain, -// DerivePathType derivePathType, -// ) async { -// final subType = chain == 0 // Here, we assume that chain == 1 if it isn't 0 -// ? isar_models.AddressSubType.receiving -// : isar_models.AddressSubType.change; -// -// isar_models.AddressType type; -// isar_models.Address? address; -// switch (derivePathType) { -// case DerivePathType.bip44: -// type = isar_models.AddressType.p2pkh; -// break; -// case DerivePathType.bip84: -// type = isar_models.AddressType.p2wpkh; -// break; -// default: -// throw Exception("DerivePathType $derivePathType not supported"); -// } -// address = await db -// .getAddresses(walletId) -// .filter() -// .typeEqualTo(type) -// .subTypeEqualTo(subType) -// .sortByDerivationIndexDesc() -// .findFirst(); -// return address!.value; -// } -// -// String _buildDerivationStorageKey({ -// required int chain, -// required DerivePathType derivePathType, -// }) { -// String key; -// String chainId = chain == 0 ? "receive" : "change"; -// -// switch (derivePathType) { -// case DerivePathType.bip44: -// key = "${walletId}_${chainId}DerivationsP2PKH"; -// break; -// case DerivePathType.bip84: -// key = "${walletId}_${chainId}DerivationsP2WPKH"; -// break; -// default: -// throw Exception("DerivePathType $derivePathType not supported"); -// } -// return key; -// } -// -// Future> _fetchDerivations({ -// required int chain, -// required DerivePathType derivePathType, -// }) async { -// // build lookup key -// final key = _buildDerivationStorageKey( -// chain: chain, derivePathType: derivePathType); -// -// // fetch current derivations -// final derivationsString = await _secureStore.read(key: key); -// return Map.from( -// jsonDecode(derivationsString ?? "{}") as Map); -// } -// -// /// Add a single derivation to the local secure storage for [chain] and -// /// [derivePathType] where [chain] must either be 1 for change or 0 for receive. -// /// This will overwrite a previous entry where the address of the new derivation -// /// matches a derivation currently stored. -// Future addDerivation({ -// required int chain, -// required String address, -// required String pubKey, -// required String wif, -// required DerivePathType derivePathType, -// }) async { -// // build lookup key -// final key = _buildDerivationStorageKey( -// chain: chain, derivePathType: derivePathType); -// -// // fetch current derivations -// final derivationsString = await _secureStore.read(key: key); -// final derivations = -// Map.from(jsonDecode(derivationsString ?? "{}") as Map); -// -// // add derivation -// derivations[address] = { -// "pubKey": pubKey, -// "wif": wif, -// }; -// -// // save derivations -// final newReceiveDerivationsString = jsonEncode(derivations); -// await _secureStore.write(key: key, value: newReceiveDerivationsString); -// } -// -// /// Add multiple derivations to the local secure storage for [chain] and -// /// [derivePathType] where [chain] must either be 1 for change or 0 for receive. -// /// This will overwrite any previous entries where the address of the new derivation -// /// matches a derivation currently stored. -// /// The [derivationsToAdd] must be in the format of: -// /// { -// /// addressA : { -// /// "pubKey": , -// /// "wif": , -// /// }, -// /// addressB : { -// /// "pubKey": , -// /// "wif": , -// /// }, -// /// } -// Future addDerivations({ -// required int chain, -// required DerivePathType derivePathType, -// required Map derivationsToAdd, -// }) async { -// // build lookup key -// final key = _buildDerivationStorageKey( -// chain: chain, derivePathType: derivePathType); -// -// // fetch current derivations -// final derivationsString = await _secureStore.read(key: key); -// final derivations = -// Map.from(jsonDecode(derivationsString ?? "{}") as Map); -// -// // add derivation -// derivations.addAll(derivationsToAdd); -// -// // save derivations -// final newReceiveDerivationsString = jsonEncode(derivations); -// await _secureStore.write(key: key, value: newReceiveDerivationsString); -// } -// -// Future _updateUTXOs() async { -// final allAddresses = await _fetchAllOwnAddresses(); -// -// try { -// final fetchedUtxoList = >>[]; -// -// final Map>> batches = {}; -// const batchSizeMax = 100; -// int batchNumber = 0; -// for (int i = 0; i < allAddresses.length; i++) { -// if (batches[batchNumber] == null) { -// batches[batchNumber] = {}; -// } -// final scripthash = -// _convertToScriptHash(allAddresses[i].value, _network); -// batches[batchNumber]!.addAll({ -// scripthash: [scripthash] -// }); -// if (i % batchSizeMax == batchSizeMax - 1) { -// batchNumber++; -// } -// } -// -// for (int i = 0; i < batches.length; i++) { -// final response = -// await _electrumXClient.getBatchUTXOs(args: batches[i]!); -// for (final entry in response.entries) { -// if (entry.value.isNotEmpty) { -// fetchedUtxoList.add(entry.value); -// } -// } -// } -// -// final List outputArray = []; -// -// for (int i = 0; i < fetchedUtxoList.length; i++) { -// for (int j = 0; j < fetchedUtxoList[i].length; j++) { -// final jsonUTXO = fetchedUtxoList[i][j]; -// -// final txn = await cachedElectrumXClient.getTransaction( -// txHash: jsonUTXO["tx_hash"] as String, -// verbose: true, -// coin: coin, -// ); -// -// final vout = jsonUTXO["tx_pos"] as int; -// -// final outputs = txn["vout"] as List; -// -// String? utxoOwnerAddress; -// // get UTXO owner address -// for (final output in outputs) { -// if (output["n"] == vout) { -// utxoOwnerAddress = -// output["scriptPubKey"]?["addresses"]?[0] as String? ?? -// output["scriptPubKey"]?["address"] as String?; -// } -// } -// -// final utxo = isar_models.UTXO( -// walletId: walletId, -// txid: txn["txid"] as String, -// vout: vout, -// value: jsonUTXO["value"] as int, -// name: "", -// isBlocked: false, -// blockedReason: null, -// isCoinbase: txn["is_coinbase"] as bool? ?? false, -// blockHash: txn["blockhash"] as String?, -// blockHeight: jsonUTXO["height"] as int?, -// blockTime: txn["blocktime"] as int?, -// address: utxoOwnerAddress, -// ); -// -// outputArray.add(utxo); -// } -// } -// -// Logging.instance -// .log('Outputs fetched: $outputArray', level: LogLevel.Info); -// -// await db.updateUTXOs(walletId, outputArray); -// -// // finally update balance -// await _updateBalance(); -// } catch (e, s) { -// Logging.instance -// .log("Output fetch unsuccessful: $e\n$s", level: LogLevel.Error); -// } -// } -// -// Future _updateBalance() async { -// // await refreshBalance(); -// } -// -// @override -// Balance get balance => _balance ??= getCachedBalance(); -// Balance? _balance; -// -// // /// Takes in a list of UtxoObjects and adds a name (dependent on object index within list) -// // /// and checks for the txid associated with the utxo being blocked and marks it accordingly. -// // /// Now also checks for output labeling. -// // Future _sortOutputs(List utxos) async { -// // final blockedHashArray = -// // DB.instance.get(boxName: walletId, key: 'blocked_tx_hashes') -// // as List?; -// // final List lst = []; -// // if (blockedHashArray != null) { -// // for (var hash in blockedHashArray) { -// // lst.add(hash as String); -// // } -// // } -// // final labels = -// // DB.instance.get(boxName: walletId, key: 'labels') as Map? ?? -// // {}; -// // -// // outputsList = []; -// // -// // for (var i = 0; i < utxos.length; i++) { -// // if (labels[utxos[i].txid] != null) { -// // utxos[i].txName = labels[utxos[i].txid] as String? ?? ""; -// // } else { -// // utxos[i].txName = 'Output #$i'; -// // } -// // -// // if (utxos[i].status.confirmed == false) { -// // outputsList.add(utxos[i]); -// // } else { -// // if (lst.contains(utxos[i].txid)) { -// // utxos[i].blocked = true; -// // outputsList.add(utxos[i]); -// // } else if (!lst.contains(utxos[i].txid)) { -// // outputsList.add(utxos[i]); -// // } -// // } -// // } -// // } -// -// Future getTxCount({required String address}) async { -// String? scripthash; -// try { -// scripthash = _convertToScriptHash(address, _network); -// final transactions = -// await electrumXClient.getHistory(scripthash: scripthash); -// return transactions.length; -// } catch (e) { -// Logging.instance.log( -// "Exception rethrown in _getTxCount(address: $address, scripthash: $scripthash): $e", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future> _getBatchTxCount({ -// required Map addresses, -// }) async { -// try { -// final Map> args = {}; -// for (final entry in addresses.entries) { -// args[entry.key] = [_convertToScriptHash(entry.value, _network)]; -// } -// final response = await electrumXClient.getBatchHistory(args: args); -// -// final Map result = {}; -// for (final entry in response.entries) { -// result[entry.key] = entry.value.length; -// } -// return result; -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown in _getBatchTxCount(address: $addresses: $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future _checkReceivingAddressForTransactions() async { -// try { -// final currentReceiving = await _currentReceivingAddress; -// -// final int txCount = await getTxCount(address: currentReceiving.value); -// Logging.instance.log( -// 'Number of txs for current receiving address $currentReceiving: $txCount', -// level: LogLevel.Info); -// -// if (txCount >= 1 || currentReceiving.derivationIndex < 0) { -// // First increment the receiving index -// final newReceivingIndex = currentReceiving.derivationIndex + 1; -// -// // Use new index to derive a new receiving address -// final newReceivingAddress = await _generateAddressForChain( -// 0, newReceivingIndex, DerivePathTypeExt.primaryFor(coin)); -// -// final existing = await db -// .getAddresses(walletId) -// .filter() -// .valueEqualTo(newReceivingAddress.value) -// .findFirst(); -// if (existing == null) { -// // Add that new change address -// await db.putAddress(newReceivingAddress); -// } else { -// // we need to update the address -// await db.updateAddress(existing, newReceivingAddress); -// } -// // keep checking until address with no tx history is set as current -// await _checkReceivingAddressForTransactions(); -// } -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from _checkReceivingAddressForTransactions(${DerivePathTypeExt.primaryFor(coin)}): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future _checkChangeAddressForTransactions() async { -// try { -// final currentChange = await _currentChangeAddress; -// final int txCount = await getTxCount(address: currentChange.value); -// Logging.instance.log( -// 'Number of txs for current change address $currentChange: $txCount', -// level: LogLevel.Info); -// -// if (txCount >= 1 || currentChange.derivationIndex < 0) { -// // First increment the change index -// final newChangeIndex = currentChange.derivationIndex + 1; -// -// // Use new index to derive a new change address -// final newChangeAddress = await _generateAddressForChain( -// 1, newChangeIndex, DerivePathTypeExt.primaryFor(coin)); -// -// final existing = await db -// .getAddresses(walletId) -// .filter() -// .valueEqualTo(newChangeAddress.value) -// .findFirst(); -// if (existing == null) { -// // Add that new change address -// await db.putAddress(newChangeAddress); -// } else { -// // we need to update the address -// await db.updateAddress(existing, newChangeAddress); -// } -// // keep checking until address with no tx history is set as current -// await _checkChangeAddressForTransactions(); -// } -// } on SocketException catch (se, s) { -// Logging.instance.log( -// "SocketException caught in _checkReceivingAddressForTransactions(${DerivePathTypeExt.primaryFor(coin)}): $se\n$s", -// level: LogLevel.Error); -// return; -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from _checkReceivingAddressForTransactions(${DerivePathTypeExt.primaryFor(coin)}): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future _checkCurrentReceivingAddressesForTransactions() async { -// try { -// // for (final type in DerivePathType.values) { -// await _checkReceivingAddressForTransactions(); -// // } -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from _checkCurrentReceivingAddressesForTransactions(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// /// public wrapper because dart can't test private... -// Future checkCurrentReceivingAddressesForTransactions() async { -// if (Platform.environment["FLUTTER_TEST"] == "true") { -// try { -// return _checkCurrentReceivingAddressesForTransactions(); -// } catch (_) { -// rethrow; -// } -// } -// } -// -// Future _checkCurrentChangeAddressesForTransactions() async { -// try { -// // for (final type in DerivePathType.values) { -// await _checkChangeAddressForTransactions(); -// // } -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from _checkCurrentChangeAddressesForTransactions(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// /// public wrapper because dart can't test private... -// Future checkCurrentChangeAddressesForTransactions() async { -// if (Platform.environment["FLUTTER_TEST"] == "true") { -// try { -// return _checkCurrentChangeAddressesForTransactions(); -// } catch (_) { -// rethrow; -// } -// } -// } -// -// /// attempts to convert a string to a valid scripthash -// /// -// /// Returns the scripthash or throws an exception on invalid particl address -// String _convertToScriptHash(String particlAddress, NetworkType network) { -// try { -// final output = Address.addressToOutputScript( -// particlAddress, network, particl.bech32!); -// final hash = sha256.convert(output.toList(growable: false)).toString(); -// -// final chars = hash.split(""); -// final reversedPairs = []; -// var i = chars.length - 1; -// while (i > 0) { -// reversedPairs.add(chars[i - 1]); -// reversedPairs.add(chars[i]); -// i -= 2; -// } -// return reversedPairs.join(""); -// } catch (e) { -// rethrow; -// } -// } -// -// Future>> _fetchHistory( -// List allAddresses) async { -// try { -// List> allTxHashes = []; -// -// final Map>> batches = {}; -// final Map requestIdToAddressMap = {}; -// const batchSizeMax = 100; -// int batchNumber = 0; -// for (int i = 0; i < allAddresses.length; i++) { -// if (batches[batchNumber] == null) { -// batches[batchNumber] = {}; -// } -// final scripthash = _convertToScriptHash(allAddresses[i], _network); -// final id = Logger.isTestEnv ? "$i" : const Uuid().v1(); -// requestIdToAddressMap[id] = allAddresses[i]; -// batches[batchNumber]!.addAll({ -// id: [scripthash] -// }); -// if (i % batchSizeMax == batchSizeMax - 1) { -// batchNumber++; -// } -// } -// -// for (int i = 0; i < batches.length; i++) { -// final response = -// await _electrumXClient.getBatchHistory(args: batches[i]!); -// for (final entry in response.entries) { -// for (int j = 0; j < entry.value.length; j++) { -// entry.value[j]["address"] = requestIdToAddressMap[entry.key]; -// if (!allTxHashes.contains(entry.value[j])) { -// allTxHashes.add(entry.value[j]); -// } -// } -// } -// } -// -// return allTxHashes; -// } catch (e, s) { -// Logging.instance.log("_fetchHistory: $e\n$s", level: LogLevel.Error); -// rethrow; -// } -// } -// -// bool _duplicateTxCheck( -// List> allTransactions, String txid) { -// for (int i = 0; i < allTransactions.length; i++) { -// if (allTransactions[i]["txid"] == txid) { -// return true; -// } -// } -// return false; -// } -// -// Future>> fastFetch(List allTxHashes) async { -// List> allTransactions = []; -// -// const futureLimit = 30; -// List>> transactionFutures = []; -// int currentFutureCount = 0; -// for (final txHash in allTxHashes) { -// Future> transactionFuture = -// cachedElectrumXClient.getTransaction( -// txHash: txHash, -// verbose: true, -// coin: coin, -// ); -// transactionFutures.add(transactionFuture); -// currentFutureCount++; -// if (currentFutureCount > futureLimit) { -// currentFutureCount = 0; -// await Future.wait(transactionFutures); -// for (final fTx in transactionFutures) { -// final tx = await fTx; -// -// allTransactions.add(tx); -// } -// } -// } -// if (currentFutureCount != 0) { -// currentFutureCount = 0; -// await Future.wait(transactionFutures); -// for (final fTx in transactionFutures) { -// final tx = await fTx; -// -// allTransactions.add(tx); -// } -// } -// return allTransactions; -// } -// -// Future _refreshTransactions() async { -// final allAddresses = await _fetchAllOwnAddresses(); -// -// List changeAddresses = allAddresses -// .where((e) => e.subType == isar_models.AddressSubType.change) -// .map((e) => e.value) -// .toList(); -// -// final List> allTxHashes = await _fetchHistory( -// allAddresses.map((e) => e.value).toList(growable: false)); -// -// Set hashes = {}; -// for (var element in allTxHashes) { -// hashes.add(element['tx_hash'] as String); -// } -// await fastFetch(hashes.toList()); -// List> allTransactions = []; -// final currentHeight = await chainHeight; -// -// for (final txHash in allTxHashes) { -// final storedTx = await db -// .getTransactions(walletId) -// .filter() -// .txidEqualTo(txHash["tx_hash"] as String) -// .findFirst(); -// -// if (storedTx == null || -// !storedTx.isConfirmed(currentHeight, MINIMUM_CONFIRMATIONS)) { -// final tx = await cachedElectrumXClient.getTransaction( -// txHash: txHash["tx_hash"] as String, -// verbose: true, -// coin: coin, -// ); -// -// if (!_duplicateTxCheck(allTransactions, tx["txid"] as String)) { -// tx["address"] = (await db -// .getAddresses(walletId) -// .filter() -// .valueEqualTo(txHash["address"] as String) -// .findFirst())!; -// tx["height"] = txHash["height"]; -// allTransactions.add(tx); -// } -// } -// } -// -// Logging.instance.log("addAddresses: $allAddresses", -// level: LogLevel.Info, printFullLength: true); -// Logging.instance.log("allTxHashes: $allTxHashes", -// level: LogLevel.Info, printFullLength: true); -// -// Logging.instance.log("allTransactions length: ${allTransactions.length}", -// level: LogLevel.Info); -// -// // final List> midSortedArray = []; -// -// Set vHashes = {}; -// for (final txObject in allTransactions) { -// for (int i = 0; i < (txObject["vin"] as List).length; i++) { -// final input = txObject["vin"]![i] as Map; -// final prevTxid = input["txid"] as String; -// vHashes.add(prevTxid); -// } -// } -// await fastFetch(vHashes.toList()); -// -// final List> txns = []; -// -// for (final txObject in allTransactions) { -// List sendersArray = []; -// List recipientsArray = []; -// -// // Usually only has value when txType = 'Send' -// int inputAmtSentFromWallet = 0; -// // Usually has value regardless of txType due to change addresses -// int outputAmtAddressedToWallet = 0; -// int fee = 0; -// -// Map midSortedTx = {}; -// -// for (int i = 0; i < (txObject["vin"] as List).length; i++) { -// final input = txObject["vin"]![i] as Map; -// final prevTxid = input["txid"] as String; -// final prevOut = input["vout"] as int; -// -// final tx = await _cachedElectrumXClient.getTransaction( -// txHash: prevTxid, -// coin: coin, -// ); -// -// for (final out in tx["vout"] as List) { -// if (prevOut == out["n"]) { -// final address = out["scriptPubKey"]?["address"] as String? ?? -// out["scriptPubKey"]?["addresses"]?[0] as String?; -// if (address != null) { -// sendersArray.add(address); -// } -// } -// } -// } -// -// Logging.instance.log("sendersArray: $sendersArray", level: LogLevel.Info); -// -// for (final output in txObject["vout"] as List) { -// // Particl has different tx types that need to be detected and handled here -// if (output.containsKey('scriptPubKey') as bool) { -// // Logging.instance.log("output is transparent", level: LogLevel.Info); -// final address = output["scriptPubKey"]?["address"] as String? ?? -// output["scriptPubKey"]?["addresses"]?[0] as String?; -// if (address != null) { -// recipientsArray.add(address); -// } -// } else if (output.containsKey('ct_fee') as bool) { -// // or type: data -// Logging.instance.log("output is blinded (CT)", level: LogLevel.Info); -// } else if (output.containsKey('rangeproof') as bool) { -// // or valueCommitment or type: anon -// Logging.instance -// .log("output is private (RingCT)", level: LogLevel.Info); -// } else { -// // TODO detect staking -// Logging.instance.log("output type not detected; output: $output", -// level: LogLevel.Info); -// } -// } -// -// Logging.instance -// .log("recipientsArray: $recipientsArray", level: LogLevel.Info); -// -// final foundInSenders = -// allAddresses.any((element) => sendersArray.contains(element.value)); -// Logging.instance -// .log("foundInSenders: $foundInSenders", level: LogLevel.Info); -// -// // If txType = Sent, then calculate inputAmtSentFromWallet -// if (foundInSenders) { -// int totalInput = 0; -// for (int i = 0; i < (txObject["vin"] as List).length; i++) { -// final input = txObject["vin"]![i] as Map; -// final prevTxid = input["txid"] as String; -// final prevOut = input["vout"] as int; -// final tx = await _cachedElectrumXClient.getTransaction( -// txHash: prevTxid, -// coin: coin, -// ); -// -// for (final out in tx["vout"] as List) { -// if (prevOut == out["n"]) { -// inputAmtSentFromWallet += -// (Decimal.parse(out["value"]!.toString()) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt())) -// .toBigInt() -// .toInt(); -// } -// } -// } -// totalInput = inputAmtSentFromWallet; -// int totalOutput = 0; -// -// Logging.instance.log("txObject: $txObject", level: LogLevel.Info); -// -// for (final output in txObject["vout"] as List) { -// // Particl has different tx types that need to be detected and handled here -// if (output.containsKey('scriptPubKey') as bool) { -// try { -// final String address = -// output["scriptPubKey"]!["addresses"][0] as String; -// final value = output["value"]!; -// final _value = (Decimal.parse(value.toString()) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt())) -// .toBigInt() -// .toInt(); -// totalOutput += _value; -// if (changeAddresses.contains(address)) { -// inputAmtSentFromWallet -= _value; -// } else { -// // change address from 'sent from' to the 'sent to' address -// txObject["address"] = await db -// .getAddresses(walletId) -// .filter() -// .valueEqualTo(address) -// .findFirst() ?? -// isar_models.Address( -// walletId: walletId, -// type: isar_models.AddressType.nonWallet, -// subType: isar_models.AddressSubType.nonWallet, -// value: address, -// publicKey: [], -// derivationIndex: -1, -// derivationPath: null, -// ); -// } -// } catch (s) { -// Logging.instance.log(s.toString(), level: LogLevel.Warning); -// } -// // Logging.instance.log("output is transparent", level: LogLevel.Info); -// } else if (output.containsKey('ct_fee') as bool) { -// // or type: data -// // TODO handle CT tx -// Logging.instance.log( -// "output is blinded (CT); cannot parse output values", -// level: LogLevel.Info); -// final ctFee = output["ct_fee"]!; -// final feeValue = (Decimal.parse(ctFee.toString()) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt())) -// .toBigInt() -// .toInt(); -// Logging.instance.log( -// "ct_fee $ctFee subtracted from inputAmtSentFromWallet $inputAmtSentFromWallet", -// level: LogLevel.Info); -// inputAmtSentFromWallet += feeValue; -// } else if (output.containsKey('rangeproof') as bool) { -// // or valueCommitment or type: anon -// // TODO handle RingCT tx -// Logging.instance.log( -// "output is private (RingCT); cannot parse output values", -// level: LogLevel.Info); -// } else { -// // TODO detect staking -// Logging.instance.log("output type not detected; output: $output", -// level: LogLevel.Info); -// } -// } -// // calculate transaction fee -// fee = totalInput - totalOutput; -// // subtract fee from sent to calculate correct value of sent tx -// inputAmtSentFromWallet -= fee; -// } else { -// // counters for fee calculation -// int totalOut = 0; -// int totalIn = 0; -// -// // add up received tx value -// for (final output in txObject["vout"] as List) { -// try { -// final address = output["scriptPubKey"]?["address"] as String? ?? -// output["scriptPubKey"]?["addresses"]?[0] as String?; -// if (address != null) { -// final value = (Decimal.parse((output["value"] ?? 0).toString()) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt())) -// .toBigInt() -// .toInt(); -// totalOut += value; -// if (allAddresses.where((e) => e.value == address).isNotEmpty) { -// outputAmtAddressedToWallet += value; -// } -// } -// } catch (s) { -// Logging.instance.log(s.toString(), level: LogLevel.Info); -// } -// } -// -// // calculate fee for received tx -// for (int i = 0; i < (txObject["vin"] as List).length; i++) { -// final input = txObject["vin"][i] as Map; -// final prevTxid = input["txid"] as String; -// final prevOut = input["vout"] as int; -// final tx = await _cachedElectrumXClient.getTransaction( -// txHash: prevTxid, -// coin: coin, -// ); -// -// for (final out in tx["vout"] as List) { -// if (prevOut == out["n"]) { -// totalIn += (Decimal.parse((out["value"] ?? 0).toString()) * -// Decimal.fromInt(Constants.satsPerCoin(coin).toInt())) -// .toBigInt() -// .toInt(); -// } -// } -// } -// fee = totalIn - totalOut; -// } -// -// // create final tx map -// midSortedTx["txid"] = txObject["txid"]; -// -// midSortedTx["timestamp"] = txObject["blocktime"] ?? -// (DateTime.now().millisecondsSinceEpoch ~/ 1000); -// -// midSortedTx["address"] = txObject["address"]; -// midSortedTx["inputs"] = txObject["vin"]; -// midSortedTx["outputs"] = txObject["vout"]; -// -// // midSortedArray.add(midSortedTx); -// isar_models.TransactionType type; -// int amount; -// if (foundInSenders) { -// type = isar_models.TransactionType.outgoing; -// amount = inputAmtSentFromWallet; -// } else { -// type = isar_models.TransactionType.incoming; -// amount = outputAmtAddressedToWallet; -// } -// -// isar_models.Address transactionAddress = -// midSortedTx["address"] as isar_models.Address; -// -// List inputs = []; -// List outputs = []; -// -// for (final json in txObject["vin"] as List) { -// bool isCoinBase = json['coinbase'] != null; -// final input = isar_models.Input( -// txid: json['txid'] as String, -// vout: json['vout'] as int? ?? -1, -// scriptSig: json['scriptSig']?['hex'] as String?, -// scriptSigAsm: json['scriptSig']?['asm'] as String?, -// isCoinbase: isCoinBase ? isCoinBase : json['is_coinbase'] as bool?, -// sequence: json['sequence'] as int?, -// innerRedeemScriptAsm: json['innerRedeemscriptAsm'] as String?, -// ); -// inputs.add(input); -// } -// -// for (final json in txObject["vout"] as List) { -// final output = isar_models.Output( -// scriptPubKey: json['scriptPubKey']?['hex'] as String?, -// scriptPubKeyAsm: json['scriptPubKey']?['asm'] as String?, -// scriptPubKeyType: json['scriptPubKey']?['type'] as String?, -// scriptPubKeyAddress: -// json["scriptPubKey"]?["addresses"]?[0] as String? ?? -// json['scriptPubKey']?['type'] as String? ?? -// "", -// value: Amount.fromDecimal( -// Decimal.parse((json["value"] ?? 0).toString()), -// fractionDigits: coin.decimals, -// ).raw.toInt(), -// ); -// outputs.add(output); -// } -// -// final tx = isar_models.Transaction( -// walletId: walletId, -// txid: midSortedTx["txid"] as String, -// timestamp: midSortedTx["timestamp"] as int, -// type: type, -// subType: isar_models.TransactionSubType.none, -// amount: amount, -// amountString: Amount( -// rawValue: BigInt.from(amount), -// fractionDigits: coin.decimals, -// ).toJsonString(), -// fee: fee, -// height: txObject["height"] as int, -// inputs: inputs, -// outputs: outputs, -// isCancelled: false, -// isLelantus: false, -// nonce: null, -// slateId: null, -// otherData: null, -// numberOfMessages: null, -// ); -// -// txns.add(Tuple2(tx, transactionAddress)); -// } -// -// await db.addNewTransactionData(txns, walletId); -// -// // quick hack to notify manager to call notifyListeners if -// // transactions changed -// if (txns.isNotEmpty) { -// GlobalEventBus.instance.fire( -// UpdatedInBackgroundEvent( -// "Transactions updated/added for: $walletId $walletName ", -// walletId, -// ), -// ); -// } -// } -// -// int estimateTxFee({required int vSize, required int feeRatePerKB}) { -// return vSize * (feeRatePerKB / 1000).ceil(); -// } -// -// /// The coinselection algorithm decides whether or not the user is eligible to make the transaction -// /// with [satoshiAmountToSend] and [selectedTxFeeRate]. If so, it will call buildTrasaction() and return -// /// a map containing the tx hex along with other important information. If not, then it will return -// /// an integer (1 or 2) -// dynamic coinSelection({ -// required int satoshiAmountToSend, -// required int selectedTxFeeRate, -// required String recipientAddress, -// required bool coinControl, -// required bool isSendAll, -// int? satsPerVByte, -// int additionalOutputs = 0, -// List? utxos, -// }) async { -// Logging.instance -// .log("Starting coinSelection ----------", level: LogLevel.Info); -// final List availableOutputs = utxos ?? await this.utxos; -// final currentChainHeight = await chainHeight; -// final List spendableOutputs = []; -// int spendableSatoshiValue = 0; -// -// // Build list of spendable outputs and totaling their satoshi amount -// for (final utxo in availableOutputs) { -// if (utxo.isBlocked == false && -// utxo.isConfirmed(currentChainHeight, MINIMUM_CONFIRMATIONS) && -// utxo.used != true) { -// spendableOutputs.add(utxo); -// spendableSatoshiValue += utxo.value; -// } -// } -// -// if (coinControl) { -// if (spendableOutputs.length < availableOutputs.length) { -// throw ArgumentError("Attempted to use an unavailable utxo"); -// } -// } -// -// // don't care about sorting if using all utxos -// if (!coinControl) { -// // sort spendable by age (oldest first) -// spendableOutputs.sort((a, b) => b.blockTime!.compareTo(a.blockTime!)); -// } -// -// Logging.instance.log("spendableOutputs.length: ${spendableOutputs.length}", -// level: LogLevel.Info); -// Logging.instance -// .log("spendableOutputs: $spendableOutputs", level: LogLevel.Info); -// Logging.instance.log("spendableSatoshiValue: $spendableSatoshiValue", -// level: LogLevel.Info); -// Logging.instance -// .log("satoshiAmountToSend: $satoshiAmountToSend", level: LogLevel.Info); -// // If the amount the user is trying to send is smaller than the amount that they have spendable, -// // then return 1, which indicates that they have an insufficient balance. -// if (spendableSatoshiValue < satoshiAmountToSend) { -// return 1; -// // If the amount the user wants to send is exactly equal to the amount they can spend, then return -// // 2, which indicates that they are not leaving enough over to pay the transaction fee -// } else if (spendableSatoshiValue == satoshiAmountToSend && !isSendAll) { -// return 2; -// } -// // If neither of these statements pass, we assume that the user has a spendable balance greater -// // than the amount they're attempting to send. Note that this value still does not account for -// // the added transaction fee, which may require an extra input and will need to be checked for -// // later on. -// -// // Possible situation right here -// int satoshisBeingUsed = 0; -// int inputsBeingConsumed = 0; -// List utxoObjectsToUse = []; -// -// if (!coinControl) { -// for (var i = 0; -// satoshisBeingUsed < satoshiAmountToSend && -// i < spendableOutputs.length; -// i++) { -// utxoObjectsToUse.add(spendableOutputs[i]); -// satoshisBeingUsed += spendableOutputs[i].value; -// inputsBeingConsumed += 1; -// } -// for (int i = 0; -// i < additionalOutputs && -// inputsBeingConsumed < spendableOutputs.length; -// i++) { -// utxoObjectsToUse.add(spendableOutputs[inputsBeingConsumed]); -// satoshisBeingUsed += spendableOutputs[inputsBeingConsumed].value; -// inputsBeingConsumed += 1; -// } -// } else { -// satoshisBeingUsed = spendableSatoshiValue; -// utxoObjectsToUse = spendableOutputs; -// inputsBeingConsumed = spendableOutputs.length; -// } -// -// Logging.instance -// .log("satoshisBeingUsed: $satoshisBeingUsed", level: LogLevel.Info); -// Logging.instance -// .log("inputsBeingConsumed: $inputsBeingConsumed", level: LogLevel.Info); -// Logging.instance -// .log('utxoObjectsToUse: $utxoObjectsToUse', level: LogLevel.Info); -// -// // numberOfOutputs' length must always be equal to that of recipientsArray and recipientsAmtArray -// List recipientsArray = [recipientAddress]; -// List recipientsAmtArray = [satoshiAmountToSend]; -// -// // gather required signing data -// final utxoSigningData = await fetchBuildTxData(utxoObjectsToUse); -// -// if (isSendAll) { -// Logging.instance -// .log("Attempting to send all $coin", level: LogLevel.Info); -// -// final int vSizeForOneOutput = (await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: [recipientAddress], -// satoshiAmounts: [satoshisBeingUsed - 1], -// ))["vSize"] as int; -// int feeForOneOutput = satsPerVByte != null -// ? (satsPerVByte * vSizeForOneOutput) -// : estimateTxFee( -// vSize: vSizeForOneOutput, -// feeRatePerKB: selectedTxFeeRate, -// ); -// -// if (satsPerVByte == null) { -// final int roughEstimate = roughFeeEstimate( -// spendableOutputs.length, -// 1, -// selectedTxFeeRate, -// ).raw.toInt(); -// if (feeForOneOutput < roughEstimate) { -// feeForOneOutput = roughEstimate; -// } -// } -// -// final int amount = satoshiAmountToSend - feeForOneOutput; -// dynamic txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: [amount], -// ); -// Map transactionObject = { -// "hex": txn["hex"], -// "recipient": recipientsArray[0], -// "recipientAmt": Amount( -// rawValue: BigInt.from(amount), -// fractionDigits: coin.decimals, -// ), -// "fee": feeForOneOutput, -// "vSize": txn["vSize"], -// "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), -// }; -// return transactionObject; -// } -// -// final int vSizeForOneOutput = (await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: [recipientAddress], -// satoshiAmounts: [satoshisBeingUsed - 1], -// ))["vSize"] as int; -// final int vSizeForTwoOutPuts = (await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: [ -// recipientAddress, -// await _getCurrentAddressForChain(1, DerivePathTypeExt.primaryFor(coin)), -// ], -// satoshiAmounts: [ -// satoshiAmountToSend, -// satoshisBeingUsed - satoshiAmountToSend - 1 -// ], // dust limit is the minimum amount a change output should be -// ))["vSize"] as int; -// -// // Assume 1 output, only for recipient and no change -// final feeForOneOutput = satsPerVByte != null -// ? (satsPerVByte * vSizeForOneOutput) -// : estimateTxFee( -// vSize: vSizeForOneOutput, -// feeRatePerKB: selectedTxFeeRate, -// ); -// // Assume 2 outputs, one for recipient and one for change -// final feeForTwoOutputs = satsPerVByte != null -// ? (satsPerVByte * vSizeForTwoOutPuts) -// : estimateTxFee( -// vSize: vSizeForTwoOutPuts, -// feeRatePerKB: selectedTxFeeRate, -// ); -// -// Logging.instance -// .log("feeForTwoOutputs: $feeForTwoOutputs", level: LogLevel.Info); -// Logging.instance -// .log("feeForOneOutput: $feeForOneOutput", level: LogLevel.Info); -// -// if (satoshisBeingUsed - satoshiAmountToSend > feeForOneOutput) { -// if (satoshisBeingUsed - satoshiAmountToSend > -// feeForOneOutput + DUST_LIMIT.raw.toInt()) { -// // Here, we know that theoretically, we may be able to include another output(change) but we first need to -// // factor in the value of this output in satoshis. -// int changeOutputSize = -// satoshisBeingUsed - satoshiAmountToSend - feeForTwoOutputs; -// // We check to see if the user can pay for the new transaction with 2 outputs instead of one. If they can and -// // the second output's size > DUST_LIMIT satoshis, we perform the mechanics required to properly generate and use a new -// // change address. -// if (changeOutputSize > DUST_LIMIT.raw.toInt() && -// satoshisBeingUsed - satoshiAmountToSend - changeOutputSize == -// feeForTwoOutputs) { -// // generate new change address if current change address has been used -// await _checkChangeAddressForTransactions(); -// final String newChangeAddress = await _getCurrentAddressForChain( -// 1, DerivePathTypeExt.primaryFor(coin)); -// -// int feeBeingPaid = -// satoshisBeingUsed - satoshiAmountToSend - changeOutputSize; -// -// recipientsArray.add(newChangeAddress); -// recipientsAmtArray.add(changeOutputSize); -// // At this point, we have the outputs we're going to use, the amounts to send along with which addresses -// // we intend to send these amounts to. We have enough to send instructions to build the transaction. -// Logging.instance.log('2 outputs in tx', level: LogLevel.Info); -// Logging.instance -// .log('Input size: $satoshisBeingUsed', level: LogLevel.Info); -// Logging.instance.log('Recipient output size: $satoshiAmountToSend', -// level: LogLevel.Info); -// Logging.instance.log('Change Output Size: $changeOutputSize', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Difference (fee being paid): $feeBeingPaid sats', -// level: LogLevel.Info); -// Logging.instance -// .log('Estimated fee: $feeForTwoOutputs', level: LogLevel.Info); -// dynamic txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: recipientsAmtArray, -// ); -// -// // make sure minimum fee is accurate if that is being used -// if (txn["vSize"] - feeBeingPaid == 1) { -// int changeOutputSize = -// satoshisBeingUsed - satoshiAmountToSend - (txn["vSize"] as int); -// feeBeingPaid = -// satoshisBeingUsed - satoshiAmountToSend - changeOutputSize; -// recipientsAmtArray.removeLast(); -// recipientsAmtArray.add(changeOutputSize); -// Logging.instance.log('Adjusted Input size: $satoshisBeingUsed', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Adjusted Recipient output size: $satoshiAmountToSend', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Adjusted Change Output Size: $changeOutputSize', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Adjusted Difference (fee being paid): $feeBeingPaid sats', -// level: LogLevel.Info); -// Logging.instance.log('Adjusted Estimated fee: $feeForTwoOutputs', -// level: LogLevel.Info); -// txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: recipientsAmtArray, -// ); -// } -// -// Map transactionObject = { -// "hex": txn["hex"], -// "recipient": recipientsArray[0], -// "recipientAmt": Amount( -// rawValue: BigInt.from(recipientsAmtArray[0]), -// fractionDigits: coin.decimals, -// ), -// "fee": feeBeingPaid, -// "vSize": txn["vSize"], -// "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), -// }; -// return transactionObject; -// } else { -// // Something went wrong here. It either overshot or undershot the estimated fee amount or the changeOutputSize -// // is smaller than or equal to DUST_LIMIT. Revert to single output transaction. -// Logging.instance.log('1 output in tx', level: LogLevel.Info); -// Logging.instance -// .log('Input size: $satoshisBeingUsed', level: LogLevel.Info); -// Logging.instance.log('Recipient output size: $satoshiAmountToSend', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Difference (fee being paid): ${satoshisBeingUsed - satoshiAmountToSend} sats', -// level: LogLevel.Info); -// Logging.instance -// .log('Estimated fee: $feeForOneOutput', level: LogLevel.Info); -// dynamic txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: recipientsAmtArray, -// ); -// Map transactionObject = { -// "hex": txn["hex"], -// "recipient": recipientsArray[0], -// "recipientAmt": Amount( -// rawValue: BigInt.from(recipientsAmtArray[0]), -// fractionDigits: coin.decimals, -// ), -// "fee": satoshisBeingUsed - satoshiAmountToSend, -// "vSize": txn["vSize"], -// "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), -// }; -// return transactionObject; -// } -// } else { -// // No additional outputs needed since adding one would mean that it'd be smaller than DUST_LIMIT sats -// // which makes it uneconomical to add to the transaction. Here, we pass data directly to instruct -// // the wallet to begin crafting the transaction that the user requested. -// Logging.instance.log('1 output in tx', level: LogLevel.Info); -// Logging.instance -// .log('Input size: $satoshisBeingUsed', level: LogLevel.Info); -// Logging.instance.log('Recipient output size: $satoshiAmountToSend', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Difference (fee being paid): ${satoshisBeingUsed - satoshiAmountToSend} sats', -// level: LogLevel.Info); -// Logging.instance -// .log('Estimated fee: $feeForOneOutput', level: LogLevel.Info); -// dynamic txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: recipientsAmtArray, -// ); -// Map transactionObject = { -// "hex": txn["hex"], -// "recipient": recipientsArray[0], -// "recipientAmt": Amount( -// rawValue: BigInt.from(recipientsAmtArray[0]), -// fractionDigits: coin.decimals, -// ), -// "fee": satoshisBeingUsed - satoshiAmountToSend, -// "vSize": txn["vSize"], -// "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), -// }; -// return transactionObject; -// } -// } else if (satoshisBeingUsed - satoshiAmountToSend == feeForOneOutput) { -// // In this scenario, no additional change output is needed since inputs - outputs equal exactly -// // what we need to pay for fees. Here, we pass data directly to instruct the wallet to begin -// // crafting the transaction that the user requested. -// Logging.instance.log('1 output in tx', level: LogLevel.Info); -// Logging.instance -// .log('Input size: $satoshisBeingUsed', level: LogLevel.Info); -// Logging.instance.log('Recipient output size: $satoshiAmountToSend', -// level: LogLevel.Info); -// Logging.instance.log( -// 'Fee being paid: ${satoshisBeingUsed - satoshiAmountToSend} sats', -// level: LogLevel.Info); -// Logging.instance -// .log('Estimated fee: $feeForOneOutput', level: LogLevel.Info); -// dynamic txn = await buildTransaction( -// utxoSigningData: utxoSigningData, -// recipients: recipientsArray, -// satoshiAmounts: recipientsAmtArray, -// ); -// Map transactionObject = { -// "hex": txn["hex"], -// "recipient": recipientsArray[0], -// "recipientAmt": Amount( -// rawValue: BigInt.from(recipientsAmtArray[0]), -// fractionDigits: coin.decimals, -// ), -// "fee": feeForOneOutput, -// "vSize": txn["vSize"], -// "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), -// }; -// return transactionObject; -// } else { -// // Remember that returning 2 indicates that the user does not have a sufficient balance to -// // pay for the transaction fee. Ideally, at this stage, we should check if the user has any -// // additional outputs they're able to spend and then recalculate fees. -// Logging.instance.log( -// 'Cannot pay tx fee - checking for more outputs and trying again', -// level: LogLevel.Warning); -// // try adding more outputs -// if (spendableOutputs.length > inputsBeingConsumed) { -// return coinSelection( -// satoshiAmountToSend: satoshiAmountToSend, -// selectedTxFeeRate: selectedTxFeeRate, -// recipientAddress: recipientAddress, -// satsPerVByte: satsPerVByte, -// isSendAll: isSendAll, -// additionalOutputs: additionalOutputs + 1, -// utxos: utxos, -// coinControl: coinControl, -// ); -// } -// return 2; -// } -// } -// -// Future> fetchBuildTxData( -// List utxosToUse, -// ) async { -// // return data -// List signingData = []; -// -// try { -// // Populating the addresses to check -// for (var i = 0; i < utxosToUse.length; i++) { -// if (utxosToUse[i].address == null) { -// final txid = utxosToUse[i].txid; -// final tx = await _cachedElectrumXClient.getTransaction( -// txHash: txid, -// coin: coin, -// ); -// for (final output in tx["vout"] as List) { -// final n = output["n"]; -// if (n != null && n == utxosToUse[i].vout) { -// utxosToUse[i] = utxosToUse[i].copyWith( -// address: output["scriptPubKey"]?["addresses"]?[0] as String? ?? -// output["scriptPubKey"]["address"] as String, -// ); -// } -// } -// } -// -// final derivePathType = addressType(address: utxosToUse[i].address!); -// -// signingData.add( -// SigningData( -// derivePathType: derivePathType, -// utxo: utxosToUse[i], -// ), -// ); -// } -// -// Map> receiveDerivations = {}; -// Map> changeDerivations = {}; -// -// for (final sd in signingData) { -// String? pubKey; -// String? wif; -// -// // fetch receiving derivations if null -// receiveDerivations[sd.derivePathType] ??= await _fetchDerivations( -// chain: 0, -// derivePathType: sd.derivePathType, -// ); -// final receiveDerivation = -// receiveDerivations[sd.derivePathType]![sd.utxo.address!]; -// -// if (receiveDerivation != null) { -// pubKey = receiveDerivation["pubKey"] as String; -// wif = receiveDerivation["wif"] as String; -// } else { -// // fetch change derivations if null -// changeDerivations[sd.derivePathType] ??= await _fetchDerivations( -// chain: 1, -// derivePathType: sd.derivePathType, -// ); -// final changeDerivation = -// changeDerivations[sd.derivePathType]![sd.utxo.address!]; -// if (changeDerivation != null) { -// pubKey = changeDerivation["pubKey"] as String; -// wif = changeDerivation["wif"] as String; -// } -// } -// -// if (wif == null || pubKey == null) { -// final address = await db.getAddress(walletId, sd.utxo.address!); -// if (address?.derivationPath != null) { -// final node = await Bip32Utils.getBip32Node( -// (await mnemonicString)!, -// (await mnemonicPassphrase)!, -// _network, -// address!.derivationPath!.value, -// ); -// -// wif = node.toWIF(); -// pubKey = Format.uint8listToString(node.publicKey); -// } -// } -// -// if (wif != null && pubKey != null) { -// final PaymentData data; -// final Uint8List? redeemScript; -// -// switch (sd.derivePathType) { -// case DerivePathType.bip44: -// data = P2PKH( -// data: PaymentData( -// pubkey: Format.stringToUint8List(pubKey), -// ), -// network: _network, -// ).data; -// redeemScript = null; -// break; -// -// case DerivePathType.bip84: -// data = P2WPKH( -// data: PaymentData( -// pubkey: Format.stringToUint8List(pubKey), -// ), -// network: _network, -// ).data; -// redeemScript = null; -// break; -// -// default: -// throw Exception("DerivePathType unsupported"); -// } -// -// final keyPair = ECPair.fromWIF( -// wif, -// network: _network, -// ); -// -// sd.redeemScript = redeemScript; -// sd.output = data.output; -// sd.keyPair = keyPair; -// } -// } -// -// return signingData; -// } catch (e, s) { -// Logging.instance -// .log("fetchBuildTxData() threw: $e,\n$s", level: LogLevel.Error); -// rethrow; -// } -// } -// -// /// Builds and signs a transaction -// Future> buildTransaction({ -// required List utxoSigningData, -// required List recipients, -// required List satoshiAmounts, -// }) async { -// Logging.instance -// .log("Starting buildTransaction ----------", level: LogLevel.Info); -// -// Logging.instance.log("UTXOs SIGNING DATA IS -----$utxoSigningData", -// level: LogLevel.Info, printFullLength: true); -// -// final txb = TransactionBuilder(network: _network); -// txb.setVersion(160); -// -// // Add transaction inputs -// for (var i = 0; i < utxoSigningData.length; i++) { -// final txid = utxoSigningData[i].utxo.txid; -// txb.addInput( -// txid, -// utxoSigningData[i].utxo.vout, -// null, -// utxoSigningData[i].output!, -// '', -// ); -// } -// -// // Add transaction output -// for (var i = 0; i < recipients.length; i++) { -// txb.addOutput(recipients[i], satoshiAmounts[i], particl.bech32!); -// } -// -// try { -// // Sign the transaction accordingly -// for (var i = 0; i < utxoSigningData.length; i++) { -// txb.sign( -// vin: i, -// keyPair: utxoSigningData[i].keyPair!, -// witnessValue: utxoSigningData[i].utxo.value, -// redeemScript: utxoSigningData[i].redeemScript, -// ); -// } -// } catch (e, s) { -// Logging.instance.log("Caught exception while signing transaction: $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// -// final builtTx = txb.build(); -// final vSize = builtTx.virtualSize(); -// -// String hexBefore = builtTx.toHex(isParticl: true).toString(); -// if (hexBefore.endsWith('000000')) { -// String stripped = hexBefore.substring(0, hexBefore.length - 6); -// return {"hex": stripped, "vSize": vSize}; -// } else if (hexBefore.endsWith('0000')) { -// String stripped = hexBefore.substring(0, hexBefore.length - 4); -// return {"hex": stripped, "vSize": vSize}; -// } else if (hexBefore.endsWith('00')) { -// String stripped = hexBefore.substring(0, hexBefore.length - 2); -// return {"hex": stripped, "vSize": vSize}; -// } else { -// return {"hex": hexBefore, "vSize": vSize}; -// } -// } -// -// @override -// Future fullRescan( -// int maxUnusedAddressGap, -// int maxNumberOfIndexesToCheck, -// ) async { -// Logging.instance.log("Starting full rescan!", level: LogLevel.Info); -// longMutex = true; -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.syncing, -// walletId, -// coin, -// ), -// ); -// -// // clear cache -// await _cachedElectrumXClient.clearSharedTransactionCache(coin: coin); -// -// // back up data -// // await _rescanBackup(); -// -// await db.deleteWalletBlockchainData(walletId); -// await _deleteDerivations(); -// -// try { -// final _mnemonic = await mnemonicString; -// final _mnemonicPassphrase = await mnemonicPassphrase; -// if (_mnemonicPassphrase == null) { -// Logging.instance.log( -// "Exception in fullRescan: mnemonic passphrase null, possible migration issue; if using internal builds, delete wallet and restore from seed, if using a release build, please file bug report", -// level: LogLevel.Error); -// } -// -// await _recoverWalletFromBIP32SeedPhrase( -// mnemonic: _mnemonic!, -// mnemonicPassphrase: _mnemonicPassphrase!, -// maxUnusedAddressGap: maxUnusedAddressGap, -// maxNumberOfIndexesToCheck: maxNumberOfIndexesToCheck, -// isRescan: true, -// ); -// -// longMutex = false; -// await refresh(); -// Logging.instance.log("Full rescan complete!", level: LogLevel.Info); -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.synced, -// walletId, -// coin, -// ), -// ); -// } catch (e, s) { -// GlobalEventBus.instance.fire( -// WalletSyncStatusChangedEvent( -// WalletSyncStatus.unableToSync, -// walletId, -// coin, -// ), -// ); -// -// // restore from backup -// // await _rescanRestore(); -// -// longMutex = false; -// Logging.instance.log("Exception rethrown from fullRescan(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// -// Future _deleteDerivations() async { -// // P2PKH derivations -// await _secureStore.delete(key: "${walletId}_receiveDerivationsP2PKH"); -// await _secureStore.delete(key: "${walletId}_changeDerivationsP2PKH"); -// -// // P2WPKH derivations -// await _secureStore.delete(key: "${walletId}_receiveDerivationsP2WPKH"); -// await _secureStore.delete(key: "${walletId}_changeDerivationsP2WPKH"); -// } -// -// // Future _rescanRestore() async { -// // Logging.instance.log("starting rescan restore", level: LogLevel.Info); -// // -// // // restore from backup -// // // p2pkh -// // final tempReceivingAddressesP2PKH = DB.instance -// // .get(boxName: walletId, key: 'receivingAddressesP2PKH_BACKUP'); -// // final tempChangeAddressesP2PKH = DB.instance -// // .get(boxName: walletId, key: 'changeAddressesP2PKH_BACKUP'); -// // final tempReceivingIndexP2PKH = DB.instance -// // .get(boxName: walletId, key: 'receivingIndexP2PKH_BACKUP'); -// // final tempChangeIndexP2PKH = DB.instance -// // .get(boxName: walletId, key: 'changeIndexP2PKH_BACKUP'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingAddressesP2PKH', -// // value: tempReceivingAddressesP2PKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeAddressesP2PKH', -// // value: tempChangeAddressesP2PKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingIndexP2PKH', -// // value: tempReceivingIndexP2PKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeIndexP2PKH', -// // value: tempChangeIndexP2PKH); -// // await DB.instance.delete( -// // key: 'receivingAddressesP2PKH_BACKUP', boxName: walletId); -// // await DB.instance -// // .delete(key: 'changeAddressesP2PKH_BACKUP', boxName: walletId); -// // await DB.instance -// // .delete(key: 'receivingIndexP2PKH_BACKUP', boxName: walletId); -// // await DB.instance -// // .delete(key: 'changeIndexP2PKH_BACKUP', boxName: walletId); -// // -// // // p2wpkh -// // final tempReceivingAddressesP2WPKH = DB.instance.get( -// // boxName: walletId, key: 'receivingAddressesP2WPKH_BACKUP'); -// // final tempChangeAddressesP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'changeAddressesP2WPKH_BACKUP'); -// // final tempReceivingIndexP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'receivingIndexP2WPKH_BACKUP'); -// // final tempChangeIndexP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'changeIndexP2WPKH_BACKUP'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingAddressesP2WPKH', -// // value: tempReceivingAddressesP2WPKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeAddressesP2WPKH', -// // value: tempChangeAddressesP2WPKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingIndexP2WPKH', -// // value: tempReceivingIndexP2WPKH); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeIndexP2WPKH', -// // value: tempChangeIndexP2WPKH); -// // await DB.instance.delete( -// // key: 'receivingAddressesP2WPKH_BACKUP', boxName: walletId); -// // await DB.instance.delete( -// // key: 'changeAddressesP2WPKH_BACKUP', boxName: walletId); -// // await DB.instance -// // .delete(key: 'receivingIndexP2WPKH_BACKUP', boxName: walletId); -// // await DB.instance -// // .delete(key: 'changeIndexP2WPKH_BACKUP', boxName: walletId); -// // -// // // P2PKH derivations -// // final p2pkhReceiveDerivationsString = await _secureStore.read( -// // key: "${walletId}_receiveDerivationsP2PKH_BACKUP"); -// // final p2pkhChangeDerivationsString = await _secureStore.read( -// // key: "${walletId}_changeDerivationsP2PKH_BACKUP"); -// // -// // await _secureStore.write( -// // key: "${walletId}_receiveDerivationsP2PKH", -// // value: p2pkhReceiveDerivationsString); -// // await _secureStore.write( -// // key: "${walletId}_changeDerivationsP2PKH", -// // value: p2pkhChangeDerivationsString); -// // -// // await _secureStore.delete( -// // key: "${walletId}_receiveDerivationsP2PKH_BACKUP"); -// // await _secureStore.delete(key: "${walletId}_changeDerivationsP2PKH_BACKUP"); -// // -// // // P2WPKH derivations -// // final p2wpkhReceiveDerivationsString = await _secureStore.read( -// // key: "${walletId}_receiveDerivationsP2WPKH_BACKUP"); -// // final p2wpkhChangeDerivationsString = await _secureStore.read( -// // key: "${walletId}_changeDerivationsP2WPKH_BACKUP"); -// // -// // await _secureStore.write( -// // key: "${walletId}_receiveDerivationsP2WPKH", -// // value: p2wpkhReceiveDerivationsString); -// // await _secureStore.write( -// // key: "${walletId}_changeDerivationsP2WPKH", -// // value: p2wpkhChangeDerivationsString); -// // -// // await _secureStore.delete( -// // key: "${walletId}_receiveDerivationsP2WPKH_BACKUP"); -// // await _secureStore.delete( -// // key: "${walletId}_changeDerivationsP2WPKH_BACKUP"); -// // -// // // UTXOs -// // final utxoData = DB.instance -// // .get(boxName: walletId, key: 'latest_utxo_model_BACKUP'); -// // await DB.instance.put( -// // boxName: walletId, key: 'latest_utxo_model', value: utxoData); -// // await DB.instance -// // .delete(key: 'latest_utxo_model_BACKUP', boxName: walletId); -// // -// // Logging.instance.log("rescan restore complete", level: LogLevel.Info); -// // } -// // -// // Future _rescanBackup() async { -// // Logging.instance.log("starting rescan backup", level: LogLevel.Info); -// // -// // // backup current and clear data -// // // p2pkh -// // final tempReceivingAddressesP2PKH = DB.instance -// // .get(boxName: walletId, key: 'receivingAddressesP2PKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingAddressesP2PKH_BACKUP', -// // value: tempReceivingAddressesP2PKH); -// // await DB.instance -// // .delete(key: 'receivingAddressesP2PKH', boxName: walletId); -// // -// // final tempChangeAddressesP2PKH = DB.instance -// // .get(boxName: walletId, key: 'changeAddressesP2PKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeAddressesP2PKH_BACKUP', -// // value: tempChangeAddressesP2PKH); -// // await DB.instance -// // .delete(key: 'changeAddressesP2PKH', boxName: walletId); -// // -// // final tempReceivingIndexP2PKH = -// // DB.instance.get(boxName: walletId, key: 'receivingIndexP2PKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingIndexP2PKH_BACKUP', -// // value: tempReceivingIndexP2PKH); -// // await DB.instance -// // .delete(key: 'receivingIndexP2PKH', boxName: walletId); -// // -// // final tempChangeIndexP2PKH = -// // DB.instance.get(boxName: walletId, key: 'changeIndexP2PKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeIndexP2PKH_BACKUP', -// // value: tempChangeIndexP2PKH); -// // await DB.instance -// // .delete(key: 'changeIndexP2PKH', boxName: walletId); -// // -// // // p2wpkh -// // final tempReceivingAddressesP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'receivingAddressesP2WPKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingAddressesP2WPKH_BACKUP', -// // value: tempReceivingAddressesP2WPKH); -// // await DB.instance -// // .delete(key: 'receivingAddressesP2WPKH', boxName: walletId); -// // -// // final tempChangeAddressesP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'changeAddressesP2WPKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeAddressesP2WPKH_BACKUP', -// // value: tempChangeAddressesP2WPKH); -// // await DB.instance -// // .delete(key: 'changeAddressesP2WPKH', boxName: walletId); -// // -// // final tempReceivingIndexP2WPKH = DB.instance -// // .get(boxName: walletId, key: 'receivingIndexP2WPKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'receivingIndexP2WPKH_BACKUP', -// // value: tempReceivingIndexP2WPKH); -// // await DB.instance -// // .delete(key: 'receivingIndexP2WPKH', boxName: walletId); -// // -// // final tempChangeIndexP2WPKH = -// // DB.instance.get(boxName: walletId, key: 'changeIndexP2WPKH'); -// // await DB.instance.put( -// // boxName: walletId, -// // key: 'changeIndexP2WPKH_BACKUP', -// // value: tempChangeIndexP2WPKH); -// // await DB.instance -// // .delete(key: 'changeIndexP2WPKH', boxName: walletId); -// // -// // // P2PKH derivations -// // final p2pkhReceiveDerivationsString = -// // await _secureStore.read(key: "${walletId}_receiveDerivationsP2PKH"); -// // final p2pkhChangeDerivationsString = -// // await _secureStore.read(key: "${walletId}_changeDerivationsP2PKH"); -// // -// // await _secureStore.write( -// // key: "${walletId}_receiveDerivationsP2PKH_BACKUP", -// // value: p2pkhReceiveDerivationsString); -// // await _secureStore.write( -// // key: "${walletId}_changeDerivationsP2PKH_BACKUP", -// // value: p2pkhChangeDerivationsString); -// // -// // await _secureStore.delete(key: "${walletId}_receiveDerivationsP2PKH"); -// // await _secureStore.delete(key: "${walletId}_changeDerivationsP2PKH"); -// // -// // // P2WPKH derivations -// // final p2wpkhReceiveDerivationsString = -// // await _secureStore.read(key: "${walletId}_receiveDerivationsP2WPKH"); -// // final p2wpkhChangeDerivationsString = -// // await _secureStore.read(key: "${walletId}_changeDerivationsP2WPKH"); -// // -// // await _secureStore.write( -// // key: "${walletId}_receiveDerivationsP2WPKH_BACKUP", -// // value: p2wpkhReceiveDerivationsString); -// // await _secureStore.write( -// // key: "${walletId}_changeDerivationsP2WPKH_BACKUP", -// // value: p2wpkhChangeDerivationsString); -// // -// // await _secureStore.delete(key: "${walletId}_receiveDerivationsP2WPKH"); -// // await _secureStore.delete(key: "${walletId}_changeDerivationsP2WPKH"); -// // -// // // UTXOs -// // final utxoData = -// // DB.instance.get(boxName: walletId, key: 'latest_utxo_model'); -// // await DB.instance.put( -// // boxName: walletId, key: 'latest_utxo_model_BACKUP', value: utxoData); -// // await DB.instance -// // .delete(key: 'latest_utxo_model', boxName: walletId); -// // -// // Logging.instance.log("rescan backup complete", level: LogLevel.Info); -// // } -// -// bool isActive = false; -// -// @override -// void Function(bool)? get onIsActiveWalletChanged => -// (isActive) => this.isActive = isActive; -// -// @override -// Future estimateFeeFor(Amount amount, int feeRate) async { -// final available = balance.spendable; -// -// if (available == amount) { -// return amount - (await sweepAllEstimate(feeRate)); -// } else if (amount <= Amount.zero || amount > available) { -// return roughFeeEstimate(1, 2, feeRate); -// } -// -// Amount runningBalance = Amount( -// rawValue: BigInt.zero, -// fractionDigits: coin.decimals, -// ); -// int inputCount = 0; -// for (final output in (await utxos)) { -// if (!output.isBlocked) { -// runningBalance += Amount( -// rawValue: BigInt.from(output.value), -// fractionDigits: coin.decimals, -// ); -// inputCount++; -// if (runningBalance > amount) { -// break; -// } -// } -// } -// -// final oneOutPutFee = roughFeeEstimate(inputCount, 1, feeRate); -// final twoOutPutFee = roughFeeEstimate(inputCount, 2, feeRate); -// -// if (runningBalance - amount > oneOutPutFee) { -// if (runningBalance - amount > oneOutPutFee + DUST_LIMIT) { -// final change = runningBalance - amount - twoOutPutFee; -// if (change > DUST_LIMIT && -// runningBalance - amount - change == twoOutPutFee) { -// return runningBalance - amount - change; -// } else { -// return runningBalance - amount; -// } -// } else { -// return runningBalance - amount; -// } -// } else if (runningBalance - amount == oneOutPutFee) { -// return oneOutPutFee; -// } else { -// return twoOutPutFee; -// } -// } -// -// Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB) { -// return Amount( -// rawValue: BigInt.from( -// ((42 + (272 * inputCount) + (128 * outputCount)) / 4).ceil() * -// (feeRatePerKB / 1000).ceil()), -// fractionDigits: coin.decimals, -// ); -// } -// -// Future sweepAllEstimate(int feeRate) async { -// int available = 0; -// int inputCount = 0; -// for (final output in (await utxos)) { -// if (!output.isBlocked && -// output.isConfirmed(storedChainHeight, MINIMUM_CONFIRMATIONS)) { -// available += output.value; -// inputCount++; -// } -// } -// -// // transaction will only have 1 output minus the fee -// final estimatedFee = roughFeeEstimate(inputCount, 1, feeRate); -// -// return Amount( -// rawValue: BigInt.from(available), -// fractionDigits: coin.decimals, -// ) - -// estimatedFee; -// } -// -// @override -// Future generateNewAddress() async { -// try { -// final currentReceiving = await _currentReceivingAddress; -// -// final newReceivingIndex = currentReceiving.derivationIndex + 1; -// -// // Use new index to derive a new receiving address -// final newReceivingAddress = await _generateAddressForChain( -// 0, newReceivingIndex, DerivePathTypeExt.primaryFor(coin)); -// -// // Add that new receiving address -// await db.putAddress(newReceivingAddress); -// -// return true; -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from generateNewAddress(): $e\n$s", -// level: LogLevel.Error); -// return false; -// } -// } -// -// @override -// Future get xpub async { -// final node = await Bip32Utils.getBip32Root( -// (await mnemonic).join(" "), -// await mnemonicPassphrase ?? "", -// _network, -// ); -// -// return node.neutered().toBase58(); -// } -// } -// -// // Particl Network -// final particl = NetworkType( -// messagePrefix: '\x18Bitcoin Signed Message:\n', -// bech32: 'pw', -// bip32: Bip32Type(public: 0x696e82d1, private: 0x8f1daeb8), -// pubKeyHash: 0x38, -// scriptHash: 0x3c, -// wif: 0x6c); diff --git a/lib/services/coins/stellar/stellar_wallet.dart b/lib/services/coins/stellar/stellar_wallet.dart deleted file mode 100644 index 482093529..000000000 --- a/lib/services/coins/stellar/stellar_wallet.dart +++ /dev/null @@ -1,227 +0,0 @@ -// import 'dart:async'; -// -// import 'package:bip39/bip39.dart' as bip39; -// import 'package:isar/isar.dart'; -// import 'package:stackwallet/db/isar/main_db.dart'; -// import 'package:stackwallet/models/balance.dart' as SWBalance; -// import 'package:stackwallet/models/isar/models/blockchain_data/address.dart' -// as SWAddress; -// import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart' -// as SWTransaction; -// import 'package:stackwallet/models/isar/models/blockchain_data/utxo.dart'; -// import 'package:stackwallet/models/node_model.dart'; -// import 'package:stackwallet/models/paymint/fee_object_model.dart'; -// import 'package:stackwallet/services/coins/coin_service.dart'; -// import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart'; -// import 'package:stackwallet/services/event_bus/events/global/updated_in_background_event.dart'; -// import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; -// import 'package:stackwallet/services/event_bus/global_event_bus.dart'; -// import 'package:stackwallet/services/mixins/wallet_cache.dart'; -// import 'package:stackwallet/services/mixins/wallet_db.dart'; -// import 'package:stackwallet/services/node_service.dart'; -// import 'package:stackwallet/services/transaction_notification_tracker.dart'; -// import 'package:stackwallet/utilities/amount/amount.dart'; -// import 'package:stackwallet/utilities/constants.dart'; -// import 'package:stackwallet/utilities/default_nodes.dart'; -// import 'package:stackwallet/utilities/enums/coin_enum.dart'; -// import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; -// import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; -// import 'package:stackwallet/utilities/logger.dart'; -// import 'package:stackwallet/utilities/prefs.dart'; -// import 'package:stackwallet/utilities/test_stellar_node_connection.dart'; -// import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart'; -// import 'package:tuple/tuple.dart'; -// -// const int MINIMUM_CONFIRMATIONS = 1; -// -// class StellarWallet extends CoinServiceAPI with WalletCache, WalletDB { -// late StellarSDK stellarSdk; -// late Network stellarNetwork; -// -// StellarWallet({ -// required String walletId, -// required String walletName, -// required Coin coin, -// required TransactionNotificationTracker tracker, -// required SecureStorageInterface secureStore, -// MainDB? mockableOverride, -// }) { -// txTracker = tracker; -// _walletId = walletId; -// _walletName = walletName; -// _coin = coin; -// _secureStore = secureStore; -// initCache(walletId, coin); -// initWalletDB(mockableOverride: mockableOverride); -// -// if (coin.isTestNet) { -// stellarNetwork = Network.TESTNET; -// } else { -// stellarNetwork = Network.PUBLIC; -// } -// -// _updateNode(); -// } -// -// Future updateTransactions() async { -// try { -// List> -// transactionList = []; -// Page payments; -// try { -// payments = await stellarSdk.payments -// .forAccount(await getAddressSW()) -// .order(RequestBuilderOrder.DESC) -// .execute() -// .onError((error, stackTrace) => throw error!); -// } catch (e) { -// if (e is ErrorResponse && -// e.body.contains("The resource at the url requested was not found. " -// "This usually occurs for one of two reasons: " -// "The url requested is not valid, or no data in our database " -// "could be found with the parameters provided.")) { -// // probably just doesn't have any history yet or whatever stellar needs -// return; -// } else { -// Logging.instance.log( -// "Stellar $walletName $walletId failed to fetch transactions", -// level: LogLevel.Warning, -// ); -// rethrow; -// } -// } -// for (OperationResponse response in payments.records!) { -// // PaymentOperationResponse por; -// if (response is PaymentOperationResponse) { -// PaymentOperationResponse por = response; -// -// SWTransaction.TransactionType type; -// if (por.sourceAccount == await getAddressSW()) { -// type = SWTransaction.TransactionType.outgoing; -// } else { -// type = SWTransaction.TransactionType.incoming; -// } -// final amount = Amount( -// rawValue: BigInt.parse(float -// .parse(por.amount!) -// .toStringAsFixed(coin.decimals) -// .replaceAll(".", "")), -// fractionDigits: coin.decimals, -// ); -// int fee = 0; -// int height = 0; -// //Query the transaction linked to the payment, -// // por.transaction returns a null sometimes -// TransactionResponse tx = -// await stellarSdk.transactions.transaction(por.transactionHash!); -// -// if (tx.hash.isNotEmpty) { -// fee = tx.feeCharged!; -// height = tx.ledger; -// } -// var theTransaction = SWTransaction.Transaction( -// walletId: walletId, -// txid: por.transactionHash!, -// timestamp: -// DateTime.parse(por.createdAt!).millisecondsSinceEpoch ~/ 1000, -// type: type, -// subType: SWTransaction.TransactionSubType.none, -// amount: 0, -// amountString: amount.toJsonString(), -// fee: fee, -// height: height, -// isCancelled: false, -// isLelantus: false, -// slateId: "", -// otherData: "", -// inputs: [], -// outputs: [], -// nonce: 0, -// numberOfMessages: null, -// ); -// SWAddress.Address? receivingAddress = await _currentReceivingAddress; -// SWAddress.Address address = -// type == SWTransaction.TransactionType.incoming -// ? receivingAddress! -// : SWAddress.Address( -// walletId: walletId, -// value: por.sourceAccount!, -// publicKey: -// KeyPair.fromAccountId(por.sourceAccount!).publicKey, -// derivationIndex: 0, -// derivationPath: null, -// type: SWAddress.AddressType.unknown, // TODO: set type -// subType: SWAddress.AddressSubType.unknown); -// Tuple2 tuple = -// Tuple2(theTransaction, address); -// transactionList.add(tuple); -// } else if (response is CreateAccountOperationResponse) { -// CreateAccountOperationResponse caor = response; -// SWTransaction.TransactionType type; -// if (caor.sourceAccount == await getAddressSW()) { -// type = SWTransaction.TransactionType.outgoing; -// } else { -// type = SWTransaction.TransactionType.incoming; -// } -// final amount = Amount( -// rawValue: BigInt.parse(float -// .parse(caor.startingBalance!) -// .toStringAsFixed(coin.decimals) -// .replaceAll(".", "")), -// fractionDigits: coin.decimals, -// ); -// int fee = 0; -// int height = 0; -// TransactionResponse tx = -// await stellarSdk.transactions.transaction(caor.transactionHash!); -// if (tx.hash.isNotEmpty) { -// fee = tx.feeCharged!; -// height = tx.ledger; -// } -// var theTransaction = SWTransaction.Transaction( -// walletId: walletId, -// txid: caor.transactionHash!, -// timestamp: -// DateTime.parse(caor.createdAt!).millisecondsSinceEpoch ~/ 1000, -// type: type, -// subType: SWTransaction.TransactionSubType.none, -// amount: 0, -// amountString: amount.toJsonString(), -// fee: fee, -// height: height, -// isCancelled: false, -// isLelantus: false, -// slateId: "", -// otherData: "", -// inputs: [], -// outputs: [], -// nonce: 0, -// numberOfMessages: null, -// ); -// SWAddress.Address? receivingAddress = await _currentReceivingAddress; -// SWAddress.Address address = -// type == SWTransaction.TransactionType.incoming -// ? receivingAddress! -// : SWAddress.Address( -// walletId: walletId, -// value: caor.sourceAccount!, -// publicKey: -// KeyPair.fromAccountId(caor.sourceAccount!).publicKey, -// derivationIndex: 0, -// derivationPath: null, -// type: SWAddress.AddressType.unknown, // TODO: set type -// subType: SWAddress.AddressSubType.unknown); -// Tuple2 tuple = -// Tuple2(theTransaction, address); -// transactionList.add(tuple); -// } -// } -// await db.addNewTransactionData(transactionList, walletId); -// } catch (e, s) { -// Logging.instance.log( -// "Exception rethrown from updateTransactions(): $e\n$s", -// level: LogLevel.Error); -// rethrow; -// } -// } -// } diff --git a/lib/services/mixins/electrum_x_parsing.dart b/lib/services/mixins/electrum_x_parsing.dart deleted file mode 100644 index b7563abdf..000000000 --- a/lib/services/mixins/electrum_x_parsing.dart +++ /dev/null @@ -1,375 +0,0 @@ -/* - * This file is part of Stack Wallet. - * - * Copyright (c) 2023 Cypher Stack - * All Rights Reserved. - * The code is distributed under GPLv3 license, see LICENSE file for details. - * Generated by Cypher Stack on 2023-05-26 - * - */ - -import 'dart:convert'; - -import 'package:bip47/src/util.dart'; -import 'package:decimal/decimal.dart'; -import 'package:stackwallet/electrumx_rpc/cached_electrumx_client.dart'; -import 'package:stackwallet/models/isar/models/blockchain_data/v2/input_v2.dart'; -import 'package:stackwallet/models/isar/models/blockchain_data/v2/output_v2.dart'; -import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; -import 'package:stackwallet/models/isar/models/isar_models.dart'; -import 'package:stackwallet/utilities/amount/amount.dart'; -import 'package:stackwallet/utilities/enums/coin_enum.dart'; -import 'package:stackwallet/utilities/util.dart' as util; -import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; -import 'package:tuple/tuple.dart'; - -mixin ElectrumXParsing { - Future getTransaction( - String txHash, - Coin coin, - String walletId, - CachedElectrumXClient cachedElectrumX, [ - String? debugTitle, - ]) async { - final jsonTx = await cachedElectrumX.getTransaction( - txHash: txHash, - coin: coin, - ); - print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); - util.Util.printJson(jsonTx, debugTitle); - print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); - - // parse inputs - final List inputs = []; - for (final jsonInput in jsonTx["vin"] as List) { - final map = Map.from(jsonInput as Map); - - final List addresses = []; - String valueStringSats = "0"; - OutpointV2? outpoint; - - final coinbase = map["coinbase"] as String?; - - if (coinbase == null) { - final txid = map["txid"] as String; - final vout = map["vout"] as int; - - final inputTx = - await cachedElectrumX.getTransaction(txHash: txid, coin: coin); - - final prevOutJson = Map.from( - (inputTx["vout"] as List).firstWhere((e) => e["n"] == vout) as Map); - - final prevOut = OutputV2.fromElectrumXJson( - prevOutJson, - decimalPlaces: coin.decimals, - walletOwns: false, - ); - - outpoint = OutpointV2.isarCantDoRequiredInDefaultConstructor( - txid: txid, - vout: vout, - ); - valueStringSats = prevOut.valueStringSats; - addresses.addAll(prevOut.addresses); - } - - final input = InputV2.isarCantDoRequiredInDefaultConstructor( - scriptSigHex: map["scriptSig"]?["hex"] as String?, - scriptSigAsm: map["scriptSig"]?["asm"] as String?, - sequence: map["sequence"] as int?, - outpoint: outpoint, - valueStringSats: valueStringSats, - addresses: addresses, - witness: map["witness"] as String?, - coinbase: coinbase, - innerRedeemScriptAsm: map["innerRedeemscriptAsm"] as String?, - walletOwns: false, - ); - - inputs.add(input); - } - - // parse outputs - final List outputs = []; - for (final outputJson in jsonTx["vout"] as List) { - final output = OutputV2.fromElectrumXJson( - Map.from(outputJson as Map), - decimalPlaces: coin.decimals, - walletOwns: false, - ); - outputs.add(output); - } - - return TransactionV2( - walletId: walletId, - blockHash: jsonTx["blockhash"] as String?, - hash: jsonTx["hash"] as String, - txid: jsonTx["txid"] as String, - height: jsonTx["height"] as int?, - version: jsonTx["version"] as int, - timestamp: jsonTx["blocktime"] as int? ?? - DateTime.timestamp().millisecondsSinceEpoch ~/ 1000, - inputs: List.unmodifiable(inputs), - outputs: List.unmodifiable(outputs), - subType: TransactionSubType.none, - type: TransactionType.unknown, - otherData: null, - ); - } - - Future> parseTransaction( - Map txData, - dynamic electrumxClient, - List
myAddresses, - Coin coin, - int minConfirms, - String walletId, - ) async { - Set receivingAddresses = myAddresses - .where((e) => - e.subType == AddressSubType.receiving || - e.subType == AddressSubType.paynymReceive || - e.subType == AddressSubType.paynymNotification) - .map((e) => e.value) - .toSet(); - Set changeAddresses = myAddresses - .where((e) => e.subType == AddressSubType.change) - .map((e) => e.value) - .toSet(); - - Set inputAddresses = {}; - Set outputAddresses = {}; - - Amount totalInputValue = Amount( - rawValue: BigInt.zero, - fractionDigits: coin.decimals, - ); - Amount totalOutputValue = Amount( - rawValue: BigInt.zero, - fractionDigits: coin.decimals, - ); - - Amount amountSentFromWallet = Amount( - rawValue: BigInt.zero, - fractionDigits: coin.decimals, - ); - Amount amountReceivedInWallet = Amount( - rawValue: BigInt.zero, - fractionDigits: coin.decimals, - ); - Amount changeAmount = Amount( - rawValue: BigInt.zero, - fractionDigits: coin.decimals, - ); - - // parse inputs - for (final input in txData["vin"] as List) { - final prevTxid = input["txid"] as String; - final prevOut = input["vout"] as int; - - // fetch input tx to get address - final inputTx = await electrumxClient.getTransaction( - txHash: prevTxid, - coin: coin, - ); - - for (final output in inputTx["vout"] as List) { - // check matching output - if (prevOut == output["n"]) { - // get value - final value = Amount.fromDecimal( - Decimal.parse(output["value"].toString()), - fractionDigits: coin.decimals, - ); - - // add value to total - totalInputValue += value; - - // get input(prevOut) address - final address = output["scriptPubKey"]?["addresses"]?[0] as String? ?? - output["scriptPubKey"]?["address"] as String?; - - if (address != null) { - inputAddresses.add(address); - - // if input was from my wallet, add value to amount sent - if (receivingAddresses.contains(address) || - changeAddresses.contains(address)) { - amountSentFromWallet += value; - } - } - } - } - } - - // parse outputs - for (final output in txData["vout"] as List) { - // get value - final value = Amount.fromDecimal( - Decimal.parse(output["value"].toString()), - fractionDigits: coin.decimals, - ); - - // add value to total - totalOutputValue += value; - - // get output address - final address = output["scriptPubKey"]?["addresses"]?[0] as String? ?? - output["scriptPubKey"]?["address"] as String?; - if (address != null) { - outputAddresses.add(address); - - // if output was to my wallet, add value to amount received - if (receivingAddresses.contains(address)) { - amountReceivedInWallet += value; - } else if (changeAddresses.contains(address)) { - changeAmount += value; - } - } - } - - final mySentFromAddresses = [ - ...receivingAddresses.intersection(inputAddresses), - ...changeAddresses.intersection(inputAddresses) - ]; - final myReceivedOnAddresses = - receivingAddresses.intersection(outputAddresses); - final myChangeReceivedOnAddresses = - changeAddresses.intersection(outputAddresses); - - final fee = totalInputValue - totalOutputValue; - - // this is the address initially used to fetch the txid - Address transactionAddress = txData["address"] as Address; - - TransactionType type; - Amount amount; - if (mySentFromAddresses.isNotEmpty && myReceivedOnAddresses.isNotEmpty) { - // tx is sent to self - type = TransactionType.sentToSelf; - - // should be 0 - amount = - amountSentFromWallet - amountReceivedInWallet - fee - changeAmount; - } else if (mySentFromAddresses.isNotEmpty) { - // outgoing tx - type = TransactionType.outgoing; - amount = amountSentFromWallet - changeAmount - fee; - - // non wallet addresses found in tx outputs - final nonWalletOutAddresses = outputAddresses.difference( - myChangeReceivedOnAddresses, - ); - - if (nonWalletOutAddresses.isNotEmpty) { - final possible = nonWalletOutAddresses.first; - - if (transactionAddress.value != possible) { - transactionAddress = Address( - walletId: walletId, - value: possible, - derivationIndex: -1, - derivationPath: null, - subType: AddressSubType.nonWallet, - type: AddressType.nonWallet, - publicKey: [], - ); - } - } else { - // some other type of tx where the receiving address is - // one of my change addresses - - type = TransactionType.sentToSelf; - amount = changeAmount; - } - } else { - // incoming tx - type = TransactionType.incoming; - amount = amountReceivedInWallet; - } - - List outs = []; - List ins = []; - - for (final json in txData["vin"] as List) { - bool isCoinBase = json['coinbase'] != null; - String? witness; - if (json['witness'] != null && json['witness'] is String) { - witness = json['witness'] as String; - } else if (json['txinwitness'] != null) { - if (json['txinwitness'] is List) { - witness = jsonEncode(json['txinwitness']); - } - } - final input = Input( - txid: json['txid'] as String, - vout: json['vout'] as int? ?? -1, - scriptSig: json['scriptSig']?['hex'] as String?, - scriptSigAsm: json['scriptSig']?['asm'] as String?, - isCoinbase: isCoinBase ? isCoinBase : json['is_coinbase'] as bool?, - sequence: json['sequence'] as int?, - innerRedeemScriptAsm: json['innerRedeemscriptAsm'] as String?, - witness: witness, - ); - ins.add(input); - } - - for (final json in txData["vout"] as List) { - final output = Output( - scriptPubKey: json['scriptPubKey']?['hex'] as String?, - scriptPubKeyAsm: json['scriptPubKey']?['asm'] as String?, - scriptPubKeyType: json['scriptPubKey']?['type'] as String?, - scriptPubKeyAddress: - json["scriptPubKey"]?["addresses"]?[0] as String? ?? - json['scriptPubKey']?['type'] as String? ?? - "", - value: Amount.fromDecimal( - Decimal.parse(json["value"].toString()), - fractionDigits: coin.decimals, - ).raw.toInt(), - ); - outs.add(output); - } - - TransactionSubType txSubType = TransactionSubType.none; - if (this is PaynymInterface && outs.length > 1 && ins.isNotEmpty) { - for (int i = 0; i < outs.length; i++) { - List? scriptChunks = outs[i].scriptPubKeyAsm?.split(" "); - if (scriptChunks?.length == 2 && scriptChunks?[0] == "OP_RETURN") { - final blindedPaymentCode = scriptChunks![1]; - final bytes = blindedPaymentCode.fromHex; - - // https://en.bitcoin.it/wiki/BIP_0047#Sending - if (bytes.length == 80 && bytes.first == 1) { - txSubType = TransactionSubType.bip47Notification; - } - } - } - } - - final tx = Transaction( - walletId: walletId, - txid: txData["txid"] as String, - timestamp: txData["blocktime"] as int? ?? - (DateTime.now().millisecondsSinceEpoch ~/ 1000), - type: type, - subType: txSubType, - // amount may overflow. Deprecated. Use amountString - amount: amount.raw.toInt(), - amountString: amount.toJsonString(), - fee: fee.raw.toInt(), - height: txData["height"] as int?, - isCancelled: false, - isLelantus: false, - slateId: null, - otherData: null, - nonce: null, - inputs: ins, - outputs: outs, - numberOfMessages: null, - ); - - return Tuple2(tx, transactionAddress); - } -} diff --git a/lib/wallets/wallets_service.dart b/lib/wallets/wallets_service.dart deleted file mode 100644 index ad22480d3..000000000 --- a/lib/wallets/wallets_service.dart +++ /dev/null @@ -1,15 +0,0 @@ -import 'package:stackwallet/db/isar/main_db.dart'; -import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; - -class WalletsService { - late final SecureStorageInterface _secureStore; - late final MainDB _mainDB; - - WalletsService({ - required SecureStorageInterface secureStorageInterface, - required MainDB mainDB, - }) { - _secureStore = secureStorageInterface; - _mainDB = mainDB; - } -} diff --git a/test/pages/send_view/send_view_test.dart b/test/pages/send_view/send_view_test.dart index 0bc36e0d4..92693e202 100644 --- a/test/pages/send_view/send_view_test.dart +++ b/test/pages/send_view/send_view_test.dart @@ -2,13 +2,11 @@ import 'package:mockito/annotations.dart'; import 'package:stackwallet/services/locale_service.dart'; import 'package:stackwallet/services/node_service.dart'; import 'package:stackwallet/services/wallets.dart'; -import 'package:stackwallet/services/wallets_service.dart'; import 'package:stackwallet/themes/theme_service.dart'; import 'package:stackwallet/utilities/prefs.dart'; @GenerateMocks([ Wallets, - WalletsService, NodeService, LocaleService, ThemeService, diff --git a/test/pages/send_view/send_view_test.mocks.dart b/test/pages/send_view/send_view_test.mocks.dart index e809b127b..fba574b15 100644 --- a/test/pages/send_view/send_view_test.mocks.dart +++ b/test/pages/send_view/send_view_test.mocks.dart @@ -4,23 +4,22 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i10; -import 'dart:typed_data' as _i20; +import 'dart:typed_data' as _i19; import 'dart:ui' as _i15; import 'package:mockito/mockito.dart' as _i1; import 'package:stackwallet/db/isar/main_db.dart' as _i3; -import 'package:stackwallet/models/isar/stack_theme.dart' as _i19; -import 'package:stackwallet/models/node_model.dart' as _i16; +import 'package:stackwallet/models/isar/stack_theme.dart' as _i18; +import 'package:stackwallet/models/node_model.dart' as _i13; import 'package:stackwallet/networking/http.dart' as _i7; -import 'package:stackwallet/services/locale_service.dart' as _i17; +import 'package:stackwallet/services/locale_service.dart' as _i16; import 'package:stackwallet/services/node_service.dart' as _i2; import 'package:stackwallet/services/wallets.dart' as _i9; -import 'package:stackwallet/services/wallets_service.dart' as _i13; -import 'package:stackwallet/themes/theme_service.dart' as _i18; -import 'package:stackwallet/utilities/amount/amount_unit.dart' as _i23; -import 'package:stackwallet/utilities/enums/backup_frequency_type.dart' as _i22; +import 'package:stackwallet/themes/theme_service.dart' as _i17; +import 'package:stackwallet/utilities/amount/amount_unit.dart' as _i22; +import 'package:stackwallet/utilities/enums/backup_frequency_type.dart' as _i21; import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i14; -import 'package:stackwallet/utilities/enums/sync_type_enum.dart' as _i21; +import 'package:stackwallet/utilities/enums/sync_type_enum.dart' as _i20; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart' as _i6; import 'package:stackwallet/utilities/prefs.dart' as _i12; @@ -208,6 +207,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { _i10.Future loadAfterStackRestore( _i12.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -215,6 +215,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i10.Future.value(), @@ -222,240 +223,6 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { ) as _i10.Future); } -/// A class which mocks [WalletsService]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockWalletsService extends _i1.Mock implements _i13.WalletsService { - MockWalletsService() { - _i1.throwOnMissingStub(this); - } - - @override - _i10.Future> get walletNames => - (super.noSuchMethod( - Invocation.getter(#walletNames), - returnValue: _i10.Future>.value( - {}), - ) as _i10.Future>); - @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); - @override - _i10.Future renameWallet({ - required String? from, - required String? to, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #renameWallet, - [], - { - #from: from, - #to: to, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - Map fetchWalletsData() => (super.noSuchMethod( - Invocation.method( - #fetchWalletsData, - [], - ), - returnValue: {}, - ) as Map); - @override - _i10.Future addExistingStackWallet({ - required String? name, - required String? walletId, - required _i14.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addExistingStackWallet, - [], - { - #name: name, - #walletId: walletId, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future addNewWallet({ - required String? name, - required _i14.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addNewWallet, - [], - { - #name: name, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future> getFavoriteWalletIds() => (super.noSuchMethod( - Invocation.method( - #getFavoriteWalletIds, - [], - ), - returnValue: _i10.Future>.value([]), - ) as _i10.Future>); - @override - _i10.Future saveFavoriteWalletIds(List? walletIds) => - (super.noSuchMethod( - Invocation.method( - #saveFavoriteWalletIds, - [walletIds], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future addFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #addFavorite, - [walletId], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future removeFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #removeFavorite, - [walletId], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future moveFavorite({ - required int? fromIndex, - required int? toIndex, - }) => - (super.noSuchMethod( - Invocation.method( - #moveFavorite, - [], - { - #fromIndex: fromIndex, - #toIndex: toIndex, - }, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future checkForDuplicate(String? name) => (super.noSuchMethod( - Invocation.method( - #checkForDuplicate, - [name], - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - _i10.Future getWalletId(String? walletName) => (super.noSuchMethod( - Invocation.method( - #getWalletId, - [walletName], - ), - returnValue: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future isMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #isMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - _i10.Future setMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #setMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future deleteWallet( - String? name, - bool? shouldNotifyListeners, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteWallet, - [ - name, - shouldNotifyListeners, - ], - ), - returnValue: _i10.Future.value(0), - ) as _i10.Future); - @override - _i10.Future refreshWallets(bool? shouldNotifyListeners) => - (super.noSuchMethod( - Invocation.method( - #refreshWallets, - [shouldNotifyListeners], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValueForMissingStub: null, - ); - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [NodeService]. /// /// See the documentation for Mockito's code generation for more information. @@ -473,15 +240,15 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ), ) as _i6.SecureStorageInterface); @override - List<_i16.NodeModel> get primaryNodes => (super.noSuchMethod( + List<_i13.NodeModel> get primaryNodes => (super.noSuchMethod( Invocation.getter(#primaryNodes), - returnValue: <_i16.NodeModel>[], - ) as List<_i16.NodeModel>); + returnValue: <_i13.NodeModel>[], + ) as List<_i13.NodeModel>); @override - List<_i16.NodeModel> get nodes => (super.noSuchMethod( + List<_i13.NodeModel> get nodes => (super.noSuchMethod( Invocation.getter(#nodes), - returnValue: <_i16.NodeModel>[], - ) as List<_i16.NodeModel>); + returnValue: <_i13.NodeModel>[], + ) as List<_i13.NodeModel>); @override bool get hasListeners => (super.noSuchMethod( Invocation.getter(#hasListeners), @@ -499,7 +266,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { @override _i10.Future setPrimaryNodeFor({ required _i14.Coin? coin, - required _i16.NodeModel? node, + required _i13.NodeModel? node, bool? shouldNotifyListeners = false, }) => (super.noSuchMethod( @@ -516,40 +283,40 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i16.NodeModel? getPrimaryNodeFor({required _i14.Coin? coin}) => + _i13.NodeModel? getPrimaryNodeFor({required _i14.Coin? coin}) => (super.noSuchMethod(Invocation.method( #getPrimaryNodeFor, [], {#coin: coin}, - )) as _i16.NodeModel?); + )) as _i13.NodeModel?); @override - List<_i16.NodeModel> getNodesFor(_i14.Coin? coin) => (super.noSuchMethod( + List<_i13.NodeModel> getNodesFor(_i14.Coin? coin) => (super.noSuchMethod( Invocation.method( #getNodesFor, [coin], ), - returnValue: <_i16.NodeModel>[], - ) as List<_i16.NodeModel>); + returnValue: <_i13.NodeModel>[], + ) as List<_i13.NodeModel>); @override - _i16.NodeModel? getNodeById({required String? id}) => + _i13.NodeModel? getNodeById({required String? id}) => (super.noSuchMethod(Invocation.method( #getNodeById, [], {#id: id}, - )) as _i16.NodeModel?); + )) as _i13.NodeModel?); @override - List<_i16.NodeModel> failoverNodesFor({required _i14.Coin? coin}) => + List<_i13.NodeModel> failoverNodesFor({required _i14.Coin? coin}) => (super.noSuchMethod( Invocation.method( #failoverNodesFor, [], {#coin: coin}, ), - returnValue: <_i16.NodeModel>[], - ) as List<_i16.NodeModel>); + returnValue: <_i13.NodeModel>[], + ) as List<_i13.NodeModel>); @override _i10.Future add( - _i16.NodeModel? node, + _i13.NodeModel? node, String? password, bool? shouldNotifyListeners, ) => @@ -601,7 +368,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i10.Future); @override _i10.Future edit( - _i16.NodeModel? editedNode, + _i13.NodeModel? editedNode, String? password, bool? shouldNotifyListeners, ) => @@ -663,7 +430,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { /// A class which mocks [LocaleService]. /// /// See the documentation for Mockito's code generation for more information. -class MockLocaleService extends _i1.Mock implements _i17.LocaleService { +class MockLocaleService extends _i1.Mock implements _i16.LocaleService { MockLocaleService() { _i1.throwOnMissingStub(this); } @@ -725,7 +492,7 @@ class MockLocaleService extends _i1.Mock implements _i17.LocaleService { /// A class which mocks [ThemeService]. /// /// See the documentation for Mockito's code generation for more information. -class MockThemeService extends _i1.Mock implements _i18.ThemeService { +class MockThemeService extends _i1.Mock implements _i17.ThemeService { MockThemeService() { _i1.throwOnMissingStub(this); } @@ -755,10 +522,10 @@ class MockThemeService extends _i1.Mock implements _i18.ThemeService { ), ) as _i3.MainDB); @override - List<_i19.StackTheme> get installedThemes => (super.noSuchMethod( + List<_i18.StackTheme> get installedThemes => (super.noSuchMethod( Invocation.getter(#installedThemes), - returnValue: <_i19.StackTheme>[], - ) as List<_i19.StackTheme>); + returnValue: <_i18.StackTheme>[], + ) as List<_i18.StackTheme>); @override void init(_i3.MainDB? db) => super.noSuchMethod( Invocation.method( @@ -768,7 +535,7 @@ class MockThemeService extends _i1.Mock implements _i18.ThemeService { returnValueForMissingStub: null, ); @override - _i10.Future install({required _i20.Uint8List? themeArchiveData}) => + _i10.Future install({required _i19.Uint8List? themeArchiveData}) => (super.noSuchMethod( Invocation.method( #install, @@ -808,33 +575,33 @@ class MockThemeService extends _i1.Mock implements _i18.ThemeService { returnValue: _i10.Future.value(false), ) as _i10.Future); @override - _i10.Future> fetchThemes() => + _i10.Future> fetchThemes() => (super.noSuchMethod( Invocation.method( #fetchThemes, [], ), - returnValue: _i10.Future>.value( - <_i18.StackThemeMetaData>[]), - ) as _i10.Future>); + returnValue: _i10.Future>.value( + <_i17.StackThemeMetaData>[]), + ) as _i10.Future>); @override - _i10.Future<_i20.Uint8List> fetchTheme( - {required _i18.StackThemeMetaData? themeMetaData}) => + _i10.Future<_i19.Uint8List> fetchTheme( + {required _i17.StackThemeMetaData? themeMetaData}) => (super.noSuchMethod( Invocation.method( #fetchTheme, [], {#themeMetaData: themeMetaData}, ), - returnValue: _i10.Future<_i20.Uint8List>.value(_i20.Uint8List(0)), - ) as _i10.Future<_i20.Uint8List>); + returnValue: _i10.Future<_i19.Uint8List>.value(_i19.Uint8List(0)), + ) as _i10.Future<_i19.Uint8List>); @override - _i19.StackTheme? getTheme({required String? themeId}) => + _i18.StackTheme? getTheme({required String? themeId}) => (super.noSuchMethod(Invocation.method( #getTheme, [], {#themeId: themeId}, - )) as _i19.StackTheme?); + )) as _i18.StackTheme?); } /// A class which mocks [Prefs]. @@ -896,12 +663,12 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - _i21.SyncingType get syncType => (super.noSuchMethod( + _i20.SyncingType get syncType => (super.noSuchMethod( Invocation.getter(#syncType), - returnValue: _i21.SyncingType.currentWalletOnly, - ) as _i21.SyncingType); + returnValue: _i20.SyncingType.currentWalletOnly, + ) as _i20.SyncingType); @override - set syncType(_i21.SyncingType? syncType) => super.noSuchMethod( + set syncType(_i20.SyncingType? syncType) => super.noSuchMethod( Invocation.setter( #syncType, syncType, @@ -1060,12 +827,12 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - _i22.BackupFrequencyType get backupFrequencyType => (super.noSuchMethod( + _i21.BackupFrequencyType get backupFrequencyType => (super.noSuchMethod( Invocation.getter(#backupFrequencyType), - returnValue: _i22.BackupFrequencyType.everyTenMinutes, - ) as _i22.BackupFrequencyType); + returnValue: _i21.BackupFrequencyType.everyTenMinutes, + ) as _i21.BackupFrequencyType); @override - set backupFrequencyType(_i22.BackupFrequencyType? backupFrequencyType) => + set backupFrequencyType(_i21.BackupFrequencyType? backupFrequencyType) => super.noSuchMethod( Invocation.setter( #backupFrequencyType, @@ -1260,17 +1027,17 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i23.AmountUnit amountUnit(_i14.Coin? coin) => (super.noSuchMethod( + _i22.AmountUnit amountUnit(_i14.Coin? coin) => (super.noSuchMethod( Invocation.method( #amountUnit, [coin], ), - returnValue: _i23.AmountUnit.normal, - ) as _i23.AmountUnit); + returnValue: _i22.AmountUnit.normal, + ) as _i22.AmountUnit); @override void updateAmountUnit({ required _i14.Coin? coin, - required _i23.AmountUnit? amountUnit, + required _i22.AmountUnit? amountUnit, }) => super.noSuchMethod( Invocation.method( diff --git a/test/widget_tests/managed_favorite_test.dart b/test/widget_tests/managed_favorite_test.dart index 3db3f458f..0d60b87c9 100644 --- a/test/widget_tests/managed_favorite_test.dart +++ b/test/widget_tests/managed_favorite_test.dart @@ -3,7 +3,6 @@ import 'package:mockito/annotations.dart'; import 'package:stackwallet/services/locale_service.dart'; import 'package:stackwallet/services/node_service.dart'; import 'package:stackwallet/services/wallets.dart'; -import 'package:stackwallet/services/wallets_service.dart'; import 'package:stackwallet/themes/theme_service.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/prefs.dart'; @@ -17,7 +16,6 @@ Amount _a(int i) => Amount.fromDecimal( @GenerateMocks([ Wallets, - WalletsService, ThemeService, Prefs, LocaleService diff --git a/test/widget_tests/managed_favorite_test.mocks.dart b/test/widget_tests/managed_favorite_test.mocks.dart index 46d50b6b4..e78909a96 100644 --- a/test/widget_tests/managed_favorite_test.mocks.dart +++ b/test/widget_tests/managed_favorite_test.mocks.dart @@ -4,23 +4,22 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i10; -import 'dart:typed_data' as _i18; -import 'dart:ui' as _i15; +import 'dart:typed_data' as _i15; +import 'dart:ui' as _i20; import 'package:mockito/mockito.dart' as _i1; import 'package:stackwallet/db/isar/main_db.dart' as _i3; -import 'package:stackwallet/models/isar/stack_theme.dart' as _i17; -import 'package:stackwallet/models/node_model.dart' as _i23; +import 'package:stackwallet/models/isar/stack_theme.dart' as _i14; +import 'package:stackwallet/models/node_model.dart' as _i22; import 'package:stackwallet/networking/http.dart' as _i6; -import 'package:stackwallet/services/locale_service.dart' as _i22; +import 'package:stackwallet/services/locale_service.dart' as _i21; import 'package:stackwallet/services/node_service.dart' as _i2; import 'package:stackwallet/services/wallets.dart' as _i9; -import 'package:stackwallet/services/wallets_service.dart' as _i13; -import 'package:stackwallet/themes/theme_service.dart' as _i16; -import 'package:stackwallet/utilities/amount/amount_unit.dart' as _i21; -import 'package:stackwallet/utilities/enums/backup_frequency_type.dart' as _i20; -import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i14; -import 'package:stackwallet/utilities/enums/sync_type_enum.dart' as _i19; +import 'package:stackwallet/themes/theme_service.dart' as _i13; +import 'package:stackwallet/utilities/amount/amount_unit.dart' as _i18; +import 'package:stackwallet/utilities/enums/backup_frequency_type.dart' as _i17; +import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i19; +import 'package:stackwallet/utilities/enums/sync_type_enum.dart' as _i16; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart' as _i8; import 'package:stackwallet/utilities/prefs.dart' as _i12; @@ -208,6 +207,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { _i10.Future loadAfterStackRestore( _i12.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -215,6 +215,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i10.Future.value(), @@ -222,244 +223,10 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { ) as _i10.Future); } -/// A class which mocks [WalletsService]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockWalletsService extends _i1.Mock implements _i13.WalletsService { - MockWalletsService() { - _i1.throwOnMissingStub(this); - } - - @override - _i10.Future> get walletNames => - (super.noSuchMethod( - Invocation.getter(#walletNames), - returnValue: _i10.Future>.value( - {}), - ) as _i10.Future>); - @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); - @override - _i10.Future renameWallet({ - required String? from, - required String? to, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #renameWallet, - [], - { - #from: from, - #to: to, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - Map fetchWalletsData() => (super.noSuchMethod( - Invocation.method( - #fetchWalletsData, - [], - ), - returnValue: {}, - ) as Map); - @override - _i10.Future addExistingStackWallet({ - required String? name, - required String? walletId, - required _i14.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addExistingStackWallet, - [], - { - #name: name, - #walletId: walletId, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future addNewWallet({ - required String? name, - required _i14.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addNewWallet, - [], - { - #name: name, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future> getFavoriteWalletIds() => (super.noSuchMethod( - Invocation.method( - #getFavoriteWalletIds, - [], - ), - returnValue: _i10.Future>.value([]), - ) as _i10.Future>); - @override - _i10.Future saveFavoriteWalletIds(List? walletIds) => - (super.noSuchMethod( - Invocation.method( - #saveFavoriteWalletIds, - [walletIds], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future addFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #addFavorite, - [walletId], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future removeFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #removeFavorite, - [walletId], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future moveFavorite({ - required int? fromIndex, - required int? toIndex, - }) => - (super.noSuchMethod( - Invocation.method( - #moveFavorite, - [], - { - #fromIndex: fromIndex, - #toIndex: toIndex, - }, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future checkForDuplicate(String? name) => (super.noSuchMethod( - Invocation.method( - #checkForDuplicate, - [name], - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - _i10.Future getWalletId(String? walletName) => (super.noSuchMethod( - Invocation.method( - #getWalletId, - [walletName], - ), - returnValue: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future isMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #isMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i10.Future.value(false), - ) as _i10.Future); - @override - _i10.Future setMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #setMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - _i10.Future deleteWallet( - String? name, - bool? shouldNotifyListeners, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteWallet, - [ - name, - shouldNotifyListeners, - ], - ), - returnValue: _i10.Future.value(0), - ) as _i10.Future); - @override - _i10.Future refreshWallets(bool? shouldNotifyListeners) => - (super.noSuchMethod( - Invocation.method( - #refreshWallets, - [shouldNotifyListeners], - ), - returnValue: _i10.Future.value(), - returnValueForMissingStub: _i10.Future.value(), - ) as _i10.Future); - @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValueForMissingStub: null, - ); - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [ThemeService]. /// /// See the documentation for Mockito's code generation for more information. -class MockThemeService extends _i1.Mock implements _i16.ThemeService { +class MockThemeService extends _i1.Mock implements _i13.ThemeService { MockThemeService() { _i1.throwOnMissingStub(this); } @@ -489,10 +256,10 @@ class MockThemeService extends _i1.Mock implements _i16.ThemeService { ), ) as _i3.MainDB); @override - List<_i17.StackTheme> get installedThemes => (super.noSuchMethod( + List<_i14.StackTheme> get installedThemes => (super.noSuchMethod( Invocation.getter(#installedThemes), - returnValue: <_i17.StackTheme>[], - ) as List<_i17.StackTheme>); + returnValue: <_i14.StackTheme>[], + ) as List<_i14.StackTheme>); @override void init(_i3.MainDB? db) => super.noSuchMethod( Invocation.method( @@ -502,7 +269,7 @@ class MockThemeService extends _i1.Mock implements _i16.ThemeService { returnValueForMissingStub: null, ); @override - _i10.Future install({required _i18.Uint8List? themeArchiveData}) => + _i10.Future install({required _i15.Uint8List? themeArchiveData}) => (super.noSuchMethod( Invocation.method( #install, @@ -542,33 +309,33 @@ class MockThemeService extends _i1.Mock implements _i16.ThemeService { returnValue: _i10.Future.value(false), ) as _i10.Future); @override - _i10.Future> fetchThemes() => + _i10.Future> fetchThemes() => (super.noSuchMethod( Invocation.method( #fetchThemes, [], ), - returnValue: _i10.Future>.value( - <_i16.StackThemeMetaData>[]), - ) as _i10.Future>); + returnValue: _i10.Future>.value( + <_i13.StackThemeMetaData>[]), + ) as _i10.Future>); @override - _i10.Future<_i18.Uint8List> fetchTheme( - {required _i16.StackThemeMetaData? themeMetaData}) => + _i10.Future<_i15.Uint8List> fetchTheme( + {required _i13.StackThemeMetaData? themeMetaData}) => (super.noSuchMethod( Invocation.method( #fetchTheme, [], {#themeMetaData: themeMetaData}, ), - returnValue: _i10.Future<_i18.Uint8List>.value(_i18.Uint8List(0)), - ) as _i10.Future<_i18.Uint8List>); + returnValue: _i10.Future<_i15.Uint8List>.value(_i15.Uint8List(0)), + ) as _i10.Future<_i15.Uint8List>); @override - _i17.StackTheme? getTheme({required String? themeId}) => + _i14.StackTheme? getTheme({required String? themeId}) => (super.noSuchMethod(Invocation.method( #getTheme, [], {#themeId: themeId}, - )) as _i17.StackTheme?); + )) as _i14.StackTheme?); } /// A class which mocks [Prefs]. @@ -630,12 +397,12 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - _i19.SyncingType get syncType => (super.noSuchMethod( + _i16.SyncingType get syncType => (super.noSuchMethod( Invocation.getter(#syncType), - returnValue: _i19.SyncingType.currentWalletOnly, - ) as _i19.SyncingType); + returnValue: _i16.SyncingType.currentWalletOnly, + ) as _i16.SyncingType); @override - set syncType(_i19.SyncingType? syncType) => super.noSuchMethod( + set syncType(_i16.SyncingType? syncType) => super.noSuchMethod( Invocation.setter( #syncType, syncType, @@ -794,12 +561,12 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - _i20.BackupFrequencyType get backupFrequencyType => (super.noSuchMethod( + _i17.BackupFrequencyType get backupFrequencyType => (super.noSuchMethod( Invocation.getter(#backupFrequencyType), - returnValue: _i20.BackupFrequencyType.everyTenMinutes, - ) as _i20.BackupFrequencyType); + returnValue: _i17.BackupFrequencyType.everyTenMinutes, + ) as _i17.BackupFrequencyType); @override - set backupFrequencyType(_i20.BackupFrequencyType? backupFrequencyType) => + set backupFrequencyType(_i17.BackupFrequencyType? backupFrequencyType) => super.noSuchMethod( Invocation.setter( #backupFrequencyType, @@ -994,17 +761,17 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i21.AmountUnit amountUnit(_i14.Coin? coin) => (super.noSuchMethod( + _i18.AmountUnit amountUnit(_i19.Coin? coin) => (super.noSuchMethod( Invocation.method( #amountUnit, [coin], ), - returnValue: _i21.AmountUnit.normal, - ) as _i21.AmountUnit); + returnValue: _i18.AmountUnit.normal, + ) as _i18.AmountUnit); @override void updateAmountUnit({ - required _i14.Coin? coin, - required _i21.AmountUnit? amountUnit, + required _i19.Coin? coin, + required _i18.AmountUnit? amountUnit, }) => super.noSuchMethod( Invocation.method( @@ -1018,7 +785,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - int maxDecimals(_i14.Coin? coin) => (super.noSuchMethod( + int maxDecimals(_i19.Coin? coin) => (super.noSuchMethod( Invocation.method( #maxDecimals, [coin], @@ -1027,7 +794,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { ) as int); @override void updateMaxDecimals({ - required _i14.Coin? coin, + required _i19.Coin? coin, required int? maxDecimals, }) => super.noSuchMethod( @@ -1042,7 +809,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - _i7.FusionInfo getFusionServerInfo(_i14.Coin? coin) => (super.noSuchMethod( + _i7.FusionInfo getFusionServerInfo(_i19.Coin? coin) => (super.noSuchMethod( Invocation.method( #getFusionServerInfo, [coin], @@ -1057,7 +824,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { ) as _i7.FusionInfo); @override void setFusionServerInfo( - _i14.Coin? coin, + _i19.Coin? coin, _i7.FusionInfo? fusionServerInfo, ) => super.noSuchMethod( @@ -1071,7 +838,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void addListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #addListener, [listener], @@ -1079,7 +846,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { returnValueForMissingStub: null, ); @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void removeListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #removeListener, [listener], @@ -1107,7 +874,7 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs { /// A class which mocks [LocaleService]. /// /// See the documentation for Mockito's code generation for more information. -class MockLocaleService extends _i1.Mock implements _i22.LocaleService { +class MockLocaleService extends _i1.Mock implements _i21.LocaleService { MockLocaleService() { _i1.throwOnMissingStub(this); } @@ -1133,7 +900,7 @@ class MockLocaleService extends _i1.Mock implements _i22.LocaleService { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void addListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #addListener, [listener], @@ -1141,7 +908,7 @@ class MockLocaleService extends _i1.Mock implements _i22.LocaleService { returnValueForMissingStub: null, ); @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void removeListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #removeListener, [listener], @@ -1179,15 +946,15 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ), ) as _i8.SecureStorageInterface); @override - List<_i23.NodeModel> get primaryNodes => (super.noSuchMethod( + List<_i22.NodeModel> get primaryNodes => (super.noSuchMethod( Invocation.getter(#primaryNodes), - returnValue: <_i23.NodeModel>[], - ) as List<_i23.NodeModel>); + returnValue: <_i22.NodeModel>[], + ) as List<_i22.NodeModel>); @override - List<_i23.NodeModel> get nodes => (super.noSuchMethod( + List<_i22.NodeModel> get nodes => (super.noSuchMethod( Invocation.getter(#nodes), - returnValue: <_i23.NodeModel>[], - ) as List<_i23.NodeModel>); + returnValue: <_i22.NodeModel>[], + ) as List<_i22.NodeModel>); @override bool get hasListeners => (super.noSuchMethod( Invocation.getter(#hasListeners), @@ -1204,8 +971,8 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i10.Future); @override _i10.Future setPrimaryNodeFor({ - required _i14.Coin? coin, - required _i23.NodeModel? node, + required _i19.Coin? coin, + required _i22.NodeModel? node, bool? shouldNotifyListeners = false, }) => (super.noSuchMethod( @@ -1222,40 +989,40 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i23.NodeModel? getPrimaryNodeFor({required _i14.Coin? coin}) => + _i22.NodeModel? getPrimaryNodeFor({required _i19.Coin? coin}) => (super.noSuchMethod(Invocation.method( #getPrimaryNodeFor, [], {#coin: coin}, - )) as _i23.NodeModel?); + )) as _i22.NodeModel?); @override - List<_i23.NodeModel> getNodesFor(_i14.Coin? coin) => (super.noSuchMethod( + List<_i22.NodeModel> getNodesFor(_i19.Coin? coin) => (super.noSuchMethod( Invocation.method( #getNodesFor, [coin], ), - returnValue: <_i23.NodeModel>[], - ) as List<_i23.NodeModel>); + returnValue: <_i22.NodeModel>[], + ) as List<_i22.NodeModel>); @override - _i23.NodeModel? getNodeById({required String? id}) => + _i22.NodeModel? getNodeById({required String? id}) => (super.noSuchMethod(Invocation.method( #getNodeById, [], {#id: id}, - )) as _i23.NodeModel?); + )) as _i22.NodeModel?); @override - List<_i23.NodeModel> failoverNodesFor({required _i14.Coin? coin}) => + List<_i22.NodeModel> failoverNodesFor({required _i19.Coin? coin}) => (super.noSuchMethod( Invocation.method( #failoverNodesFor, [], {#coin: coin}, ), - returnValue: <_i23.NodeModel>[], - ) as List<_i23.NodeModel>); + returnValue: <_i22.NodeModel>[], + ) as List<_i22.NodeModel>); @override _i10.Future add( - _i23.NodeModel? node, + _i22.NodeModel? node, String? password, bool? shouldNotifyListeners, ) => @@ -1307,7 +1074,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i10.Future); @override _i10.Future edit( - _i23.NodeModel? editedNode, + _i22.NodeModel? editedNode, String? password, bool? shouldNotifyListeners, ) => @@ -1333,7 +1100,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - void addListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void addListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #addListener, [listener], @@ -1341,7 +1108,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: null, ); @override - void removeListener(_i15.VoidCallback? listener) => super.noSuchMethod( + void removeListener(_i20.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #removeListener, [listener], diff --git a/test/widget_tests/node_options_sheet_test.mocks.dart b/test/widget_tests/node_options_sheet_test.mocks.dart index 0fe34c285..3d0a10b68 100644 --- a/test/widget_tests/node_options_sheet_test.mocks.dart +++ b/test/widget_tests/node_options_sheet_test.mocks.dart @@ -208,6 +208,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { _i10.Future loadAfterStackRestore( _i12.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -215,6 +216,7 @@ class MockWallets extends _i1.Mock implements _i9.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i10.Future.value(), diff --git a/test/widget_tests/table_view/table_view_row_test.dart b/test/widget_tests/table_view/table_view_row_test.dart index 70c36b8aa..4ec1f435d 100644 --- a/test/widget_tests/table_view/table_view_row_test.dart +++ b/test/widget_tests/table_view/table_view_row_test.dart @@ -1,11 +1,9 @@ import 'package:mockito/annotations.dart'; import 'package:stackwallet/services/wallets.dart'; -import 'package:stackwallet/services/wallets_service.dart'; import 'package:stackwallet/themes/theme_service.dart'; @GenerateMocks([ Wallets, - WalletsService, ThemeService, ], customMocks: []) void main() { diff --git a/test/widget_tests/table_view/table_view_row_test.mocks.dart b/test/widget_tests/table_view/table_view_row_test.mocks.dart index 25720f6ed..9880d1e22 100644 --- a/test/widget_tests/table_view/table_view_row_test.mocks.dart +++ b/test/widget_tests/table_view/table_view_row_test.mocks.dart @@ -4,18 +4,15 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i8; -import 'dart:typed_data' as _i17; -import 'dart:ui' as _i14; +import 'dart:typed_data' as _i14; import 'package:mockito/mockito.dart' as _i1; import 'package:stackwallet/db/isar/main_db.dart' as _i3; -import 'package:stackwallet/models/isar/stack_theme.dart' as _i16; +import 'package:stackwallet/models/isar/stack_theme.dart' as _i13; import 'package:stackwallet/networking/http.dart' as _i6; import 'package:stackwallet/services/node_service.dart' as _i2; import 'package:stackwallet/services/wallets.dart' as _i7; -import 'package:stackwallet/services/wallets_service.dart' as _i12; -import 'package:stackwallet/themes/theme_service.dart' as _i15; -import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i13; +import 'package:stackwallet/themes/theme_service.dart' as _i12; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart' as _i10; import 'package:stackwallet/utilities/prefs.dart' as _i11; @@ -180,6 +177,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { _i8.Future loadAfterStackRestore( _i11.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -187,6 +185,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i8.Future.value(), @@ -194,244 +193,10 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { ) as _i8.Future); } -/// A class which mocks [WalletsService]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockWalletsService extends _i1.Mock implements _i12.WalletsService { - MockWalletsService() { - _i1.throwOnMissingStub(this); - } - - @override - _i8.Future> get walletNames => - (super.noSuchMethod( - Invocation.getter(#walletNames), - returnValue: _i8.Future>.value( - {}), - ) as _i8.Future>); - @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); - @override - _i8.Future renameWallet({ - required String? from, - required String? to, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #renameWallet, - [], - { - #from: from, - #to: to, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - Map fetchWalletsData() => (super.noSuchMethod( - Invocation.method( - #fetchWalletsData, - [], - ), - returnValue: {}, - ) as Map); - @override - _i8.Future addExistingStackWallet({ - required String? name, - required String? walletId, - required _i13.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addExistingStackWallet, - [], - { - #name: name, - #walletId: walletId, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future addNewWallet({ - required String? name, - required _i13.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addNewWallet, - [], - { - #name: name, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future> getFavoriteWalletIds() => (super.noSuchMethod( - Invocation.method( - #getFavoriteWalletIds, - [], - ), - returnValue: _i8.Future>.value([]), - ) as _i8.Future>); - @override - _i8.Future saveFavoriteWalletIds(List? walletIds) => - (super.noSuchMethod( - Invocation.method( - #saveFavoriteWalletIds, - [walletIds], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future addFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #addFavorite, - [walletId], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future removeFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #removeFavorite, - [walletId], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future moveFavorite({ - required int? fromIndex, - required int? toIndex, - }) => - (super.noSuchMethod( - Invocation.method( - #moveFavorite, - [], - { - #fromIndex: fromIndex, - #toIndex: toIndex, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future checkForDuplicate(String? name) => (super.noSuchMethod( - Invocation.method( - #checkForDuplicate, - [name], - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - _i8.Future getWalletId(String? walletName) => (super.noSuchMethod( - Invocation.method( - #getWalletId, - [walletName], - ), - returnValue: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future isMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #isMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - _i8.Future setMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #setMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future deleteWallet( - String? name, - bool? shouldNotifyListeners, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteWallet, - [ - name, - shouldNotifyListeners, - ], - ), - returnValue: _i8.Future.value(0), - ) as _i8.Future); - @override - _i8.Future refreshWallets(bool? shouldNotifyListeners) => - (super.noSuchMethod( - Invocation.method( - #refreshWallets, - [shouldNotifyListeners], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValueForMissingStub: null, - ); - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [ThemeService]. /// /// See the documentation for Mockito's code generation for more information. -class MockThemeService extends _i1.Mock implements _i15.ThemeService { +class MockThemeService extends _i1.Mock implements _i12.ThemeService { MockThemeService() { _i1.throwOnMissingStub(this); } @@ -461,10 +226,10 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { ), ) as _i3.MainDB); @override - List<_i16.StackTheme> get installedThemes => (super.noSuchMethod( + List<_i13.StackTheme> get installedThemes => (super.noSuchMethod( Invocation.getter(#installedThemes), - returnValue: <_i16.StackTheme>[], - ) as List<_i16.StackTheme>); + returnValue: <_i13.StackTheme>[], + ) as List<_i13.StackTheme>); @override void init(_i3.MainDB? db) => super.noSuchMethod( Invocation.method( @@ -474,7 +239,7 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { returnValueForMissingStub: null, ); @override - _i8.Future install({required _i17.Uint8List? themeArchiveData}) => + _i8.Future install({required _i14.Uint8List? themeArchiveData}) => (super.noSuchMethod( Invocation.method( #install, @@ -514,31 +279,31 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { returnValue: _i8.Future.value(false), ) as _i8.Future); @override - _i8.Future> fetchThemes() => + _i8.Future> fetchThemes() => (super.noSuchMethod( Invocation.method( #fetchThemes, [], ), - returnValue: _i8.Future>.value( - <_i15.StackThemeMetaData>[]), - ) as _i8.Future>); + returnValue: _i8.Future>.value( + <_i12.StackThemeMetaData>[]), + ) as _i8.Future>); @override - _i8.Future<_i17.Uint8List> fetchTheme( - {required _i15.StackThemeMetaData? themeMetaData}) => + _i8.Future<_i14.Uint8List> fetchTheme( + {required _i12.StackThemeMetaData? themeMetaData}) => (super.noSuchMethod( Invocation.method( #fetchTheme, [], {#themeMetaData: themeMetaData}, ), - returnValue: _i8.Future<_i17.Uint8List>.value(_i17.Uint8List(0)), - ) as _i8.Future<_i17.Uint8List>); + returnValue: _i8.Future<_i14.Uint8List>.value(_i14.Uint8List(0)), + ) as _i8.Future<_i14.Uint8List>); @override - _i16.StackTheme? getTheme({required String? themeId}) => + _i13.StackTheme? getTheme({required String? themeId}) => (super.noSuchMethod(Invocation.method( #getTheme, [], {#themeId: themeId}, - )) as _i16.StackTheme?); + )) as _i13.StackTheme?); } diff --git a/test/widget_tests/transaction_card_test.mocks.dart b/test/widget_tests/transaction_card_test.mocks.dart index 1b593ed24..e3880f1b6 100644 --- a/test/widget_tests/transaction_card_test.mocks.dart +++ b/test/widget_tests/transaction_card_test.mocks.dart @@ -246,6 +246,7 @@ class MockWallets extends _i1.Mock implements _i10.Wallets { _i11.Future loadAfterStackRestore( _i14.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -253,6 +254,7 @@ class MockWallets extends _i1.Mock implements _i10.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i11.Future.value(), @@ -877,11 +879,6 @@ class MockPriceService extends _i1.Mock implements _i21.PriceService { returnValueForMissingStub: null, ); @override - Set get tokenContractAddressesToCheck => (super.noSuchMethod( - Invocation.getter(#tokenContractAddressesToCheck), - returnValue: {}, - ) as Set); - @override Duration get updateInterval => (super.noSuchMethod( Invocation.getter(#updateInterval), returnValue: _FakeDuration_4( @@ -890,6 +887,12 @@ class MockPriceService extends _i1.Mock implements _i21.PriceService { ), ) as Duration); @override + _i11.Future> get tokenContractAddressesToCheck => + (super.noSuchMethod( + Invocation.getter(#tokenContractAddressesToCheck), + returnValue: _i11.Future>.value({}), + ) as _i11.Future>); + @override bool get hasListeners => (super.noSuchMethod( Invocation.getter(#hasListeners), returnValue: false, diff --git a/test/widget_tests/wallet_card_test.mocks.dart b/test/widget_tests/wallet_card_test.mocks.dart index f90cfb8a2..d984f4aef 100644 --- a/test/widget_tests/wallet_card_test.mocks.dart +++ b/test/widget_tests/wallet_card_test.mocks.dart @@ -179,6 +179,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { _i8.Future loadAfterStackRestore( _i11.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -186,6 +187,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i8.Future.value(), diff --git a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart index f93a56568..a3161a73e 100644 --- a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart +++ b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart @@ -1,11 +1,9 @@ import 'package:mockito/annotations.dart'; import 'package:stackwallet/services/node_service.dart'; import 'package:stackwallet/services/wallets.dart'; -import 'package:stackwallet/services/wallets_service.dart'; @GenerateMocks([ Wallets, - WalletsService, ], customMocks: [ MockSpec(returnNullOnMissingStub: true), // MockSpec(returnNullOnMissingStub: true), diff --git a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.mocks.dart b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.mocks.dart index 36f9688f8..e02c41ec5 100644 --- a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.mocks.dart +++ b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.mocks.dart @@ -8,10 +8,9 @@ import 'dart:ui' as _i13; import 'package:mockito/mockito.dart' as _i1; import 'package:stackwallet/db/isar/main_db.dart' as _i3; -import 'package:stackwallet/models/node_model.dart' as _i14; +import 'package:stackwallet/models/node_model.dart' as _i11; import 'package:stackwallet/services/node_service.dart' as _i2; import 'package:stackwallet/services/wallets.dart' as _i7; -import 'package:stackwallet/services/wallets_service.dart' as _i11; import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i12; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart' as _i6; @@ -178,6 +177,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { _i8.Future loadAfterStackRestore( _i10.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -185,6 +185,7 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i8.Future.value(), @@ -192,240 +193,6 @@ class MockWallets extends _i1.Mock implements _i7.Wallets { ) as _i8.Future); } -/// A class which mocks [WalletsService]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockWalletsService extends _i1.Mock implements _i11.WalletsService { - MockWalletsService() { - _i1.throwOnMissingStub(this); - } - - @override - _i8.Future> get walletNames => - (super.noSuchMethod( - Invocation.getter(#walletNames), - returnValue: _i8.Future>.value( - {}), - ) as _i8.Future>); - @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); - @override - _i8.Future renameWallet({ - required String? from, - required String? to, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #renameWallet, - [], - { - #from: from, - #to: to, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - Map fetchWalletsData() => (super.noSuchMethod( - Invocation.method( - #fetchWalletsData, - [], - ), - returnValue: {}, - ) as Map); - @override - _i8.Future addExistingStackWallet({ - required String? name, - required String? walletId, - required _i12.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addExistingStackWallet, - [], - { - #name: name, - #walletId: walletId, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future addNewWallet({ - required String? name, - required _i12.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addNewWallet, - [], - { - #name: name, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future> getFavoriteWalletIds() => (super.noSuchMethod( - Invocation.method( - #getFavoriteWalletIds, - [], - ), - returnValue: _i8.Future>.value([]), - ) as _i8.Future>); - @override - _i8.Future saveFavoriteWalletIds(List? walletIds) => - (super.noSuchMethod( - Invocation.method( - #saveFavoriteWalletIds, - [walletIds], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future addFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #addFavorite, - [walletId], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future removeFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #removeFavorite, - [walletId], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future moveFavorite({ - required int? fromIndex, - required int? toIndex, - }) => - (super.noSuchMethod( - Invocation.method( - #moveFavorite, - [], - { - #fromIndex: fromIndex, - #toIndex: toIndex, - }, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future checkForDuplicate(String? name) => (super.noSuchMethod( - Invocation.method( - #checkForDuplicate, - [name], - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - _i8.Future getWalletId(String? walletName) => (super.noSuchMethod( - Invocation.method( - #getWalletId, - [walletName], - ), - returnValue: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future isMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #isMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i8.Future.value(false), - ) as _i8.Future); - @override - _i8.Future setMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #setMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - _i8.Future deleteWallet( - String? name, - bool? shouldNotifyListeners, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteWallet, - [ - name, - shouldNotifyListeners, - ], - ), - returnValue: _i8.Future.value(0), - ) as _i8.Future); - @override - _i8.Future refreshWallets(bool? shouldNotifyListeners) => - (super.noSuchMethod( - Invocation.method( - #refreshWallets, - [shouldNotifyListeners], - ), - returnValue: _i8.Future.value(), - returnValueForMissingStub: _i8.Future.value(), - ) as _i8.Future); - @override - void addListener(_i13.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void removeListener(_i13.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValueForMissingStub: null, - ); - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [NodeService]. /// /// See the documentation for Mockito's code generation for more information. @@ -439,15 +206,15 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ), ) as _i6.SecureStorageInterface); @override - List<_i14.NodeModel> get primaryNodes => (super.noSuchMethod( + List<_i11.NodeModel> get primaryNodes => (super.noSuchMethod( Invocation.getter(#primaryNodes), - returnValue: <_i14.NodeModel>[], - ) as List<_i14.NodeModel>); + returnValue: <_i11.NodeModel>[], + ) as List<_i11.NodeModel>); @override - List<_i14.NodeModel> get nodes => (super.noSuchMethod( + List<_i11.NodeModel> get nodes => (super.noSuchMethod( Invocation.getter(#nodes), - returnValue: <_i14.NodeModel>[], - ) as List<_i14.NodeModel>); + returnValue: <_i11.NodeModel>[], + ) as List<_i11.NodeModel>); @override bool get hasListeners => (super.noSuchMethod( Invocation.getter(#hasListeners), @@ -465,7 +232,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { @override _i8.Future setPrimaryNodeFor({ required _i12.Coin? coin, - required _i14.NodeModel? node, + required _i11.NodeModel? node, bool? shouldNotifyListeners = false, }) => (super.noSuchMethod( @@ -482,40 +249,40 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i14.NodeModel? getPrimaryNodeFor({required _i12.Coin? coin}) => + _i11.NodeModel? getPrimaryNodeFor({required _i12.Coin? coin}) => (super.noSuchMethod(Invocation.method( #getPrimaryNodeFor, [], {#coin: coin}, - )) as _i14.NodeModel?); + )) as _i11.NodeModel?); @override - List<_i14.NodeModel> getNodesFor(_i12.Coin? coin) => (super.noSuchMethod( + List<_i11.NodeModel> getNodesFor(_i12.Coin? coin) => (super.noSuchMethod( Invocation.method( #getNodesFor, [coin], ), - returnValue: <_i14.NodeModel>[], - ) as List<_i14.NodeModel>); + returnValue: <_i11.NodeModel>[], + ) as List<_i11.NodeModel>); @override - _i14.NodeModel? getNodeById({required String? id}) => + _i11.NodeModel? getNodeById({required String? id}) => (super.noSuchMethod(Invocation.method( #getNodeById, [], {#id: id}, - )) as _i14.NodeModel?); + )) as _i11.NodeModel?); @override - List<_i14.NodeModel> failoverNodesFor({required _i12.Coin? coin}) => + List<_i11.NodeModel> failoverNodesFor({required _i12.Coin? coin}) => (super.noSuchMethod( Invocation.method( #failoverNodesFor, [], {#coin: coin}, ), - returnValue: <_i14.NodeModel>[], - ) as List<_i14.NodeModel>); + returnValue: <_i11.NodeModel>[], + ) as List<_i11.NodeModel>); @override _i8.Future add( - _i14.NodeModel? node, + _i11.NodeModel? node, String? password, bool? shouldNotifyListeners, ) => @@ -567,7 +334,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i8.Future); @override _i8.Future edit( - _i14.NodeModel? editedNode, + _i11.NodeModel? editedNode, String? password, bool? shouldNotifyListeners, ) => diff --git a/test/widget_tests/wallet_info_row/wallet_info_row_test.dart b/test/widget_tests/wallet_info_row/wallet_info_row_test.dart index 7038a5f6e..d4f97e600 100644 --- a/test/widget_tests/wallet_info_row/wallet_info_row_test.dart +++ b/test/widget_tests/wallet_info_row/wallet_info_row_test.dart @@ -6,7 +6,6 @@ import 'package:stackwallet/themes/theme_service.dart'; @GenerateMocks([ Wallets, - WalletsService, ThemeService, ], customMocks: [ MockSpec(returnNullOnMissingStub: true), diff --git a/test/widget_tests/wallet_info_row/wallet_info_row_test.mocks.dart b/test/widget_tests/wallet_info_row/wallet_info_row_test.mocks.dart index c6e839a02..eec63a4fd 100644 --- a/test/widget_tests/wallet_info_row/wallet_info_row_test.mocks.dart +++ b/test/widget_tests/wallet_info_row/wallet_info_row_test.mocks.dart @@ -4,19 +4,18 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i9; -import 'dart:typed_data' as _i17; -import 'dart:ui' as _i14; +import 'dart:typed_data' as _i14; +import 'dart:ui' as _i17; import 'package:mockito/mockito.dart' as _i1; import 'package:stackwallet/db/isar/main_db.dart' as _i3; -import 'package:stackwallet/models/isar/stack_theme.dart' as _i16; -import 'package:stackwallet/models/node_model.dart' as _i18; +import 'package:stackwallet/models/isar/stack_theme.dart' as _i13; +import 'package:stackwallet/models/node_model.dart' as _i15; import 'package:stackwallet/networking/http.dart' as _i6; import 'package:stackwallet/services/node_service.dart' as _i2; import 'package:stackwallet/services/wallets.dart' as _i8; -import 'package:stackwallet/services/wallets_service.dart' as _i12; -import 'package:stackwallet/themes/theme_service.dart' as _i15; -import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i13; +import 'package:stackwallet/themes/theme_service.dart' as _i12; +import 'package:stackwallet/utilities/enums/coin_enum.dart' as _i16; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart' as _i7; import 'package:stackwallet/utilities/prefs.dart' as _i11; @@ -192,6 +191,7 @@ class MockWallets extends _i1.Mock implements _i8.Wallets { _i9.Future loadAfterStackRestore( _i11.Prefs? prefs, List<_i5.Wallet<_i4.CryptoCurrency>>? wallets, + bool? isDesktop, ) => (super.noSuchMethod( Invocation.method( @@ -199,6 +199,7 @@ class MockWallets extends _i1.Mock implements _i8.Wallets { [ prefs, wallets, + isDesktop, ], ), returnValue: _i9.Future.value(), @@ -206,244 +207,10 @@ class MockWallets extends _i1.Mock implements _i8.Wallets { ) as _i9.Future); } -/// A class which mocks [WalletsService]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockWalletsService extends _i1.Mock implements _i12.WalletsService { - MockWalletsService() { - _i1.throwOnMissingStub(this); - } - - @override - _i9.Future> get walletNames => - (super.noSuchMethod( - Invocation.getter(#walletNames), - returnValue: _i9.Future>.value( - {}), - ) as _i9.Future>); - @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); - @override - _i9.Future renameWallet({ - required String? from, - required String? to, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #renameWallet, - [], - { - #from: from, - #to: to, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i9.Future.value(false), - ) as _i9.Future); - @override - Map fetchWalletsData() => (super.noSuchMethod( - Invocation.method( - #fetchWalletsData, - [], - ), - returnValue: {}, - ) as Map); - @override - _i9.Future addExistingStackWallet({ - required String? name, - required String? walletId, - required _i13.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addExistingStackWallet, - [], - { - #name: name, - #walletId: walletId, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future addNewWallet({ - required String? name, - required _i13.Coin? coin, - required bool? shouldNotifyListeners, - }) => - (super.noSuchMethod( - Invocation.method( - #addNewWallet, - [], - { - #name: name, - #coin: coin, - #shouldNotifyListeners: shouldNotifyListeners, - }, - ), - returnValue: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future> getFavoriteWalletIds() => (super.noSuchMethod( - Invocation.method( - #getFavoriteWalletIds, - [], - ), - returnValue: _i9.Future>.value([]), - ) as _i9.Future>); - @override - _i9.Future saveFavoriteWalletIds(List? walletIds) => - (super.noSuchMethod( - Invocation.method( - #saveFavoriteWalletIds, - [walletIds], - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future addFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #addFavorite, - [walletId], - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future removeFavorite(String? walletId) => (super.noSuchMethod( - Invocation.method( - #removeFavorite, - [walletId], - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future moveFavorite({ - required int? fromIndex, - required int? toIndex, - }) => - (super.noSuchMethod( - Invocation.method( - #moveFavorite, - [], - { - #fromIndex: fromIndex, - #toIndex: toIndex, - }, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future checkForDuplicate(String? name) => (super.noSuchMethod( - Invocation.method( - #checkForDuplicate, - [name], - ), - returnValue: _i9.Future.value(false), - ) as _i9.Future); - @override - _i9.Future getWalletId(String? walletName) => (super.noSuchMethod( - Invocation.method( - #getWalletId, - [walletName], - ), - returnValue: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future isMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #isMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i9.Future.value(false), - ) as _i9.Future); - @override - _i9.Future setMnemonicVerified({required String? walletId}) => - (super.noSuchMethod( - Invocation.method( - #setMnemonicVerified, - [], - {#walletId: walletId}, - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - _i9.Future deleteWallet( - String? name, - bool? shouldNotifyListeners, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteWallet, - [ - name, - shouldNotifyListeners, - ], - ), - returnValue: _i9.Future.value(0), - ) as _i9.Future); - @override - _i9.Future refreshWallets(bool? shouldNotifyListeners) => - (super.noSuchMethod( - Invocation.method( - #refreshWallets, - [shouldNotifyListeners], - ), - returnValue: _i9.Future.value(), - returnValueForMissingStub: _i9.Future.value(), - ) as _i9.Future); - @override - void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), - returnValueForMissingStub: null, - ); - @override - void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), - returnValueForMissingStub: null, - ); - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [ThemeService]. /// /// See the documentation for Mockito's code generation for more information. -class MockThemeService extends _i1.Mock implements _i15.ThemeService { +class MockThemeService extends _i1.Mock implements _i12.ThemeService { MockThemeService() { _i1.throwOnMissingStub(this); } @@ -473,10 +240,10 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { ), ) as _i3.MainDB); @override - List<_i16.StackTheme> get installedThemes => (super.noSuchMethod( + List<_i13.StackTheme> get installedThemes => (super.noSuchMethod( Invocation.getter(#installedThemes), - returnValue: <_i16.StackTheme>[], - ) as List<_i16.StackTheme>); + returnValue: <_i13.StackTheme>[], + ) as List<_i13.StackTheme>); @override void init(_i3.MainDB? db) => super.noSuchMethod( Invocation.method( @@ -486,7 +253,7 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { returnValueForMissingStub: null, ); @override - _i9.Future install({required _i17.Uint8List? themeArchiveData}) => + _i9.Future install({required _i14.Uint8List? themeArchiveData}) => (super.noSuchMethod( Invocation.method( #install, @@ -526,33 +293,33 @@ class MockThemeService extends _i1.Mock implements _i15.ThemeService { returnValue: _i9.Future.value(false), ) as _i9.Future); @override - _i9.Future> fetchThemes() => + _i9.Future> fetchThemes() => (super.noSuchMethod( Invocation.method( #fetchThemes, [], ), - returnValue: _i9.Future>.value( - <_i15.StackThemeMetaData>[]), - ) as _i9.Future>); + returnValue: _i9.Future>.value( + <_i12.StackThemeMetaData>[]), + ) as _i9.Future>); @override - _i9.Future<_i17.Uint8List> fetchTheme( - {required _i15.StackThemeMetaData? themeMetaData}) => + _i9.Future<_i14.Uint8List> fetchTheme( + {required _i12.StackThemeMetaData? themeMetaData}) => (super.noSuchMethod( Invocation.method( #fetchTheme, [], {#themeMetaData: themeMetaData}, ), - returnValue: _i9.Future<_i17.Uint8List>.value(_i17.Uint8List(0)), - ) as _i9.Future<_i17.Uint8List>); + returnValue: _i9.Future<_i14.Uint8List>.value(_i14.Uint8List(0)), + ) as _i9.Future<_i14.Uint8List>); @override - _i16.StackTheme? getTheme({required String? themeId}) => + _i13.StackTheme? getTheme({required String? themeId}) => (super.noSuchMethod(Invocation.method( #getTheme, [], {#themeId: themeId}, - )) as _i16.StackTheme?); + )) as _i13.StackTheme?); } /// A class which mocks [NodeService]. @@ -568,15 +335,15 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ), ) as _i7.SecureStorageInterface); @override - List<_i18.NodeModel> get primaryNodes => (super.noSuchMethod( + List<_i15.NodeModel> get primaryNodes => (super.noSuchMethod( Invocation.getter(#primaryNodes), - returnValue: <_i18.NodeModel>[], - ) as List<_i18.NodeModel>); + returnValue: <_i15.NodeModel>[], + ) as List<_i15.NodeModel>); @override - List<_i18.NodeModel> get nodes => (super.noSuchMethod( + List<_i15.NodeModel> get nodes => (super.noSuchMethod( Invocation.getter(#nodes), - returnValue: <_i18.NodeModel>[], - ) as List<_i18.NodeModel>); + returnValue: <_i15.NodeModel>[], + ) as List<_i15.NodeModel>); @override bool get hasListeners => (super.noSuchMethod( Invocation.getter(#hasListeners), @@ -593,8 +360,8 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i9.Future); @override _i9.Future setPrimaryNodeFor({ - required _i13.Coin? coin, - required _i18.NodeModel? node, + required _i16.Coin? coin, + required _i15.NodeModel? node, bool? shouldNotifyListeners = false, }) => (super.noSuchMethod( @@ -611,40 +378,40 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - _i18.NodeModel? getPrimaryNodeFor({required _i13.Coin? coin}) => + _i15.NodeModel? getPrimaryNodeFor({required _i16.Coin? coin}) => (super.noSuchMethod(Invocation.method( #getPrimaryNodeFor, [], {#coin: coin}, - )) as _i18.NodeModel?); + )) as _i15.NodeModel?); @override - List<_i18.NodeModel> getNodesFor(_i13.Coin? coin) => (super.noSuchMethod( + List<_i15.NodeModel> getNodesFor(_i16.Coin? coin) => (super.noSuchMethod( Invocation.method( #getNodesFor, [coin], ), - returnValue: <_i18.NodeModel>[], - ) as List<_i18.NodeModel>); + returnValue: <_i15.NodeModel>[], + ) as List<_i15.NodeModel>); @override - _i18.NodeModel? getNodeById({required String? id}) => + _i15.NodeModel? getNodeById({required String? id}) => (super.noSuchMethod(Invocation.method( #getNodeById, [], {#id: id}, - )) as _i18.NodeModel?); + )) as _i15.NodeModel?); @override - List<_i18.NodeModel> failoverNodesFor({required _i13.Coin? coin}) => + List<_i15.NodeModel> failoverNodesFor({required _i16.Coin? coin}) => (super.noSuchMethod( Invocation.method( #failoverNodesFor, [], {#coin: coin}, ), - returnValue: <_i18.NodeModel>[], - ) as List<_i18.NodeModel>); + returnValue: <_i15.NodeModel>[], + ) as List<_i15.NodeModel>); @override _i9.Future add( - _i18.NodeModel? node, + _i15.NodeModel? node, String? password, bool? shouldNotifyListeners, ) => @@ -696,7 +463,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { ) as _i9.Future); @override _i9.Future edit( - _i18.NodeModel? editedNode, + _i15.NodeModel? editedNode, String? password, bool? shouldNotifyListeners, ) => @@ -722,7 +489,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( + void addListener(_i17.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #addListener, [listener], @@ -730,7 +497,7 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService { returnValueForMissingStub: null, ); @override - void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( + void removeListener(_i17.VoidCallback? listener) => super.noSuchMethod( Invocation.method( #removeListener, [listener],